File size: 40,155 Bytes
68804db
 
 
 
 
 
 
faef7c4
68804db
 
faef7c4
68804db
 
 
 
 
 
 
 
 
faef7c4
 
68804db
3cf5afe
68804db
 
faef7c4
 
68804db
 
75779bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faef7c4
 
 
 
 
 
 
 
 
 
 
68804db
faef7c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68804db
 
 
 
 
 
 
 
faef7c4
68804db
 
81a0b1a
 
 
75779bf
 
 
 
 
 
81a0b1a
 
75779bf
 
 
 
 
 
 
 
 
81a0b1a
75779bf
 
 
 
 
81a0b1a
 
 
75779bf
 
 
 
 
 
 
 
 
81a0b1a
75779bf
81a0b1a
3cf5afe
 
 
 
a84d30a
faef7c4
a84d30a
 
 
 
faef7c4
 
 
a84d30a
 
faef7c4
 
3cf5afe
a84d30a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faef7c4
a84d30a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faef7c4
3cf5afe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faef7c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68804db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cf5afe
faef7c4
 
 
68804db
 
3cf5afe
faef7c4
 
68804db
faef7c4
3cf5afe
faef7c4
 
 
 
68804db
 
 
faef7c4
 
 
 
 
 
 
68804db
faef7c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cf5afe
faef7c4
68804db
 
3cf5afe
faef7c4
 
 
3cf5afe
faef7c4
fcfba23
faef7c4
68804db
 
 
 
faef7c4
 
68804db
 
faef7c4
 
a84d30a
 
 
 
 
 
 
 
 
68804db
 
 
3cf5afe
faef7c4
 
fcfba23
a84d30a
 
68804db
a84d30a
 
 
 
 
 
 
 
68804db
3cf5afe
faef7c4
 
 
fcfba23
3cf5afe
faef7c4
fcfba23
faef7c4
 
a84d30a
68804db
 
 
 
 
 
 
 
3cf5afe
faef7c4
 
68804db
faef7c4
68804db
 
 
3cf5afe
faef7c4
 
 
3cf5afe
68804db
faef7c4
68804db
 
 
faef7c4
68804db
 
 
 
 
faef7c4
68804db
faef7c4
68804db
 
 
 
faef7c4
 
68804db
 
 
3cf5afe
faef7c4
 
 
68804db
 
faef7c4
 
 
3cf5afe
 
faef7c4
68804db
3cf5afe
68804db
3cf5afe
 
68804db
 
 
 
 
 
 
1728a14
faef7c4
81a0b1a
 
 
 
 
 
 
 
3cf5afe
faef7c4
 
3cf5afe
 
faef7c4
3cf5afe
 
 
 
 
faef7c4
3cf5afe
faef7c4
3cf5afe
faef7c4
3cf5afe
faef7c4
 
 
 
3cf5afe
faef7c4
 
 
 
 
3cf5afe
 
 
 
 
 
 
 
faef7c4
 
3cf5afe
 
fcfba23
 
faef7c4
 
 
3cf5afe
faef7c4
 
3cf5afe
a84d30a
68804db
3cf5afe
 
 
 
 
 
faef7c4
 
3cf5afe
 
faef7c4
3cf5afe
 
 
faef7c4
 
 
 
 
3cf5afe
68804db
faef7c4
 
 
3cf5afe
68804db
faef7c4
 
 
3cf5afe
68804db
faef7c4
 
 
3cf5afe
68804db
 
 
81a0b1a
 
 
 
3cf5afe
faef7c4
3cf5afe
 
 
 
faef7c4
 
 
 
 
3cf5afe
 
faef7c4
 
 
 
3cf5afe
 
faef7c4
 
 
 
3cf5afe
 
faef7c4
 
68804db
3cf5afe
 
 
 
faef7c4
 
fcfba23
68804db
faef7c4
 
 
 
 
 
 
68804db
faef7c4
68804db
 
 
3cf5afe
68804db
3cf5afe
a84d30a
68804db
 
3cf5afe
 
faef7c4
68804db
faef7c4
c29f743
faef7c4
 
3cf5afe
faef7c4
 
 
 
 
3cf5afe
 
 
faef7c4
fcfba23
faef7c4
fcfba23
faef7c4
 
 
 
 
 
68804db
faef7c4
68804db
faef7c4
3cf5afe
 
faef7c4
 
 
 
3cf5afe
faef7c4
 
 
 
 
 
 
3cf5afe
 
 
faef7c4
fcfba23
faef7c4
fcfba23
faef7c4
 
 
 
 
 
 
 
 
3cf5afe
faef7c4
 
 
 
3cf5afe
faef7c4
 
 
 
 
 
 
3cf5afe
 
 
faef7c4
 
fcfba23
68804db
faef7c4
 
 
68804db
faef7c4
 
3cf5afe
faef7c4
 
 
 
 
 
 
3cf5afe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faef7c4
68804db
 
3cf5afe
 
 
 
68804db
faef7c4
68804db
 
 
faef7c4
3cf5afe
 
 
faef7c4
 
68804db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faef7c4
68804db
faef7c4
3cf5afe
68804db
faef7c4
 
68804db
 
 
 
faef7c4
3cf5afe
faef7c4
3cf5afe
68804db
 
 
3cf5afe
68804db
 
 
3cf5afe
68804db
3cf5afe
faef7c4
 
68804db
3cf5afe
68804db
 
 
3cf5afe
68804db
 
faef7c4
3cf5afe
 
 
68804db
 
 
 
 
 
faef7c4
68804db
 
 
75779bf
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
import gradio as gr
import pandas as pd
import numpy as np
import warnings
import plotly.graph_objects as go
import re
from collections import Counter
from itertools import combinations
warnings.filterwarnings('ignore')

# ==================== STOP WORDS ====================
PERSIAN_STOP_WORDS = set([
    'و', 'در', 'به', 'از', 'که', 'این', 'را', 'با', 'است', 'برای',
    'آن', 'یک', 'خود', 'تا', 'کرد', 'بر', 'هم', 'نیز', 'اما', 'یا',
    'اگر', 'همه', 'بود', 'شد', 'می', 'هر', 'ما', 'او', 'ها', 'های',
    'شده', 'کند', 'باید', 'دارد', 'داد', 'بی', 'نه', 'هیچ', 'چه',
    'وی', 'آنها', 'ان', 'پس', 'چون', 'پیش', 'دو', 'سه', 'چهار',
    'شود', 'کرده', 'بوده', 'داشت', 'شدن', 'کنند', 'دهد', 'گفت',
    'نمی', 'خواهد', 'کنیم', 'دارند', 'شده‌اند', 'بودند', 'کردند',
    'ولی', 'چنین', 'نشده', 'کنم', 'هستند', 'درباره', 'بیش', 'کم',
    'بین', 'زیر', 'بالای', 'طی', 'حتی', 'مورد', 'جز', 'علیه', 'روی',
    'هنوز', 'فقط', 'هم‌چنین', 'همچنین', 'البته', 'اکنون', 'دیگر',
    'ایسنا', 'isna', 'isna_farsi', 'خبرگزاری', 'گزارش', 'اعلام',
    'خبر', 'منتشر', 'اینکه', 'گفته', 'طبق', 'براساس',
    'https', 'http', 'rt', 'co', 'amp', 't', 'the', 'of', 'in',
    'a', 'to', 'is', 'and', 'for', 'on', 'that', 'are', 'was',
    'it', 'with', 'he', 'she', 'they', 'we', 'i', 'you', 'at',
    'this', 'by', 'an', 'be', 'from', 'or', 'but', 'not', 'has',
])

PERSIAN_LANGUAGE_WORDS = set([
    'و', 'در', 'به', 'از', 'که', 'این', 'را', 'با', 'است', 'برای',
    'آن', 'یک', 'خود', 'تا', 'کرد', 'بر', 'هم', 'نیز', 'اما', 'یا',
    'اگر', 'همه', 'بود', 'شد', 'می', 'هر', 'ما', 'او', 'ها', 'های',
    'شود', 'کرده', 'دارد', 'گفت', 'نمی', 'خواهد', 'کنیم', 'دارند',
    'ایران', 'خبر', 'گزارش', 'امروز', 'درباره', 'مردم', 'کشور'
])

ARABIC_LANGUAGE_WORDS = set([
    'و', 'في', 'من', 'على', 'إلى', 'الى', 'عن', 'أن', 'ان', 'إن',
    'هذا', 'هذه', 'ذلك', 'تلك', 'الذي', 'التي', 'الذين', 'كان',
    'كانت', 'يكون', 'لا', 'ما', 'مع', 'كما', 'بعد', 'قبل', 'بين',
    'اليوم', 'قال', 'الله', 'الناس', 'الدولة', 'البلاد', 'خبر'
])

ENGLISH_LANGUAGE_WORDS = set([
    'the', 'of', 'in', 'a', 'to', 'is', 'and', 'for', 'on', 'that',
    'are', 'was', 'it', 'with', 'he', 'she', 'they', 'we', 'i', 'you',
    'at', 'this', 'by', 'an', 'be', 'from', 'or', 'but', 'not', 'has',
    'have', 'as', 'will', 'can', 'about', 'news', 'today', 'people'
])

# الگوهای بازنشر خبر ایسنا
ISNA_NEWS_PATTERNS = [
    r'/ایسنا',
    r'به گزارش ایسنا',
    r'به نقل از ایسنا',
    r'منبع:\s*ایسنا',
    r'به گزارش خبرگزاری ایسنا',
    r'ایسنا نوشت',
    r'ایسنا:',
]
ISNA_PATTERN_COMBINED = '|'.join(ISNA_NEWS_PATTERNS)

# ==================== توابع کمکی ====================

def format_number(n):
    try:
        return f"{int(n):,}"
    except:
        return '۰'

def parse_date_range(df):
    if 'روز انتشار شمسی' not in df.columns:
        return '—', '—'
    dates = sorted(df['روز انتشار شمسی'].dropna().unique())
    if not dates:
        return '—', '—'
    return dates[0], dates[-1]

def clean_text(text):
    if pd.isna(text):
        return ''
    text = str(text)
    text = re.sub(r'https?://\S+', '', text)
    text = re.sub(r'@\S+', '', text)
    text = re.sub(r'#', '', text)
    text = re.sub(r'[^\w\s\u0600-\u06FF]', ' ', text)
    text = re.sub(r'\d+', '', text)
    text = re.sub(r'\s+', ' ', text)
    return text.strip()

def detect_text_language(text):
    if pd.isna(text):
        return 'سایر'
    text = re.sub(r'https?://\S+|@\S+|#', ' ', str(text).lower())
    text = re.sub(r'\d+', ' ', text)
    text = re.sub(r'\s+', ' ', text).strip()
    if not text:
        return 'سایر'

    latin_count = len(re.findall(r'[A-Za-z]', text))
    arabic_script_count = len(re.findall(r'[\u0600-\u06FF]', text))
    useful_chars = latin_count + arabic_script_count
    if useful_chars < 3:
        return 'سایر'

    tokens = re.findall(r'[A-Za-z]+|[\u0600-\u06FF]+', text)
    english_hits = sum(1 for t in tokens if t in ENGLISH_LANGUAGE_WORDS)
    persian_hits = sum(1 for t in tokens if t in PERSIAN_LANGUAGE_WORDS)
    arabic_hits = sum(1 for t in tokens if t in ARABIC_LANGUAGE_WORDS)

    persian_specific = len(re.findall(r'[پچژگکی]', text))
    arabic_specific = len(re.findall(r'[أإؤئءةىيىك]', text))

    english_score = latin_count + english_hits * 8
    persian_score = arabic_script_count + persian_specific * 6 + persian_hits * 8
    arabic_score = arabic_script_count + arabic_specific * 6 + arabic_hits * 8

    if arabic_script_count == 0 and latin_count == 0:
        return 'سایر'
    if latin_count >= 4 and english_score > max(persian_score, arabic_score) * 1.2:
        return 'انگلیسی'
    if arabic_script_count >= 4:
        if arabic_score >= persian_score + 10 and arabic_hits >= 1:
            return 'عربی'
        if persian_score >= arabic_score + 4 or persian_specific > 0 or persian_hits >= 1:
            return 'فارسی'
        return 'سایر'
    if latin_count >= 4:
        return 'انگلیسی'
    return 'سایر'

def is_valid_word(w):
    """کلمه معتبر: حداقل ۳ حرف و در لیست stop words نباشد"""
    return len(w) >= 3 and w.lower() not in PERSIAN_STOP_WORDS

def get_ngrams_adjusted(df, top_n=20, min_count=2, max_ngram=8):
    """
    استخراج عبارات پرتکرار ۲ تا max_ngram کلمه‌ای (بدون تک‌کلمه).
    - عبارات بلند‌تر از اجزای کوتاه‌تر کسر می‌شوند.
    - حداقل طول کلمه: ۳ حرف.
    - تک‌کلمه‌ای‌ها نمایش داده نمی‌شوند.
    """
    all_texts = df['متن'].apply(clean_text).tolist()

    # شمارش همه n-gram های ۲ تا max_ngram
    ngram_counters = {n: Counter() for n in range(2, max_ngram + 1)}

    for text in all_texts:
        words = [w for w in text.split() if is_valid_word(w)]
        for n in range(2, max_ngram + 1):
            for i in range(len(words) - n + 1):
                ngram_counters[n][' '.join(words[i:i+n])] += 1

    # فیلتر: حداقل min_count بار تکرار، از بزرگ به کوچک
    filtered = {n: Counter({k: v for k, v in c.items() if v >= min_count})
                for n, c in ngram_counters.items()}

    # کسر تکرار عبارات بلندتر از کوتاه‌تر (از بزرگترین شروع)
    for n in range(max_ngram, 2, -1):
        for phrase, count in filtered[n].items():
            if count == 0:
                continue
            ws = phrase.split()
            # از همه اندازه‌های کوچکتر کسر کن
            for m in range(2, n):
                for i in range(len(ws) - m + 1):
                    sub = ' '.join(ws[i:i+m])
                    if sub in filtered[m]:
                        filtered[m][sub] = max(0, filtered[m][sub] - count)

    # ترکیب همه (بدون تک‌کلمه)
    all_phrases = Counter()
    for n in range(2, max_ngram + 1):
        all_phrases.update({k: v for k, v in filtered[n].items() if v >= min_count})

    # حذف overlap: اگر دو عبارت کلمات مشترک دارند و تعداد تکرارشان نزدیک است،
    # فقط بلندترین را نگه دار
    phrases_sorted = sorted(all_phrases.items(), key=lambda x: (-x[1], -len(x[0].split())))
    kept = []
    for phrase, count in phrases_sorted:
        phrase_words = set(phrase.split())
        # بررسی overlap با عبارات قبلاً نگه‌داشته‌شده
        dominated = False
        for kp, kc in kept:
            kp_words = set(kp.split())
            overlap = len(phrase_words & kp_words)
            union = len(phrase_words | kp_words)
            # اگر بیش از ۶۰٪ کلمات مشترک و تعداد تکرار مشابه → این عبارت حذف شود
            if overlap / union > 0.4 and abs(count - kc) <= 2:
                dominated = True
                break
        if not dominated:
            kept.append((phrase, count))

    return kept[:top_n]

def get_hourly_top_words(df, hour, top_n=3):
    """پرتکرارترین کلمات در یک ساعت مشخص"""
    texts = df[df['ساعت'] == hour]['متن'].apply(clean_text)
    words = []
    for t in texts:
        words += [w for w in t.split() if is_valid_word(w)]
    return [w for w, _ in Counter(words).most_common(top_n)]

def generate_heatmap_insights(df):
    """تولید توضیح داینامیک برای heatmap"""
    df = df.copy()
    df['ساعت'] = df['زمان انتشار'].apply(
        lambda x: int(str(x).split(':')[0]) if pd.notna(x) and ':' in str(x) else None
    )
    df = df.dropna(subset=['ساعت'])
    df['ساعت'] = df['ساعت'].astype(int)

    hourly_counts = df['ساعت'].value_counts()
    if hourly_counts.empty:
        return ''

    # پیک ساعتی
    peak_hour = int(hourly_counts.idxmax())
    peak_count = int(hourly_counts.max())
    peak_words = get_hourly_top_words(df, peak_hour)

    # سه ساعت پرتوییت
    top3_hours = hourly_counts.nlargest(3)

    bullets = []
    bullets.append(
        f"پیک توییت در ساعت <b>{peak_hour}:00</b> با <b>{peak_count}</b> توییت بوده؛ "
        f"پرتکرارترین موضوعات: {' ، '.join(peak_words) if peak_words else '—'}"
    )

    for h, cnt in top3_hours.items():
        h = int(h)
        if h == peak_hour:
            continue
        words = get_hourly_top_words(df, h)
        if words:
            bullets.append(
                f"ساعت <b>{h}:00</b> ({cnt} توییت): بیشتر درباره {' ، '.join(words)} صحبت شد"
            )

    # ساعت با کمترین فعالیت
    low_hour = int(hourly_counts.idxmin())
    low_count = int(hourly_counts.min())
    if low_count == 0:
        bullets.append(f"در ساعت <b>{low_hour}:00</b> هیچ توییتی ثبت نشده است")
    else:
        bullets.append(f"کمترین فعالیت در ساعت <b>{low_hour}:00</b> با <b>{low_count}</b> توییت")

    return bullets

def classify_tweets(df):
    df = df.copy()
    df['نوع_تعامل'] = 'سایر'
    df.loc[
        df['متن'].str.contains(ISNA_PATTERN_COMBINED, case=False, na=False, regex=True),
        'نوع_تعامل'
    ] = 'بازنشر_خبر'
    df.loc[
        (df['نوع_تعامل'] == 'سایر') &
        df['در پاسخ به کاربر'].str.contains('isna_farsi', case=False, na=False),
        'نوع_تعامل'
    ] = 'کامنت_ایسنا'
    df.loc[
        (df['نوع_تعامل'] == 'سایر') &
        df['منشن ها'].str.contains('isna_farsi', case=False, na=False),
        'نوع_تعامل'
    ] = 'منشن_مستقل'
    return df

# ==================== نمودارها ====================

def create_hourly_chart(df):
    df = df.copy()
    df['ساعت'] = df['زمان انتشار'].apply(
        lambda x: int(str(x).split(':')[0]) if pd.notna(x) and ':' in str(x) else None
    )
    hourly = df['ساعت'].value_counts().sort_index().reset_index()
    hourly.columns = ['ساعت', 'تعداد']
    all_hours = pd.DataFrame({'ساعت': range(24)})
    hourly = all_hours.merge(hourly, on='ساعت', how='left').fillna(0)

    fig = go.Figure()
    fig.add_trace(go.Bar(
        x=hourly['ساعت'], y=hourly['تعداد'],
        marker=dict(color=hourly['تعداد'], colorscale='Blues', showscale=False,
                    line=dict(width=0.5, color='#1565c0')),
        hovertemplate='<b>ساعت %{x}</b>: %{y} توییت<extra></extra>'
    ))
    fig.update_layout(
        title={'text': 'توزیع توییت‌ها بر اساس ساعت انتشار',
               'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'},
               'x': 0.5, 'xanchor': 'center'},
        xaxis_title='ساعت', yaxis_title='تعداد توییت',
        font=dict(family='Tahoma', size=13, color='#212121'),
        height=370, plot_bgcolor='rgba(240,245,255,0.6)', paper_bgcolor='white',
        xaxis=dict(tickmode='linear', dtick=1, gridcolor='rgba(150,150,150,0.2)',
                   tickfont=dict(color='#212121')),
        yaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121')),
        margin=dict(l=50, r=30, t=60, b=50)
    )
    return fig

def create_hourly_words_heatmap(df, top_n_words=10):
    df = df.copy()
    df['ساعت'] = df['زمان انتشار'].apply(
        lambda x: int(str(x).split(':')[0]) if pd.notna(x) and ':' in str(x) else None
    )
    df = df.dropna(subset=['ساعت'])
    df['ساعت'] = df['ساعت'].astype(int)

    top_phrases = get_ngrams_adjusted(df, top_n=top_n_words)
    if not top_phrases:
        return go.Figure()
    top_words = [p[0] for p in top_phrases]

    hours = sorted(df['ساعت'].unique())
    matrix = []
    for word in top_words:
        row = []
        for h in hours:
            texts = df[df['ساعت'] == h]['متن'].apply(clean_text)
            count = sum(1 for t in texts if word in t)
            row.append(count)
        matrix.append(row)

    fig = go.Figure(go.Heatmap(
        z=matrix,
        x=[f'{h}:00' for h in hours],
        y=top_words,
        colorscale='Blues',
        hovertemplate='ساعت %{x}<br>عبارت: %{y}<br>تعداد توییت: %{z}<extra></extra>',
        colorbar=dict(title='تعداد', tickfont=dict(color='#212121'))
    ))
    fig.update_layout(
        title={'text': 'در هر ساعت بیشتر از چه صحبت شد؟',
               'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'},
               'x': 0.5, 'xanchor': 'center'},
        font=dict(family='Tahoma', size=12, color='#212121'),
        height=420, paper_bgcolor='white', plot_bgcolor='white',
        xaxis=dict(tickfont=dict(color='#212121'), title='ساعت'),
        yaxis=dict(tickfont=dict(color='#212121', size=11)),
        margin=dict(l=130, r=30, t=60, b=60)
    )
    return fig

def create_words_chart(df):
    top_phrases = get_ngrams_adjusted(df, top_n=20)
    if not top_phrases:
        return go.Figure()

    labels = [p[0] for p in top_phrases][::-1]
    counts = [p[1] for p in top_phrases][::-1]

    def phrase_color(l):
        n = len(l.split())
        if n == 2: return '#00897b'
        elif n == 3: return '#6a1b9a'
        elif n == 4: return '#c62828'
        else: return '#e65100'   # ۵ کلمه و بیشتر

    colors = [phrase_color(l) for l in labels]

    fig = go.Figure()
    fig.add_trace(go.Bar(
        y=labels, x=counts, orientation='h',
        marker=dict(color=colors, line=dict(width=0.5, color='white')),
        text=counts, textposition='outside',
        textfont=dict(color='#212121', size=14),
        hovertemplate='<b>%{y}</b>: %{x} بار<extra></extra>',
        showlegend=False
    ))
    # legend جداگانه با scatter (بدون trace اضافه روی نمودار)
    for color, label in [('#00897b', 'دوکلمه‌ای'), ('#6a1b9a', 'سه‌کلمه‌ای'),
                         ('#c62828', 'چهارکلمه‌ای'), ('#e65100', '۵+ کلمه')]:
        fig.add_trace(go.Scatter(
            x=[None], y=[None], mode='markers',
            marker=dict(size=12, color=color, symbol='square'),
            name=label, showlegend=True
        ))
    fig.update_layout(
        title={'text': 'پرتکرارترین عبارات در توییت‌ها',
               'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'},
               'x': 0.5, 'xanchor': 'center'},
        xaxis_title='تعداد تکرار',
        font=dict(family='Tahoma', size=16, color='#212121'),
        height=580, plot_bgcolor='rgba(240,245,255,0.6)', paper_bgcolor='white',
        xaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121')),
        yaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121', size=14)),
        legend=dict(orientation='h', yanchor='bottom', y=1.01, xanchor='center', x=0.5,
                    font=dict(color='#212121')),
        margin=dict(l=200, r=80, t=80, b=50)
    )
    return fig

def create_content_type_chart(df):
    content_counts = df['نوع محتوا'].value_counts()
    labels_map = {'text': 'متن', 'photo': 'عکس', 'video': 'ویدئو'}
    labels = [labels_map.get(l, l) for l in content_counts.index]
    fig = go.Figure(go.Pie(
        labels=labels, values=content_counts.values, hole=0.45,
        marker=dict(colors=['#1565c0', '#2e7d32', '#e65100'],
                    line=dict(color='white', width=2)),
        textinfo='label+percent',
        textfont=dict(size=14, family='Tahoma', color='#212121'),
        hovertemplate='%{label}: %{value} توییت (%{percent})<extra></extra>'
    ))
    fig.update_layout(
        title={'text': 'توزیع نوع محتوای توییت‌ها',
               'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'},
               'x': 0.5, 'xanchor': 'center'},
        font=dict(family='Tahoma', size=13, color='#212121'),
        height=360, paper_bgcolor='white',
        margin=dict(l=20, r=20, t=60, b=20),
        legend=dict(font=dict(family='Tahoma', size=13, color='#212121'))
    )
    return fig

# ==================== تابع اصلی ====================

def process_twitter_data(file):
    try:
        import io
        try:
            df = pd.read_excel(io.BytesIO(file) if isinstance(file, bytes) else file)
        except Exception:
            df = pd.read_excel(io.BytesIO(file) if isinstance(file, bytes) else file, engine='openpyxl')

        required = ['متن', 'نام کاربری', 'تعداد بازنشر', 'تعداد لایک']
        missing = [c for c in required if c not in df.columns]
        if missing:
            err = f"<div style='direction:rtl;font-family:Tahoma;padding:20px;color:#b71c1c;'>❌ ستون‌های مفقود: {', '.join(missing)}</div>"
            return err, None, None, None, None

        # پاکسازی
        df['تعداد بازنشر'] = pd.to_numeric(df['تعداد بازنشر'], errors='coerce').fillna(0)
        df['تعداد لایک']   = pd.to_numeric(df['تعداد لایک'],   errors='coerce').fillna(0)
        follower_col = 'تعداد دنبال کننده\u200cها'
        if follower_col in df.columns:
            df[follower_col] = pd.to_numeric(df[follower_col], errors='coerce').fillna(0)
        df['تعامل_کل'] = df['تعداد بازنشر'] + df['تعداد لایک']

        # تفکیک نوع تعامل
        df = classify_tweets(df)
        count_news_share = (df['نوع_تعامل'] == 'بازنشر_خبر').sum()
        count_comment    = (df['نوع_تعامل'] == 'کامنت_ایسنا').sum()
        count_mention    = (df['نوع_تعامل'] == 'منشن_مستقل').sum()

        date_from, date_to = parse_date_range(df)
        total         = len(df)
        total_retweet = int(df['تعداد بازنشر'].sum())
        total_like    = int(df['تعداد لایک'].sum())
        unique_users  = df['نام کاربری'].nunique()

        # نوع محتوا
        content_dist = ''
        if 'نوع محتوا' in df.columns:
            for ct, cnt in df['نوع محتوا'].value_counts().items():
                label = {'text': 'متن', 'photo': 'عکس', 'video': 'ویدئو'}.get(ct, ct)
                pct = round(cnt / total * 100)
                content_dist += f"<span style='margin-left:18px; color:#212121;'>{label}: <b style='color:#212121;'>{cnt}</b> ({pct}%)</span>"

        # توزیع زبان متن توییت‌ها
        language_counts = df['متن'].apply(detect_text_language).value_counts()
        language_dist = ''
        for lang in ['فارسی', 'انگلیسی', 'عربی', 'سایر']:
            cnt = int(language_counts.get(lang, 0))
            pct = round(cnt / total * 100, 1) if total else 0
            language_dist += f"<span style='margin-left:18px; color:#212121;'>{lang}: <b style='color:#212121;'>{format_number(cnt)}</b> ({pct}%)</span>"

        # پرتعامل‌ترین توییت‌ها
        top_tweets = df.nlargest(10, 'تعامل_کل').copy()

        # فعال‌ترین کاربران
        agg_dict = {'متن': 'count', 'تعامل_کل': 'sum'}
        if follower_col in df.columns:
            agg_dict[follower_col] = 'max'
        user_agg = df.groupby('نام کاربری').agg(agg_dict).reset_index()
        user_agg.columns = ['نام کاربری', 'تعداد_توییت', 'تعامل_کل'] + ([follower_col] if follower_col in df.columns else [])
        sort_cols = ['تعداد_توییت', follower_col] if follower_col in df.columns else ['تعداد_توییت']
        user_agg = user_agg.sort_values(sort_cols, ascending=False)

        # بازنشردهندگان خبر ایسنا
        df_news = df[df['نوع_تعامل'] == 'بازنشر_خبر']
        news_sharers = pd.DataFrame()
        if follower_col in df.columns and len(df_news) > 0:
            ns = df_news.groupby('نام کاربری').agg(
                تعداد_توییت=('متن', 'count'),
                فالوور=(follower_col, 'max'),
                بازنشر_کل=('تعداد بازنشر', 'sum')
            ).reset_index().sort_values('فالوور', ascending=False).head(10)
            news_sharers = ns

        # توییت‌های ایسنا با بیشترین کامنت
        df_comments = df[df['نوع_تعامل'] == 'کامنت_ایسنا'].copy()
        isna_tweet_comments = pd.DataFrame()
        if 'در پاسخ به این پیام' in df_comments.columns and len(df_comments) > 0:
            cc = df_comments.groupby('در پاسخ به این پیام').size().reset_index()
            cc.columns = ['تیتر_توییت_ایسنا', 'تعداد_کامنت']
            isna_tweet_comments = cc.sort_values('تعداد_کامنت', ascending=False).head(8)

        # توضیح داینامیک heatmap
        heatmap_bullets = []
        if 'زمان انتشار' in df.columns:
            heatmap_bullets = generate_heatmap_insights(df)

        # ==================== ساخت HTML ====================
        C  = "#212121"   # رنگ متن اصلی - تقریباً مشکی
        CS = "#37474f"   # رنگ متن ثانوی
        TD = f"style='padding:10px 14px; border:1px solid #cfd8dc; text-align:right; color:{C}; font-size:15px;'"
        TH = f"style='padding:11px 14px; border:1px solid #1565c0; text-align:right; color:white; font-weight:bold; font-size:16px;'"

        html = f"""
        <div style='direction:rtl; font-family:Tahoma,Arial; text-align:right; padding:24px;
                    background:white; color:{C}; line-height:1.8;'>

            <h2 style='text-align:center; color:#0d47a1; border-bottom:3px solid #1565c0;
                       padding-bottom:12px; font-size:22px; margin-bottom:6px;'>
                گزارش تحلیل توییتر ایسنا
            </h2>
            <p style='text-align:center; color:{CS}; font-size:14px; margin-top:4px;'>
                بازه زمانی: <b style='color:{C};'>{date_from}</b> تا <b style='color:{C};'>{date_to}</b>
            </p>
            <p style='text-align:center; color:{CS}; font-size:12px; margin-top:6px; margin-bottom:0;'>
                تدوین: فاطمه نظرمحمدی &nbsp;|&nbsp; بازبینی: مهناز محمدی‌زادگان
                <br>اداره نظارت و ارزیابی، خبرگزاری دانشجویان ایران (ایسنا)
            </p>

            <hr style='border:none; border-top:1px solid #e0e0e0; margin:20px 0;'>

            <!-- ===== آمار کلی ===== -->
            <h3 style='color:#1a237e; margin-top:20px; font-size:17px;
                       border-right:4px solid #1565c0; padding-right:10px;'>
                آمار کلی
            </h3>
            <div style='display:flex; flex-wrap:wrap; gap:14px; margin:14px 0 20px 0;'>
                <div style='flex:1; min-width:130px; background:#e3f2fd; border-radius:10px;
                            padding:16px 12px; text-align:center; border-top:4px solid #1565c0;'>
                    <div style='font-size:28px; font-weight:bold; color:#0d47a1;'>{format_number(total)}</div>
                    <div style='font-size:13px; color:{CS}; margin-top:6px;'>کل توییت‌ها</div>
                </div>
                <div style='flex:1; min-width:130px; background:#e8f5e9; border-radius:10px;
                            padding:16px 12px; text-align:center; border-top:4px solid #2e7d32;'>
                    <div style='font-size:28px; font-weight:bold; color:#1b5e20;'>{format_number(total_retweet)}</div>
                    <div style='font-size:13px; color:{CS}; margin-top:6px;'>مجموع بازنشر</div>
                </div>
                <div style='flex:1; min-width:130px; background:#fff8e1; border-radius:10px;
                            padding:16px 12px; text-align:center; border-top:4px solid #f9a825;'>
                    <div style='font-size:28px; font-weight:bold; color:#e65100;'>{format_number(total_like)}</div>
                    <div style='font-size:13px; color:{CS}; margin-top:6px;'>مجموع لایک</div>
                </div>
                <div style='flex:1; min-width:130px; background:#fce4ec; border-radius:10px;
                            padding:16px 12px; text-align:center; border-top:4px solid #c62828;'>
                    <div style='font-size:28px; font-weight:bold; color:#b71c1c;'>{format_number(unique_users)}</div>
                    <div style='font-size:13px; color:{CS}; margin-top:6px;'>کاربران یکتا</div>
                </div>
            </div>

            <div style='background:#f5f5f5; border-radius:8px; padding:12px 16px; margin:10px 0 10px 0; font-size:14px; color:{C};'>
                توزیع زبان متن توییت‌ها: {language_dist}
            </div>

            {"<div style='background:#f5f5f5; border-radius:8px; padding:12px 16px; margin:10px 0 20px 0; font-size:14px; color:" + C + ";'>نوع محتوا: " + content_dist + "</div>" if content_dist else ""}

            <!-- ===== تفکیک نوع تعامل ===== -->
            <h3 style='color:#1a237e; margin-top:28px; font-size:17px;
                       border-right:4px solid #1565c0; padding-right:10px;'>
                نوع تعامل با ایسنا
            </h3>
            <div style='display:flex; flex-wrap:wrap; gap:14px; margin:14px 0 24px 0;'>
                <div style='flex:1; min-width:140px; background:#e8f5e9; border-radius:10px;
                            padding:16px 12px; text-align:center; border-top:4px solid #2e7d32;'>
                    <div style='font-size:26px; font-weight:bold; color:#1b5e20;'>{format_number(count_news_share)}</div>
                    <div style='font-size:13px; color:{CS}; margin-top:6px;'>بازنشر خبر ایسنا</div>
                    <div style='font-size:11px; color:#546e7a; margin-top:3px;'>محتوا با منبع ایسنا</div>
                </div>
                <div style='flex:1; min-width:140px; background:#fff3e0; border-radius:10px;
                            padding:16px 12px; text-align:center; border-top:4px solid #e65100;'>
                    <div style='font-size:26px; font-weight:bold; color:#bf360c;'>{format_number(count_comment)}</div>
                    <div style='font-size:13px; color:{CS}; margin-top:6px;'>کامنت به توییت ایسنا</div>
                    <div style='font-size:11px; color:#546e7a; margin-top:3px;'>ریپلای مستقیم</div>
                </div>
                <div style='flex:1; min-width:140px; background:#f3e5f5; border-radius:10px;
                            padding:16px 12px; text-align:center; border-top:4px solid #6a1b9a;'>
                    <div style='font-size:26px; font-weight:bold; color:#4a148c;'>{format_number(count_mention)}</div>
                    <div style='font-size:13px; color:{CS}; margin-top:6px;'>تگ مستقل ایسنا</div>
                    <div style='font-size:11px; color:#546e7a; margin-top:3px;'>منشن بدون ریپلای</div>
                </div>
            </div>

            <!-- ===== پرتعامل‌ترین توییت‌ها ===== -->
            <h3 style='color:#1a237e; margin-top:28px; font-size:17px;
                       border-right:4px solid #1565c0; padding-right:10px;'>
                پرتعامل‌ترین توییت‌ها
            </h3>
            <div style='overflow-x:auto; margin:14px 0 24px 0;'>
            <table style='width:100%; border-collapse:collapse; font-size:15px;'>
                <thead>
                <tr style='background:#1565c0;'>
                    <th {TH}>کاربر</th>
                    <th {TH}>متن توییت</th>
                    <th {TH}>بازنشر</th>
                    <th {TH}>لایک</th>
                    {"<th " + TH + ">فالوور</th>" if follower_col in df.columns else ""}
                    {"<th " + TH + ">تاریخ</th>" if 'روز انتشار شمسی' in df.columns else ""}
                </tr>
                </thead><tbody>
        """

        for i, (_, row) in enumerate(top_tweets.iterrows()):
            bg = '#e3f2fd' if i % 2 == 0 else '#f9f9f9'
            username = row.get('نام کاربری', '—')
            text_raw = str(row.get('متن', ''))
            text_display = text_raw.replace('\n', ' ')
            rt = format_number(row.get('تعداد بازنشر', 0))
            lk = format_number(row.get('تعداد لایک', 0))
            f_cell = f"<td {TD}>{format_number(row[follower_col])}</td>" if follower_col in df.columns else ""
            d_cell = f"<td {TD}>{row['روز انتشار شمسی']}</td>" if 'روز انتشار شمسی' in df.columns else ""
            html += f"""
                <tr style='background:{bg};'>
                    <td {TD}><b style='color:#0d47a1;'>@{username}</b></td>
                    <td {TD} style='max-width:380px; font-size:15px; color:{C};'>{text_display}</td>
                    <td {TD}><b style='color:#1b5e20;'>{rt}</b></td>
                    <td {TD}><b style='color:#b71c1c;'>{lk}</b></td>
                    {f_cell}{d_cell}
                </tr>"""
        html += "</tbody></table></div>"

        # ===== فعال‌ترین کاربران =====
        html += f"""
            <h3 style='color:#1a237e; margin-top:28px; font-size:17px;
                       border-right:4px solid #1565c0; padding-right:10px;'>
                فعال‌ترین کاربران
            </h3>
            <p style='color:{CS}; font-size:16px; margin:4px 0 12px 0;'>سورت بر اساس تعداد توییت و فالوور</p>
            <div style='overflow-x:auto; margin:0 0 24px 0;'>
            <table style='width:100%; border-collapse:collapse; font-size:15px;'>
                <thead>
                <tr style='background:#1565c0;'>
                    <th {TH}>کاربر</th>
                    <th {TH}>تعداد توییت</th>
                    {"<th " + TH + ">فالوور</th>" if follower_col in df.columns else ""}
                    <th {TH}>لایک+بازنشر</th>
                </tr>
                </thead><tbody>"""

        for i, (_, row) in enumerate(user_agg.head(10).iterrows()):
            bg = '#e8f5e9' if i % 2 == 0 else '#f9f9f9'
            f_cell = f"<td {TD}>{format_number(row.get(follower_col, 0))}</td>" if follower_col in df.columns else ""
            html += f"""
                <tr style='background:{bg};'>
                    <td {TD}><b style='color:#0d47a1;'>@{row['نام کاربری']}</b></td>
                    <td {TD}><b style='color:#1b5e20;'>{row['تعداد_توییت']}</b></td>
                    {f_cell}
                    <td {TD}>{format_number(row['تعامل_کل'])}</td>
                </tr>"""
        html += "</tbody></table></div>"

        # ===== بازنشردهندگان خبر ایسنا =====
        if not news_sharers.empty:
            html += f"""
            <h3 style='color:#1a237e; margin-top:28px; font-size:17px;
                       border-right:4px solid #1565c0; padding-right:10px;'>
                صفحات مهم بازنشردهنده خبر ایسنا
            </h3>
            <p style='color:{CS}; font-size:16px; margin:4px 0 12px 0;'>سورت بر اساس تعداد دنبال‌کننده (دامنه انتشار)</p>
            <div style='overflow-x:auto; margin:0 0 24px 0;'>
            <table style='width:100%; border-collapse:collapse; font-size:15px;'>
                <thead>
                <tr style='background:#1565c0;'>
                    <th {TH}>کاربر</th>
                    <th {TH}>فالوور</th>
                    <th {TH}>تعداد توییت با منبع ایسنا</th>
                    <th {TH}>بازنشر کل</th>
                </tr>
                </thead><tbody>"""
            for i, (_, row) in enumerate(news_sharers.iterrows()):
                bg = '#fff8e1' if i % 2 == 0 else '#f9f9f9'
                html += f"""
                <tr style='background:{bg};'>
                    <td {TD}><b style='color:#0d47a1;'>@{row['نام کاربری']}</b></td>
                    <td {TD}><b style='color:#e65100;'>{format_number(row['فالوور'])}</b></td>
                    <td {TD}><b style='color:{C};'>{row['تعداد_توییت']}</b></td>
                    <td {TD}>{format_number(row['بازنشر_کل'])}</td>
                </tr>"""
            html += "</tbody></table></div>"

        # ===== توییت‌های ایسنا با بیشترین کامنت =====
        if not isna_tweet_comments.empty:
            html += f"""
            <h3 style='color:#1a237e; margin-top:28px; font-size:17px;
                       border-right:4px solid #1565c0; padding-right:10px;'>
                توییت‌های ایسنا با بیشترین واکنش (کامنت)
            </h3>
            <div style='overflow-x:auto; margin:14px 0 24px 0;'>
            <table style='width:100%; border-collapse:collapse; font-size:15px;'>
                <thead>
                <tr style='background:#1565c0;'>
                    <th {TH}>تیتر توییت ایسنا</th>
                    <th {TH}>تعداد کامنت</th>
                </tr>
                </thead><tbody>"""
            for i, (_, row) in enumerate(isna_tweet_comments.iterrows()):
                bg = '#fce4ec' if i % 2 == 0 else '#f9f9f9'
                html += f"""
                <tr style='background:{bg};'>
                    <td {TD}>{row['تیتر_توییت_ایسنا']}</td>
                    <td {TD}><b style='color:#b71c1c;'>{row['تعداد_کامنت']}</b></td>
                </tr>"""
            html += "</tbody></table></div>"

        # ===== توضیح heatmap =====
        if heatmap_bullets:
            bullets_html = ''.join(
                f"<li style='margin-bottom:6px; color:{C};'>{b}</li>"
                for b in heatmap_bullets
            )
            html += f"""
            <div style='background:#e8f5e9; border-radius:8px; padding:14px 18px;
                        margin:10px 0 24px 0; border-right:4px solid #2e7d32;'>
                <p style='font-size:13px; font-weight:bold; color:#1b5e20; margin:0 0 8px 0;'>
                    نکات کلیدی نمودار موضوع به تفکیک ساعت:
                </p>
                <ul style='margin:0; padding-right:20px; font-size:13px; line-height:1.9;'>
                    {bullets_html}
                </ul>
            </div>"""

        html += "</div>"

        # ==================== نمودارها ====================
        chart_hourly   = create_hourly_chart(df) if 'زمان انتشار' in df.columns else go.Figure()
        chart_heatmap  = create_hourly_words_heatmap(df) if 'زمان انتشار' in df.columns else go.Figure()
        chart_content  = create_content_type_chart(df) if 'نوع محتوا' in df.columns else go.Figure()
        chart_words    = create_words_chart(df) if 'متن' in df.columns else go.Figure()

        return html, chart_hourly, chart_heatmap, chart_content, chart_words

    except Exception as e:
        import traceback
        err = f"""<div style='direction:rtl;font-family:Tahoma;padding:20px;color:#b71c1c;'>
            <h3>خطا در پردازش فایل</h3>
            <p style='background:#ffebee;padding:15px;border-right:4px solid #b71c1c;color:#212121;'>{str(e)}</p>
            <pre style='font-size:11px;color:#424242;'>{traceback.format_exc()}</pre>
        </div>"""
        return err, None, None, None, None


# ==================== رابط کاربری ====================

custom_css = """
.gradio-container {
    direction: rtl;
    background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
    min-height: 100vh;
}
"""

with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
    gr.HTML("""
        <div style='text-align:center; direction:rtl; font-family:Tahoma; padding:25px;
                    background:rgba(255,255,255,0.97); border-radius:12px; margin-bottom:10px;
                    box-shadow:0 2px 10px rgba(0,0,0,0.1);'>
            <h1 style='color:#0d47a1; margin-bottom:10px; font-size:26px;'>
                دستیار هوشمند تحلیل توییتر ایسنا
            </h1>
            <p style='color:#37474f; font-size:15px;'>فایل اکسل توییتر را آپلود کنید تا گزارش کامل دریافت نمایید</p>
            <hr style='border:1px solid #1565c0; width:40%; margin:15px auto;'>
        </div>
    """)

    with gr.Row():
        with gr.Column():
            input_file = gr.File(label="آپلود فایل اکسل توییتر",
                                 file_types=[".xlsx", ".xls"], type="binary")
            submit_btn = gr.Button("شروع تحلیل", variant="primary", size="lg")

    with gr.Row():
        with gr.Column():
            output_html = gr.HTML(label="گزارش")

    with gr.Row():
        with gr.Column():
            chart_hourly = gr.Plot(label="توزیع ساعتی")
        with gr.Column():
            chart_content = gr.Plot(label="نوع محتوا")

    with gr.Row():
        with gr.Column():
            chart_words = gr.Plot(label="پرتکرارترین عبارات")

    with gr.Row():
        with gr.Column():
            chart_heatmap = gr.Plot(label="موضوع به تفکیک ساعت")

    gr.Markdown("""
        <div style='text-align:center; direction:rtl; margin-top:20px; padding:12px;
                    color:#424242; border-top:1px solid #e0e0e0; font-family:Tahoma;'>
            <p style='font-size:13px;'>فایل باید شامل ستون‌های «متن»، «نام کاربری»، «تعداد بازنشر» و «تعداد لایک» باشد</p>
            <p style='font-size:11px; margin-top:4px; color:#546e7a;'>سامانه هوشمند ایسنا | تحلیل توییتر | نسخه ۲.۱</p>
        </div>
    """)

    submit_btn.click(
        fn=process_twitter_data,
        inputs=input_file,
        outputs=[output_html, chart_hourly, chart_heatmap, chart_content, chart_words]
    )

if __name__ == "__main__":
    demo.launch()