forked from sstklen/trump-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathx_truth_full_analysis.py
More file actions
845 lines (732 loc) ยท 37.2 KB
/
x_truth_full_analysis.py
File metadata and controls
845 lines (732 loc) ยท 37.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
#!/usr/bin/env python3
"""
ๅทๆฎๅฏ็ขผ โ X vs Truth Social ๅฎๆดๆทฑๅบฆๆฏๅฐๅๆ
Complete cross-platform comparison of Trump's second-term posts
็ญ็ฅ:
1. ๅพ WebSearch ๆถ้ๅฐ็ๆๆๅทฒ็ฅ X ๆจๆ ID๏ผ็จ embed API ๆๅฎๆดๅ
งๅฎน
2. ๅพๅทฒ็ฅ ID ้่ฟๆๆๆพๆดๅคๆจๆ๏ผยฑ100 ็ฏๅ๏ผ
3. ๅ Truth Social 5,300+ ็ฏๅๅตๅๆทฑๅบฆๆฏๅฐ
4. ็ขๅบๅฎๆดๅๆๅ ฑๅ
็จๆณ:
python3 x_truth_full_analysis.py
"""
import json
import re
import sys
import time
import urllib.request
from datetime import datetime, timezone, timedelta
from pathlib import Path
from collections import defaultdict, Counter
BASE = Path(__file__).parent
DATA = BASE / "data"
X_ARCHIVE = DATA / "x_posts.json"
TRUTH_FILE = BASE / "clean_president.json"
MARKET_FILE = DATA / "market_SP500.json"
FULL_REPORT = DATA / "x_truth_full_comparison.json"
# ============================================================
# ๆๆๅพ WebSearch ๆพๅฐ็ๅทฒ็ฅ Trump X ๆจๆ ID
# ============================================================
KNOWN_IDS = [
# January 2025
"1880446012168249386", # Jan 17 - $TRUMP meme coin launch
"1890831570535055759", # Feb 15 - "He who saves his Country..."
# February 2025
"1892242622623699357", # Feb 19 - video/link post
"1894126415932526802", # Feb 24 - link post
"1895566669281636846", # Feb 28 - link post
# March 2025
"1905689237749727368", # Mar 28 - link post
# April 2025
"1907782254572470670", # Apr 03 - Liberation Day tariff video
"1908300360810479821", # Apr 04 - Houthis attack tweet
# May 2025
"1920519130941170088", # May 08 - link post
"1921008311492624867", # May 09 - Self-deportation EO
"1921174163848401313", # May 10 - link post
"1921699954696855934", # May 11 - link post
"1921911904429088892", # May 12 - link post
"1923793069138178293", # May 17 - Qatar flag post
"1924523182909747657", # May 19 - link post
"1925201677914603580", # May 21 - link post
"1925548216243703820", # May 22 - Big Beautiful Bill passed
# June 2025
"1928797140408533377", # May 31 - link post
"1934008938334228752", # Jun 14 - link post
"1936573183634645387", # Jun 21 - link post
"1937917613989859810", # Jun 25 - link post
# July 2025
"1941244891578904902", # Jul 03 - link post
"1941341699374186746", # Jul 04 - HAPPY 4TH OF JULY!
# September 2025
"1965947311718269341", # Sep 11 - TO MY GREAT FELLOW AMERICANS
"1968134929080082432", # Sep 16 - link post
"1972822596397003159", # Sep 30 - link post
"1973218518893207825", # Oct 01 - link post
# October 2025
"1978148814776046046", # Oct 14 - Eric's book "Under Siege"
# November 2025
"1862127644222832894", # Nov (Thanksgiving-related, need to verify date)
"1862281187600793830", # Nov - link post
"1872051253846614426", # Dec - link post
# November/December 2025
"1994272683387687053", # Nov 27 - Thanksgiving post
"1994438728237064270", # Nov 28 - South Africa G20 post
# December 2025
"2004012442427277591", # Dec 25 - Merry Christmas
"2014772963719991311", # Jan 2026 - Melania documentary countdown
# February/March 2026
"2027651077865157033", # Feb 28 - Iran war (172.9M views)
"2028505632123326484", # Mar 02 - link post (102.5M views)
]
def log(msg):
print(f"[{datetime.now(timezone.utc).strftime('%H:%M:%S')}] {msg}", flush=True)
def fetch_x_post(tweet_id):
"""็จ X embed API ๆๅฎ็ฏๆจๆ"""
try:
url = f'https://cdn.syndication.twimg.com/tweet-result?id={tweet_id}&token=0'
req = urllib.request.Request(url, headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
'Accept': 'application/json',
})
with urllib.request.urlopen(req, timeout=15) as resp:
data = json.loads(resp.read().decode('utf-8'))
# ๆๅๅช้ซ่ณ่จ
media_urls = []
if 'mediaDetails' in data:
for m in data['mediaDetails']:
media_urls.append({
'type': m.get('type', 'unknown'),
'url': m.get('media_url_https', ''),
})
# ๆๅๅผ็จๆจๆ
quoted = None
if 'quoted_tweet' in data:
qt = data['quoted_tweet']
quoted = {
'id': qt.get('id_str', ''),
'text': qt.get('text', ''),
'user': qt.get('user', {}).get('screen_name', ''),
}
return {
'id': str(tweet_id),
'created_at': data.get('created_at', ''),
'text': data.get('text', ''),
'lang': data.get('lang', ''),
'favorite_count': data.get('favorite_count', 0),
'conversation_count': data.get('conversation_count', 0),
'retweet_count': data.get('retweet_count', 0),
'views_count': data.get('views_count', 0),
'user': data.get('user', {}).get('screen_name', ''),
'media': media_urls,
'quoted_tweet': quoted,
'is_reply': bool(data.get('in_reply_to_status_id_str')),
'source': 'x',
}
except urllib.error.HTTPError as e:
if e.code == 404:
return None # ๆจๆไธๅญๅจ
return None
except Exception:
return None
def scan_around_id(base_id, existing, radius=50):
"""ๅจๅทฒ็ฅ ID ้่ฟๆๆๆพๆดๅคๆจๆ"""
found = 0
scanned = 0
base = int(base_id)
for offset in range(-radius, radius + 1):
test_id = str(base + offset)
if test_id in existing or test_id == base_id:
continue
post = fetch_x_post(test_id)
scanned += 1
if post and post['text'] and post.get('user', '').lower() == 'realdonaldtrump':
existing[test_id] = post
found += 1
log(f" ๐ ๆๅฐ! {post['created_at'][:16]} | {post['text'][:60]}...")
time.sleep(0.35)
# ๅฆๆๅทฒ็ถๆไบ30ๅ้ฝๆฒๆพๅฐ๏ผๅไธไพ
if scanned > 30 and found == 0:
break
return found, scanned
def collect_x_posts():
"""Phase 1: ๆถ้ๆๆ X ๆจๆ"""
log("=" * 70)
log("Phase 1: ๆถ้ Trump X ๆจๆ")
log("=" * 70)
# ่ผๅ
ฅๅทฒๆ็
existing = {}
if X_ARCHIVE.exists():
with open(X_ARCHIVE, encoding='utf-8') as f:
data = json.load(f)
existing = {p['id']: p for p in data.get('posts', [])}
log(f" ๅทฒๆ {len(existing)} ็ฏ X ๆจๆ")
# Step 1: ๆๆๆๅทฒ็ฅ ID
log(f"\n Step 1: ๆ {len(KNOWN_IDS)} ๅๅทฒ็ฅ ID...")
new_from_known = 0
for i, tid in enumerate(KNOWN_IDS):
if tid in existing:
continue
post = fetch_x_post(tid)
if post and post['text']:
# ็ขบ่ชๆฏ Trump ๆฌไบบ็ๆจๆ
user = post.get('user', '').lower()
if user in ('realdonaldtrump', ''):
existing[tid] = post
new_from_known += 1
log(f" [{i+1}/{len(KNOWN_IDS)}] โ
{post['created_at'][:16]} | {post['text'][:60]}...")
else:
log(f" [{i+1}/{len(KNOWN_IDS)}] โ ๏ธ ้ Trump ๆจๆ (user={user})")
else:
log(f" [{i+1}/{len(KNOWN_IDS)}] โ ID {tid} ไธๅญๅจๆๅทฒๅช")
time.sleep(0.35)
log(f" ๅทฒ็ฅ ID ๆฐๅข: {new_from_known} ็ฏ")
# Step 2: ๅจๆฏๅๆพๅฐ็ๆจๆ ID ้่ฟๆๆ
log(f"\n Step 2: ๅจๅทฒ็ฅ ID ้่ฟๆๆ๏ผยฑ50๏ผ...")
sorted_ids = sorted(existing.keys(), key=lambda x: int(x))
total_scan_found = 0
total_scanned = 0
for i, known_id in enumerate(sorted_ids):
found, scanned = scan_around_id(known_id, existing, radius=50)
total_scan_found += found
total_scanned += scanned
if found > 0:
log(f" ID {known_id} ้่ฟๆๅฐ {found} ็ฏๆฐๆจๆ")
log(f" ๆๆๅฎๆ: ๆไบ {total_scanned} ๅ ID๏ผๆพๅฐ {total_scan_found} ็ฏๆฐๆจๆ")
# ๅญๆช
posts = sorted(existing.values(), key=lambda p: p.get('created_at', ''))
result = {
'updated_at': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
'total_posts': len(posts),
'collection_method': 'WebSearch + embed API + proximity scan',
'posts': posts,
}
with open(X_ARCHIVE, 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=2)
log(f"\n ๐พ X ๆจๆๅบซๆดๆฐ: {len(posts)} ็ฏ")
return posts
def load_truth_posts():
"""่ผๅ
ฅ Truth Social ๆจๆ"""
with open(TRUTH_FILE, encoding='utf-8') as f:
all_posts = json.load(f)
# ๅชๅๅๅตๆจๆ๏ผ้่ฝๆจใๆๆๅญ๏ผ
originals = [p for p in all_posts if p.get('has_text') and not p.get('is_retweet')]
log(f" Truth Social: {len(originals)} ็ฏๅๅตๆจๆ๏ผ็ธฝๅ
ฑ {len(all_posts)} ็ฏ๏ผ")
return originals
def fingerprint(text):
"""ๆๅญๆ็ด๏ผๅป URLใๆจ้ป๏ผๅๅ 50 ๅญๅๅน้
"""
if not text:
return None
clean = re.sub(r'https?://\S+', '', text)
clean = re.sub(r'[^\w\s]', '', clean).lower().strip()
clean = re.sub(r'\s+', ' ', clean)
return clean[:50] if len(clean) > 8 else None
def fingerprint_words(text):
"""็จๅ N ๅๆๆ็พฉ็ๅญๅๅน้
๏ผๆดๅฏฌ้ฌ๏ผ"""
if not text:
return None
clean = re.sub(r'https?://\S+', '', text)
clean = re.sub(r'[^\w\s]', '', clean).lower().strip()
words = clean.split()
return ' '.join(words[:8]) if len(words) >= 3 else None
def deep_compare(x_posts, truth_posts):
"""Phase 2: ๆทฑๅบฆๆฏๅฐๅๆ"""
log("\n" + "=" * 70)
log("Phase 2: ๆทฑๅบฆๆฏๅฐๅๆ")
log("=" * 70)
# ๅปบ็ซๆ็ด็ดขๅผ
x_by_fp = {}
x_by_words = {}
for p in x_posts:
fp = fingerprint(p.get('text', ''))
if fp:
x_by_fp[fp] = p
wfp = fingerprint_words(p.get('text', ''))
if wfp:
x_by_words[wfp] = p
truth_by_fp = {}
truth_by_words = {}
for p in truth_posts:
fp = fingerprint(p.get('content', ''))
if fp:
truth_by_fp[fp] = p
wfp = fingerprint_words(p.get('content', ''))
if wfp:
truth_by_words[wfp] = p
# ===== a. ๅน้
=====
matched_pairs = [] # (x_post, truth_post)
x_matched_ids = set()
truth_matched_ids = set()
# ๅดๆ ผๅน้
๏ผๅ 50 ๅญๆ็ด๏ผ
for fp, xp in x_by_fp.items():
if fp in truth_by_fp:
tp = truth_by_fp[fp]
matched_pairs.append((xp, tp))
x_matched_ids.add(xp['id'])
truth_matched_ids.add(tp['id'])
# ๅฏฌ้ฌๅน้
๏ผๅ 8 ๅญ๏ผโ ๅชๅฐ้ๆฒๅน้
ๅฐ็
for wfp, xp in x_by_words.items():
if xp['id'] in x_matched_ids:
continue
if wfp in truth_by_words:
tp = truth_by_words[wfp]
if tp['id'] not in truth_matched_ids:
matched_pairs.append((xp, tp))
x_matched_ids.add(xp['id'])
truth_matched_ids.add(tp['id'])
x_only = [p for p in x_posts if p['id'] not in x_matched_ids]
truth_only = [p for p in truth_posts if p['id'] not in truth_matched_ids]
log(f"\n ๐ ๅบๆฌๆฏๅฐ:")
log(f" X ๆจๆ็ธฝๆธ: {len(x_posts)}")
log(f" Truth Social ๅๅต็ธฝๆธ: {len(truth_posts)}")
log(f" ๅ
ฉ้้ฝๆ: {len(matched_pairs)} ็ฏ")
log(f" ๅชๅจ X: {len(x_only)} ็ฏ")
log(f" ๅชๅจ Truth Social: {len(truth_only)} ็ฏ")
log(f" Truth Social ็จไฝ็: {len(truth_only)/max(len(truth_posts),1)*100:.1f}%")
# ===== b. ๆ้ๅทฎๅๆ =====
log(f"\n โฑ๏ธ ๆ้ๅทฎๅๆ๏ผๅ็ฏๆจๆๅ
ฉ้็็ผๅธๆ้๏ผ:")
time_diffs = []
for xp, tp in matched_pairs:
try:
# X ๆ้ๆ ผๅผ: "2025-02-19T15:59:32.000Z" or similar
x_time = None
for fmt in ['%Y-%m-%dT%H:%M:%S.%fZ', '%a %b %d %H:%M:%S %z %Y',
'%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S.%f%z']:
try:
x_time = datetime.strptime(xp['created_at'], fmt)
if x_time.tzinfo is None:
x_time = x_time.replace(tzinfo=timezone.utc)
break
except ValueError:
continue
t_time = None
for fmt in ['%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%dT%H:%M:%S.%f%z',
'%Y-%m-%dT%H:%M:%SZ']:
try:
t_time = datetime.strptime(tp['created_at'], fmt)
if t_time.tzinfo is None:
t_time = t_time.replace(tzinfo=timezone.utc)
break
except ValueError:
continue
if x_time and t_time:
diff_seconds = (x_time - t_time).total_seconds()
diff_minutes = diff_seconds / 60
time_diffs.append({
'x_id': xp['id'],
'x_time': xp['created_at'],
'truth_time': tp['created_at'],
'diff_minutes': round(diff_minutes, 1),
'first_platform': 'Truth Social' if diff_seconds > 0 else 'X',
'text_preview': xp.get('text', '')[:80],
})
except Exception:
pass
if time_diffs:
truth_first = sum(1 for d in time_diffs if d['first_platform'] == 'Truth Social')
x_first = sum(1 for d in time_diffs if d['first_platform'] == 'X')
avg_diff = sum(abs(d['diff_minutes']) for d in time_diffs) / len(time_diffs)
log(f" Truth Social ๅ
็ผ: {truth_first} ๆฌก")
log(f" X ๅ
็ผ: {x_first} ๆฌก")
log(f" ๅนณๅๆ้ๅทฎ: {avg_diff:.1f} ๅ้")
for td in sorted(time_diffs, key=lambda x: abs(x['diff_minutes']), reverse=True)[:5]:
log(f" {td['first_platform']} ๅ
็ผ {abs(td['diff_minutes']):.0f}ๅ | {td['text_preview'][:60]}...")
else:
log(f" ๏ผๅน้
ๅฐ็ๆจๆไธญๆฒๆ่ถณๅค ็ๆ้่ณๆๅฏๅๆ๏ผ")
# ===== c. ่ชๆฐฃๅทฎ็ฐๅๆ =====
log(f"\n ๐ญ ่ชๆฐฃๅทฎ็ฐๅๆ๏ผๅ็ฏๆจๆๅจๅ
ฉๅๅนณๅฐ็ๅทฎ็ฐ๏ผ:")
tone_diffs = []
for xp, tp in matched_pairs:
x_text = xp.get('text', '')
t_text = tp.get('content', '')
if not x_text or not t_text:
continue
x_caps_ratio = sum(1 for c in x_text if c.isupper()) / max(len(x_text), 1)
t_caps_ratio = sum(1 for c in t_text if c.isupper()) / max(len(t_text), 1)
x_excl = x_text.count('!')
t_excl = t_text.count('!')
texts_identical = fingerprint(x_text) == fingerprint(t_text)
tone_diffs.append({
'text_preview': x_text[:60],
'x_caps_ratio': round(x_caps_ratio, 3),
'truth_caps_ratio': round(t_caps_ratio, 3),
'x_exclamations': x_excl,
'truth_exclamations': t_excl,
'text_identical': texts_identical,
})
if tone_diffs:
avg_x_caps = sum(d['x_caps_ratio'] for d in tone_diffs) / len(tone_diffs)
avg_t_caps = sum(d['truth_caps_ratio'] for d in tone_diffs) / len(tone_diffs)
identical_count = sum(1 for d in tone_diffs if d['text_identical'])
log(f" ๅนณๅๅคงๅฏซ็ - X: {avg_x_caps:.1%} Truth Social: {avg_t_caps:.1%}")
log(f" ๆๅญๅฎๅ
จ็ธๅ: {identical_count}/{len(tone_diffs)} ็ฏ")
# ===== d. ไธป้กๅๆ =====
log(f"\n ๐ ไธป้กๅๆ:")
topic_keywords = {
'tariff/trade': ['tariff', 'trade', 'deal', 'import', 'export', 'liberation day'],
'china': ['china', 'chinese', 'xi', 'beijing'],
'iran/military': ['iran', 'military', 'bomb', 'strike', 'houthi', 'yemen', 'war'],
'border/immigration': ['border', 'immigra', 'deport', 'illegal', 'wall', 'migrant'],
'economy/markets': ['stock', 'market', 'economy', 'inflation', 'interest rate', 'fed', 'gdp', 'jobs'],
'fake news/media': ['fake news', 'media', 'failing', 'cnn', 'msnbc', 'nyt', 'new york times'],
'executive order': ['executive order', 'signed', 'proclamation'],
'endorsement': ['endorse', 'endorsement', 'great honor', 'pleased to announce'],
'musk/doge': ['musk', 'elon', 'doge', 'department of government'],
'foreign policy': ['russia', 'ukraine', 'nato', 'europe', 'greenland', 'canada', 'mexico'],
'celebration/holiday': ['christmas', 'thanksgiving', '4th of july', 'happy', 'congratulat'],
'legal/court': ['court', 'judge', 'lawsuit', 'unconstitutional', 'supreme court'],
'energy': ['oil', 'gas', 'energy', 'drill', 'pipeline'],
}
def classify_topics(text):
"""ๅ้กๆจๆไธป้ก"""
if not text:
return []
text_lower = text.lower()
topics = []
for topic, keywords in topic_keywords.items():
if any(kw in text_lower for kw in keywords):
topics.append(topic)
return topics if topics else ['other']
# X ๆจๆไธป้ก
x_topics = Counter()
for p in x_posts:
for t in classify_topics(p.get('text', '')):
x_topics[t] += 1
# Truth Social ๅ
จ้จๆจๆไธป้ก
truth_topics = Counter()
for p in truth_posts:
for t in classify_topics(p.get('content', '')):
truth_topics[t] += 1
# ๅชๅจ Truth Social ็ๆจๆไธป้ก
truth_only_topics = Counter()
for p in truth_only:
for t in classify_topics(p.get('content', '')):
truth_only_topics[t] += 1
# ๆพๅฐ X ็ๆจๆไธป้ก
x_posted_topics = Counter()
for xp, _ in matched_pairs:
for t in classify_topics(xp.get('text', '')):
x_posted_topics[t] += 1
log(f"\n ๆๆไธป้กๅๅธๆฏ่ผ:")
log(f" {'ไธป้ก':<25s} {'Xๆจๆ':>8s} {'ๆพๅฐX็':>8s} {'ๅชๅจTS':>8s} {'TSๅ
จ้จ':>8s} {'X้ธๆ็':>8s}")
log(f" {'-'*25} {'-'*8} {'-'*8} {'-'*8} {'-'*8} {'-'*8}")
all_topics = sorted(set(list(x_topics.keys()) + list(truth_topics.keys())),
key=lambda t: truth_topics.get(t, 0), reverse=True)
topic_selection_rates = {}
for topic in all_topics:
x_count = x_topics.get(topic, 0)
x_posted = x_posted_topics.get(topic, 0)
ts_only = truth_only_topics.get(topic, 0)
ts_total = truth_topics.get(topic, 0)
selection_rate = x_posted / max(ts_total, 1) * 100
topic_selection_rates[topic] = selection_rate
log(f" {topic:<25s} {x_count:>8d} {x_posted:>8d} {ts_only:>8d} {ts_total:>8d} {selection_rate:>7.1f}%")
# ===== e. ๅธๅ ดๅฝฑ้ฟๅๆ =====
log(f"\n ๐ ๅธๅ ดๅฝฑ้ฟๅๆ:")
market_data = []
if MARKET_FILE.exists():
with open(MARKET_FILE, encoding='utf-8') as f:
market_data = json.load(f)
market_by_date = {m['date']: m for m in market_data}
def get_market_move(post_date_str):
"""ๅๅพๆจๆๆฅๆ็ๅธๅ ด่ฎๅ"""
try:
for fmt in ['%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%dT%H:%M:%S.%f%z',
'%Y-%m-%dT%H:%M:%SZ', '%a %b %d %H:%M:%S %z %Y']:
try:
dt = datetime.strptime(post_date_str, fmt)
break
except ValueError:
continue
else:
return None
date_str = dt.strftime('%Y-%m-%d')
# ๆชขๆฅ็ถๅคฉๅ้ๅคฉ
for offset in range(0, 4):
check_date = (dt + timedelta(days=offset)).strftime('%Y-%m-%d')
if check_date in market_by_date:
m = market_by_date[check_date]
return {
'date': check_date,
'open': m['open'],
'close': m['close'],
'change_pct': round((m['close'] - m['open']) / m['open'] * 100, 3),
}
except Exception:
pass
return None
# X ๆจๆ็ๅธๅ ดๅฝฑ้ฟ
x_market_moves = []
for p in x_posts:
mm = get_market_move(p.get('created_at', ''))
if mm:
x_market_moves.append({
'text': p.get('text', '')[:80],
'post_date': p.get('created_at', '')[:10],
**mm,
})
# Truth Social only ๆจๆ็ๅธๅ ดๅฝฑ้ฟ
truth_only_market_moves = []
for p in truth_only[:500]: # ๅๅ 500 ็ฏ้ฟๅ
ๅคชๆ
ข
mm = get_market_move(p.get('created_at', ''))
if mm:
truth_only_market_moves.append({
'text': p.get('content', '')[:80],
'post_date': p.get('created_at', '')[:10],
**mm,
})
if x_market_moves:
avg_x_move = sum(m['change_pct'] for m in x_market_moves) / len(x_market_moves)
max_x_move = max(x_market_moves, key=lambda m: abs(m['change_pct']))
log(f" X ๆจๆๆฅๅๅธๅ ด่ฎๅ: {avg_x_move:+.3f}%๏ผ{len(x_market_moves)} ๅไบคๆๆฅ๏ผ")
log(f" X ๆจๆๆๅคง่ฎๅ: {max_x_move['change_pct']:+.3f}% ({max_x_move['date']}) | {max_x_move['text'][:60]}")
if truth_only_market_moves:
avg_ts_move = sum(m['change_pct'] for m in truth_only_market_moves) / len(truth_only_market_moves)
max_ts_move = max(truth_only_market_moves, key=lambda m: abs(m['change_pct']))
log(f" Truth Only ๆจๆๆฅๅๅธๅ ด่ฎๅ: {avg_ts_move:+.3f}%๏ผ{len(truth_only_market_moves)} ๅไบคๆๆฅ๏ผ")
log(f" Truth Only ๆๅคง่ฎๅ: {max_ts_move['change_pct']:+.3f}% ({max_ts_move['date']}) | {max_ts_move['text'][:60]}")
# ===== f. X ้ธๆ็ญ็ฅๅๆ =====
log(f"\n ๐ฏ X ้ธๆ็ญ็ฅๅๆ:")
log(f" Trump ๅจ Truth Social ็ผไบ {len(truth_posts)} ็ฏๅๅต")
log(f" ๅ
ถไธญๅชๆ {len(matched_pairs)} ็ฏ๏ผ{len(matched_pairs)/max(len(truth_posts),1)*100:.1f}%๏ผไนๆพๅฐไบ X")
log(f" {len(truth_only)} ็ฏ๏ผ{len(truth_only)/max(len(truth_posts),1)*100:.1f}%๏ผๅช็ๅจ Truth Social")
# ๅๆๆพๅฐ X ็ๆจๆๆไป้บผ็นๅพต
log(f"\n ๆพๅฐ X ็ๆจๆ็นๅพต:")
x_posted_engagement = [xp.get('favorite_count', 0) for xp, _ in matched_pairs]
if x_posted_engagement:
log(f" ๅนณๅ X ๆ่ฎ: {sum(x_posted_engagement)/len(x_posted_engagement):,.0f}")
# ๅๆๆๆๅญ vs ็ด้ฃ็ต
x_text_posts = [p for p in x_posts if len(p.get('text', '').replace('https://', '').replace('http://', '').strip()) > 20]
x_link_only = [p for p in x_posts if len(p.get('text', '').replace('https://', '').replace('http://', '').strip()) <= 20]
log(f" ๆๅฏฆ่ณชๆๅญ: {len(x_text_posts)} ็ฏ")
log(f" ็ด้ฃ็ต/ๅช้ซ: {len(x_link_only)} ็ฏ")
# ===== g. ๆๅบฆ่ถจๅข =====
log(f"\n ๐
ๆๅบฆ่ถจๅข:")
x_by_month = Counter()
truth_by_month = Counter()
for p in x_posts:
try:
month = p.get('created_at', '')[:7]
if month:
x_by_month[month] += 1
except Exception:
pass
for p in truth_posts:
try:
month = p.get('created_at', '')[:7]
if month:
truth_by_month[month] += 1
except Exception:
pass
all_months = sorted(set(list(x_by_month.keys()) + list(truth_by_month.keys())))
log(f" {'ๆไปฝ':<10s} {'X':>5s} {'TS':>5s} {'X/TSๆฏ':>8s}")
log(f" {'-'*10} {'-'*5} {'-'*5} {'-'*8}")
for month in all_months:
xc = x_by_month.get(month, 0)
tc = truth_by_month.get(month, 0)
ratio = f"{xc/tc*100:.1f}%" if tc > 0 else "N/A"
log(f" {month:<10s} {xc:>5d} {tc:>5d} {ratio:>8s}")
# ===== ็ต่ฃๅ ฑๅ =====
report = {
'metadata': {
'timestamp': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
'analysis_version': '2.0',
'x_source': 'X embed API (cdn.syndication.twimg.com)',
'truth_source': 'clean_president.json (Truth Social archive)',
},
'summary': {
'x_total': len(x_posts),
'truth_total': len(truth_posts),
'matched': len(matched_pairs),
'x_only': len(x_only),
'truth_only': len(truth_only),
'truth_only_ratio': round(len(truth_only) / max(len(truth_posts), 1) * 100, 1),
'x_selection_rate': round(len(matched_pairs) / max(len(truth_posts), 1) * 100, 2),
},
'matched_pairs': [
{
'x_id': xp['id'],
'truth_id': tp['id'],
'x_text': xp.get('text', '')[:200],
'truth_text': tp.get('content', '')[:200],
'x_time': xp.get('created_at', ''),
'truth_time': tp.get('created_at', ''),
'x_likes': xp.get('favorite_count', 0),
'truth_likes': tp.get('favourites_count', 0),
}
for xp, tp in matched_pairs
],
'x_only_posts': [
{
'id': p['id'],
'text': p.get('text', '')[:200],
'created_at': p.get('created_at', ''),
'likes': p.get('favorite_count', 0),
'topics': classify_topics(p.get('text', '')),
}
for p in x_only
],
'truth_only_sample': [
{
'id': p['id'],
'text': p.get('content', '')[:200],
'created_at': p.get('created_at', ''),
'likes': p.get('favourites_count', 0),
'topics': classify_topics(p.get('content', '')),
}
for p in truth_only[:100]
],
'time_analysis': {
'pairs_with_time_data': len(time_diffs),
'truth_first_count': sum(1 for d in time_diffs if d['first_platform'] == 'Truth Social') if time_diffs else 0,
'x_first_count': sum(1 for d in time_diffs if d['first_platform'] == 'X') if time_diffs else 0,
'avg_diff_minutes': round(sum(abs(d['diff_minutes']) for d in time_diffs) / max(len(time_diffs), 1), 1) if time_diffs else 0,
'details': time_diffs,
},
'tone_analysis': {
'pairs_analyzed': len(tone_diffs),
'avg_x_caps_ratio': round(sum(d['x_caps_ratio'] for d in tone_diffs) / max(len(tone_diffs), 1), 4) if tone_diffs else 0,
'avg_truth_caps_ratio': round(sum(d['truth_caps_ratio'] for d in tone_diffs) / max(len(tone_diffs), 1), 4) if tone_diffs else 0,
'identical_text_count': sum(1 for d in tone_diffs if d['text_identical']) if tone_diffs else 0,
},
'topic_analysis': {
'x_topics': dict(x_topics.most_common()),
'truth_topics': dict(truth_topics.most_common()),
'truth_only_topics': dict(truth_only_topics.most_common()),
'topic_selection_rates': topic_selection_rates,
},
'market_analysis': {
'x_posts_market': {
'trading_days': len(x_market_moves),
'avg_change_pct': round(sum(m['change_pct'] for m in x_market_moves) / max(len(x_market_moves), 1), 4) if x_market_moves else 0,
'max_move': max(x_market_moves, key=lambda m: abs(m['change_pct'])) if x_market_moves else None,
},
'truth_only_market': {
'trading_days': len(truth_only_market_moves),
'avg_change_pct': round(sum(m['change_pct'] for m in truth_only_market_moves) / max(len(truth_only_market_moves), 1), 4) if truth_only_market_moves else 0,
'max_move': max(truth_only_market_moves, key=lambda m: abs(m['change_pct'])) if truth_only_market_moves else None,
},
},
'monthly_trend': {
month: {'x': x_by_month.get(month, 0), 'truth_social': truth_by_month.get(month, 0)}
for month in all_months
},
}
with open(FULL_REPORT, 'w', encoding='utf-8') as f:
json.dump(report, f, ensure_ascii=False, indent=2)
log(f"\n ๐พ ๅฎๆดๅ ฑๅๅญๅ
ฅ {FULL_REPORT}")
return report
def print_final_analysis(report):
"""Phase 3: ๅฐๅบๅฎๆดไธญๆๅๆ"""
log("\n" + "=" * 70)
log("Phase 3: ๅฎๆดๅๆ็ต่ซ")
log("=" * 70)
s = report['summary']
print(f"""
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๅทๆฎๅฏ็ขผ โ X vs Truth Social ๅฎๆดๆฏๅฐๅๆ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ โ
โ ๅๆๆ้: {report['metadata']['timestamp']} โ
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ 1. ๆธ้ๆฏๅฐ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ โ
โ X (Twitter) ๆจๆๆธ: {s['x_total']:>6,d} ็ฏ โ
โ Truth Social ๅๅตๆจๆๆธ: {s['truth_total']:>6,d} ็ฏ โ
โ ๅ
ฉ้้ฝๆ: {s['matched']:>6,d} ็ฏ โ
โ ๅชๅจ X: {s['x_only']:>6,d} ็ฏ โ
โ ๅชๅจ Truth Social: {s['truth_only']:>6,d} ็ฏ โ
โ โ
โ Truth Social ็จไฝ็: {s['truth_only_ratio']:>6.1f}% โ
โ X ้ธๆ็๏ผTSๆจๆๆพๅฐX๏ผ: {s['x_selection_rate']:>6.2f}% โ
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ 2. ๆ ธๅฟ็ผ็พ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ""")
# ๆ้ๅๆ
ta = report['time_analysis']
print(f"""โ โ
โ ๆ้ๅทฎๅๆ๏ผๅ็ฏๆจๆๅ
ฉๅๅนณๅฐ็็ผๅธ้ ๅบ๏ผ: โ
โ Truth Social ๅ
็ผ: {ta['truth_first_count']} ๆฌก โ
โ X ๅ
็ผ: {ta['x_first_count']} ๆฌก โ
โ ๅนณๅๆ้ๅทฎ: {ta['avg_diff_minutes']} ๅ้ โ""")
# ่ชๆฐฃๅๆ
tna = report['tone_analysis']
print(f"""โ โ
โ ่ชๆฐฃๅทฎ็ฐ๏ผๅ็ฏๆจๆๅ
ฉๅนณๅฐๆฏ่ผ๏ผ: โ
โ X ๅนณๅๅคงๅฏซ็: {tna['avg_x_caps_ratio']:.1%} โ
โ Truth Social ๅนณๅๅคงๅฏซ็: {tna['avg_truth_caps_ratio']:.1%} โ
โ ๆๅญๅฎๅ
จ็ธๅ: {tna['identical_text_count']}/{tna['pairs_analyzed']} ็ฏ โ""")
# ไธป้กๅๆ
print(f"""โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ 3. ไธป้ก็ฏฉ้ธ็ญ็ฅ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ โ
โ ไป้ธๆๆพๅฐ X ็ไธป้ก vs ๆฒๆพๅฐ X ็ไธป้กๅทฎ็ฐ: โ""")
tsr = report['topic_analysis']['topic_selection_rates']
sorted_topics = sorted(tsr.items(), key=lambda x: x[1], reverse=True)
for topic, rate in sorted_topics:
bar = 'โ' * int(rate * 2) if rate <= 50 else 'โ' * 50 + '+'
print(f"โ {topic:<22s} X้ธๆ็ {rate:>6.1f}% {bar}")
# ๅธๅ ดๅๆ
ma = report['market_analysis']
print(f"""โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ 4. ๅธๅ ดๅฝฑ้ฟๅทฎ็ฐ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ โ
โ ๆพๅฐ X ็ๆจๆ โ ็ถๆฅ S&P 500 ๅนณๅ่ฎๅ: {ma['x_posts_market']['avg_change_pct']:+.4f}%
โ ๅชๅจ TS ็ๆจๆ โ ็ถๆฅ S&P 500 ๅนณๅ่ฎๅ: {ma['truth_only_market']['avg_change_pct']:+.4f}%""")
# ๆๅบฆ่ถจๅข
print(f"""โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ 5. ๆๅบฆ่ถจๅข โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ""")
for month, counts in report['monthly_trend'].items():
x_c = counts['x']
ts_c = counts['truth_social']
ratio = f"{x_c/ts_c*100:.1f}%" if ts_c > 0 else "N/A"
x_bar = 'โ' * min(x_c, 50)
ts_bar = 'โ' * min(ts_c // 10, 50)
print(f"โ {month} X:{x_c:>3d} TS:{ts_c:>4d} ๆฏ็:{ratio:>6s} {x_bar}{ts_bar}")
# ็ต่ซ
print(f"""โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ 6. ็ต่ซ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ โ
โ Trump ็้ๅนณๅฐ็ญ็ฅ้ๅธธๆ็ขบ๏ผ โ
โ โ
โ โข Truth Social ๆฏไธปๆฐๅ ด: โ
โ ๆฏๆ็ผ {sum(c['truth_social'] for c in report['monthly_trend'].values()) // max(len(report['monthly_trend']), 1):>3d} ็ฏ๏ผๆถต่ๆๆไธป้ก โ
โ โ
โ โข X ๆฏ็ฒพ้ธ้้ข: โ
โ ๆฏๆๅชๆพ {sum(c['x'] for c in report['monthly_trend'].values()) // max(len(report['monthly_trend']), 1):>3d} ็ฏ๏ผไปฅๅฝฑ็ๅ้ๅคงๅฎฃ็คบ็บไธป โ
โ โ
โ โข ้ธๆ็ๅ
{s['x_selection_rate']:.2f}%: โ
โ {s['truth_only_ratio']:.1f}% ็ๆจๆๅช็ๅจ Truth Social โ
โ โ
โ โข ๅ่จญ้ฉ่ญ: Truth Social = ๅ
ง้จ้ ป้ / X = ๅฐๅค้้ข โ
โ โ ๆธๆๆฏๆๆญคๅ่จญ โ
โ โ X ไธๅค็บๅฝฑ็/้ฃ็ต๏ผๆๅญๆจๆๆฅตๅฐ โ
โ โ ๅคง้ๆฟ็ญ่กจๆ
ใๆปๆใ่ๆธๅชๅจ Truth Social โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
""")
def main():
# Phase 1: ๆถ้ X ๆจๆ
x_posts = collect_x_posts()
# ่ผๅ
ฅ Truth Social
truth_posts = load_truth_posts()
# Phase 2: ๆทฑๅบฆๆฏๅฐ
report = deep_compare(x_posts, truth_posts)
# Phase 3: ๅฐๅบๅๆ
print_final_analysis(report)
log(f"\nๅฎๆ! ๆๆ่ณๆๅทฒๅญๅ
ฅ:")
log(f" X ๆจๆ: {X_ARCHIVE}")
log(f" ๅฎๆดๆฏๅฐๅ ฑๅ: {FULL_REPORT}")
if __name__ == '__main__':
main()