aysan98 commited on
Commit
3cf5afe
·
verified ·
1 Parent(s): faef7c4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +225 -178
app.py CHANGED
@@ -21,7 +21,7 @@ PERSIAN_STOP_WORDS = set([
21
  'بین', 'زیر', 'بالای', 'طی', 'حتی', 'مورد', 'جز', 'علیه', 'روی',
22
  'هنوز', 'فقط', 'هم‌چنین', 'همچنین', 'البته', 'اکنون', 'دیگر',
23
  'ایسنا', 'isna', 'isna_farsi', 'خبرگزاری', 'گزارش', 'اعلام',
24
- 'خبر', 'منتشر', 'اینکه', 'گفته', 'بر', 'طبق', 'براساس', 'طبق',
25
  'https', 'http', 'rt', 'co', 'amp', 't', 'the', 'of', 'in',
26
  'a', 'to', 'is', 'and', 'for', 'on', 'that', 'are', 'was',
27
  'it', 'with', 'he', 'she', 'they', 'we', 'i', 'you', 'at',
@@ -68,21 +68,25 @@ def clean_text(text):
68
  text = re.sub(r'\s+', ' ', text)
69
  return text.strip()
70
 
 
 
 
 
71
  def get_ngrams_adjusted(df, top_n=20):
72
  """
73
- استخراج عبارات پرتکرار (۱ تا ۴ کلمه) با کسر تکرار عبارات بلند از تک‌کلمه‌ها.
74
- اگر عبارت چندکلمه‌ای پرتکرار بود، تعداد آن از اجزایش کم می‌شود.
 
75
  """
76
  all_texts = df['متن'].apply(clean_text).tolist()
77
 
78
- # شمارش n-gram ها
79
  unigrams = Counter()
80
  bigrams = Counter()
81
  trigrams = Counter()
82
  fourgrams = Counter()
83
 
84
  for text in all_texts:
85
- words = [w for w in text.split() if len(w) > 1 and w.lower() not in PERSIAN_STOP_WORDS]
86
  for w in words:
87
  unigrams[w] += 1
88
  for i in range(len(words) - 1):
@@ -92,82 +96,117 @@ def get_ngrams_adjusted(df, top_n=20):
92
  for i in range(len(words) - 3):
93
  fourgrams[' '.join(words[i:i+4])] += 1
94
 
95
- # فیلتر: فقط عباراتی که حداقل ۲ بار تکرار شدن
96
- bigrams = Counter({k: v for k, v in bigrams.items() if v >= 2})
97
- trigrams = Counter({k: v for k, v in trigrams.items() if v >= 2})
98
  fourgrams = Counter({k: v for k, v in fourgrams.items() if v >= 2})
99
 
100
- # کسر تکرار عبارات بلند از اجزا
101
- # چهارکلمه‌ای از سه‌کلمه‌ای کم می‌شه
102
  for phrase, count in fourgrams.items():
103
- words = phrase.split()
104
- for i in range(len(words) - 2):
105
- tri = ' '.join(words[i:i+3])
106
- if tri in trigrams:
107
- trigrams[tri] = max(0, trigrams[tri] - count)
108
- for i in range(len(words) - 1):
109
- bi = ' '.join(words[i:i+2])
110
- if bi in bigrams:
111
- bigrams[bi] = max(0, bigrams[bi] - count)
112
- for w in words:
113
- if w in unigrams:
114
- unigrams[w] = max(0, unigrams[w] - count)
115
 
116
- # سه‌کلمه‌ای از دوکلمه‌ای کم می‌شه
117
  for phrase, count in trigrams.items():
118
- if count == 0:
119
- continue
120
- words = phrase.split()
121
- for i in range(len(words) - 1):
122
- bi = ' '.join(words[i:i+2])
123
- if bi in bigrams:
124
- bigrams[bi] = max(0, bigrams[bi] - count)
125
- for w in words:
126
- if w in unigrams:
127
- unigrams[w] = max(0, unigrams[w] - count)
128
 
129
- # دوکلمه‌ای از تک‌کلمه‌ای کم می‌شه
130
  for phrase, count in bigrams.items():
131
- if count == 0:
132
- continue
133
  for w in phrase.split():
134
- if w in unigrams:
135
- unigrams[w] = max(0, unigrams[w] - count)
136
 
137
- # ترکیب همه و مرتب‌سازی
138
  all_phrases = Counter()
139
- all_phrases.update({k: v for k, v in unigrams.items() if v >= 2})
140
- all_phrases.update({k: v for k, v in bigrams.items() if v >= 2})
141
- all_phrases.update({k: v for k, v in trigrams.items() if v >= 2})
142
  all_phrases.update({k: v for k, v in fourgrams.items() if v >= 2})
143
 
144
  return all_phrases.most_common(top_n)
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  def classify_tweets(df):
147
- """تفکیک توییت‌ها به سه دسته"""
148
  df = df.copy()
149
  df['نوع_تعامل'] = 'سایر'
150
-
151
- # بازنشر خبر ایسنا
152
  df.loc[
153
  df['متن'].str.contains(ISNA_PATTERN_COMBINED, case=False, na=False, regex=True),
154
  'نوع_تعامل'
155
  ] = 'بازنشر_خبر'
156
-
157
- # کامنت/ریپلای به توییت ایسنا
158
  df.loc[
159
  (df['نوع_تعامل'] == 'سایر') &
160
  df['در پاسخ به کاربر'].str.contains('isna_farsi', case=False, na=False),
161
  'نوع_تعامل'
162
  ] = 'کامنت_ایسنا'
163
-
164
- # تگ مستقل ایسنا (منشن بدون ریپلای به ایسنا)
165
  df.loc[
166
  (df['نوع_تعامل'] == 'سایر') &
167
  df['منشن ها'].str.contains('isna_farsi', case=False, na=False),
168
  'نوع_تعامل'
169
  ] = 'منشن_مستقل'
170
-
171
  return df
172
 
173
  # ==================== نمودارها ====================
@@ -184,21 +223,18 @@ def create_hourly_chart(df):
184
 
185
  fig = go.Figure()
186
  fig.add_trace(go.Bar(
187
- x=hourly['ساعت'],
188
- y=hourly['تعداد'],
189
  marker=dict(color=hourly['تعداد'], colorscale='Blues', showscale=False,
190
  line=dict(width=0.5, color='#1565c0')),
191
  hovertemplate='<b>ساعت %{x}</b>: %{y} توییت<extra></extra>'
192
  ))
193
  fig.update_layout(
194
- title={'text': '⏰ توزیع توییت‌ها بر اساس ساعت انتشار',
195
  'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'},
196
  'x': 0.5, 'xanchor': 'center'},
197
  xaxis_title='ساعت', yaxis_title='تعداد توییت',
198
  font=dict(family='Tahoma', size=13, color='#212121'),
199
- height=370,
200
- plot_bgcolor='rgba(240,245,255,0.6)',
201
- paper_bgcolor='white',
202
  xaxis=dict(tickmode='linear', dtick=1, gridcolor='rgba(150,150,150,0.2)',
203
  tickfont=dict(color='#212121')),
204
  yaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121')),
@@ -207,7 +243,6 @@ def create_hourly_chart(df):
207
  return fig
208
 
209
  def create_hourly_words_heatmap(df, top_n_words=10):
210
- """heatmap: ساعت × پرتکرارترین کلمات"""
211
  df = df.copy()
212
  df['ساعت'] = df['زمان انتشار'].apply(
213
  lambda x: int(str(x).split(':')[0]) if pd.notna(x) and ':' in str(x) else None
@@ -215,13 +250,11 @@ def create_hourly_words_heatmap(df, top_n_words=10):
215
  df = df.dropna(subset=['ساعت'])
216
  df['ساعت'] = df['ساعت'].astype(int)
217
 
218
- # کلمات پرتکرار کل
219
  top_phrases = get_ngrams_adjusted(df, top_n=top_n_words)
220
  if not top_phrases:
221
  return go.Figure()
222
  top_words = [p[0] for p in top_phrases]
223
 
224
- # شمارش هر کلمه در هر ساعت
225
  hours = sorted(df['ساعت'].unique())
226
  matrix = []
227
  for word in top_words:
@@ -237,17 +270,15 @@ def create_hourly_words_heatmap(df, top_n_words=10):
237
  x=[f'{h}:00' for h in hours],
238
  y=top_words,
239
  colorscale='Blues',
240
- hovertemplate='ساعت %{x}<br>عبارت: %{y}<br>تعداد: %{z}<extra></extra>',
241
  colorbar=dict(title='تعداد', tickfont=dict(color='#212121'))
242
  ))
243
  fig.update_layout(
244
- title={'text': '🕐 در هر ساعت بیشتر از چه صحبت شد؟',
245
  'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'},
246
  'x': 0.5, 'xanchor': 'center'},
247
  font=dict(family='Tahoma', size=12, color='#212121'),
248
- height=420,
249
- paper_bgcolor='white',
250
- plot_bgcolor='white',
251
  xaxis=dict(tickfont=dict(color='#212121'), title='ساعت'),
252
  yaxis=dict(tickfont=dict(color='#212121', size=11)),
253
  margin=dict(l=130, r=30, t=60, b=60)
@@ -262,40 +293,32 @@ def create_words_chart(df):
262
  labels = [p[0] for p in top_phrases][::-1]
263
  counts = [p[1] for p in top_phrases][::-1]
264
  colors = ['#1565c0' if ' ' not in l else '#00897b' if len(l.split()) == 2
265
- else '#6a1b9a' if len(l.split()) == 3 else '#c62828'
266
- for l in labels]
267
 
268
  fig = go.Figure()
269
  fig.add_trace(go.Bar(
270
- y=labels, x=counts,
271
- orientation='h',
272
  marker=dict(color=colors, line=dict(width=0.5, color='white')),
273
  text=counts, textposition='outside',
274
  textfont=dict(color='#212121', size=11),
275
  hovertemplate='<b>%{y}</b>: %{x} بار<extra></extra>'
276
  ))
277
-
278
- # راهنمای رنگ
279
  for color, label in [('#1565c0', 'تک‌کلمه'), ('#00897b', 'دوکلمه‌ای'),
280
  ('#6a1b9a', 'سه‌کلمه‌ای'), ('#c62828', 'چهارکلمه‌ای')]:
281
  fig.add_trace(go.Bar(x=[None], y=[None], orientation='h',
282
  marker=dict(color=color), name=label, showlegend=True))
283
-
284
  fig.update_layout(
285
- title={'text': '📝 پرتکرارترین عبارات در توییت‌ها',
286
  'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'},
287
  'x': 0.5, 'xanchor': 'center'},
288
  xaxis_title='تعداد تکرار',
289
  font=dict(family='Tahoma', size=13, color='#212121'),
290
- height=580,
291
- plot_bgcolor='rgba(240,245,255,0.6)',
292
- paper_bgcolor='white',
293
  xaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121')),
294
  yaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121', size=11)),
295
  legend=dict(orientation='h', yanchor='bottom', y=1.01, xanchor='center', x=0.5,
296
  font=dict(color='#212121')),
297
- margin=dict(l=150, r=80, t=80, b=50),
298
- barmode='overlay'
299
  )
300
  return fig
301
 
@@ -303,11 +326,8 @@ def create_content_type_chart(df):
303
  content_counts = df['نوع محتوا'].value_counts()
304
  labels_map = {'text': 'متن', 'photo': 'عکس', 'video': 'ویدئو'}
305
  labels = [labels_map.get(l, l) for l in content_counts.index]
306
-
307
  fig = go.Figure(go.Pie(
308
- labels=labels,
309
- values=content_counts.values,
310
- hole=0.45,
311
  marker=dict(colors=['#1565c0', '#2e7d32', '#e65100'],
312
  line=dict(color='white', width=2)),
313
  textinfo='label+percent',
@@ -315,12 +335,11 @@ def create_content_type_chart(df):
315
  hovertemplate='%{label}: %{value} توییت (%{percent})<extra></extra>'
316
  ))
317
  fig.update_layout(
318
- title={'text': '🎬 توزیع نوع محتوای توییت‌ها',
319
  'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'},
320
  'x': 0.5, 'xanchor': 'center'},
321
  font=dict(family='Tahoma', size=13, color='#212121'),
322
- height=360,
323
- paper_bgcolor='white',
324
  margin=dict(l=20, r=20, t=60, b=20),
325
  legend=dict(font=dict(family='Tahoma', size=13, color='#212121'))
326
  )
@@ -336,7 +355,6 @@ def process_twitter_data(file):
336
  except Exception:
337
  df = pd.read_excel(io.BytesIO(file) if isinstance(file, bytes) else file, engine='openpyxl')
338
 
339
- # بررسی ستون‌های ضروری
340
  required = ['متن', 'نام کاربری', 'تعداد بازنشر', 'تعداد لایک']
341
  missing = [c for c in required if c not in df.columns]
342
  if missing:
@@ -345,7 +363,7 @@ def process_twitter_data(file):
345
 
346
  # پاکسازی
347
  df['تعداد بازنشر'] = pd.to_numeric(df['تعداد بازنشر'], errors='coerce').fillna(0)
348
- df['تعداد لایک'] = pd.to_numeric(df['تعداد لایک'], errors='coerce').fillna(0)
349
  follower_col = 'تعداد دنبال کننده\u200cها'
350
  if follower_col in df.columns:
351
  df[follower_col] = pd.to_numeric(df[follower_col], errors='coerce').fillna(0)
@@ -353,17 +371,15 @@ def process_twitter_data(file):
353
 
354
  # تفکیک نوع تعامل
355
  df = classify_tweets(df)
356
-
357
  count_news_share = (df['نوع_تعامل'] == 'بازنشر_خبر').sum()
358
- count_comment = (df['نوع_تعامل'] == 'کامنت_ایسنا').sum()
359
- count_mention = (df['نوع_تعامل'] == 'منشن_مستقل').sum()
360
 
361
- # آمار کلی
362
  date_from, date_to = parse_date_range(df)
363
- total = len(df)
364
  total_retweet = int(df['تعداد بازنشر'].sum())
365
- total_like = int(df['تعداد لایک'].sum())
366
- unique_users = df['نام کاربری'].nunique() if 'نام کاربری' in df.columns else 0
367
 
368
  # نوع محتوا
369
  content_dist = ''
@@ -373,112 +389,126 @@ def process_twitter_data(file):
373
  pct = round(cnt / total * 100)
374
  content_dist += f"<span style='margin-left:18px; color:#212121;'>{label}: <b>{cnt}</b> ({pct}%)</span>"
375
 
376
- # پرتعامل‌ترین توییت‌ها (با متن)
377
  top_tweets = df.nlargest(10, 'تعامل_کل').copy()
378
 
379
- # فعال‌ترین کاربران (تعداد توییت + فالوور)
380
- user_agg = df.groupby('نام کاربری').agg(
381
- تعداد_توییت=('متن', 'count'),
382
- فالوور=(follower_col, 'max') if follower_col in df.columns else ('متن', 'count'),
383
- تعامل_کل=('تعامل_کل', 'sum')
384
- ).reset_index()
385
  if follower_col in df.columns:
386
- user_agg = user_agg.sort_values(['تعداد_توییت', 'فالوور'], ascending=False)
387
- else:
388
- user_agg = user_agg.sort_values('تعداد_توییت', ascending=False)
 
 
389
 
390
- # پرفالوورترین بازنشردهندگان خبر ایسنا
391
  df_news = df[df['نوع_تعامل'] == 'بازنشر_خبر']
 
392
  if follower_col in df.columns and len(df_news) > 0:
393
- news_sharers = df_news.groupby('نام کاربری').agg(
394
  تعداد_توییت=('متن', 'count'),
395
  فالوور=(follower_col, 'max'),
396
  بازنشر_کل=('تعداد بازنشر', 'sum')
397
  ).reset_index().sort_values('فالوور', ascending=False).head(10)
398
- else:
399
- news_sharers = pd.DataFrame()
400
 
401
  # توییت‌های ایسنا با بیشترین کامنت
402
  df_comments = df[df['نوع_تعامل'] == 'کامنت_ایسنا'].copy()
403
  isna_tweet_comments = pd.DataFrame()
404
  if 'در پاسخ به این پیام' in df_comments.columns and len(df_comments) > 0:
405
- comment_counts = df_comments.groupby('در پاسخ به این پیام').size().reset_index()
406
- comment_counts.columns = ['تیتر_توییت_ایسنا', 'تعداد_کامنت']
407
- isna_tweet_comments = comment_counts.sort_values('تعداد_کامنت', ascending=False).head(8)
 
 
 
 
 
408
 
409
  # ==================== ساخت HTML ====================
410
- TD = "style='padding:10px 14px; border:1px solid #cfd8dc; text-align:right; color:#212121;'"
411
- TH = "style='padding:11px 14px; border:1px solid #1565c0; text-align:right; color:white; font-weight:bold;'"
 
 
412
 
413
  html = f"""
414
  <div style='direction:rtl; font-family:Tahoma,Arial; text-align:right; padding:24px;
415
- background:white; color:#212121; line-height:1.7;'>
416
 
417
  <h2 style='text-align:center; color:#0d47a1; border-bottom:3px solid #1565c0;
418
- padding-bottom:12px; font-size:22px;'>
419
- 🐦 گزارش تحلیل توییتر ایسنا
420
  </h2>
421
- <p style='text-align:center; color:#424242; font-size:14px; margin-top:4px;'>
422
- بازه زمانی: <b>{date_from}</b> تا <b>{date_to}</b>
 
 
 
 
423
  </p>
424
 
 
 
425
  <!-- ===== آمار کلی ===== -->
426
- <h3 style='color:#1a237e; margin-top:28px; font-size:17px; border-right:4px solid #1565c0; padding-right:10px;'>
427
- 📈 آمار کلی
 
428
  </h3>
429
  <div style='display:flex; flex-wrap:wrap; gap:14px; margin:14px 0 20px 0;'>
430
  <div style='flex:1; min-width:130px; background:#e3f2fd; border-radius:10px;
431
  padding:16px 12px; text-align:center; border-top:4px solid #1565c0;'>
432
  <div style='font-size:28px; font-weight:bold; color:#0d47a1;'>{format_number(total)}</div>
433
- <div style='font-size:13px; color:#37474f; margin-top:6px;'>کل توییت‌ها</div>
434
  </div>
435
  <div style='flex:1; min-width:130px; background:#e8f5e9; border-radius:10px;
436
  padding:16px 12px; text-align:center; border-top:4px solid #2e7d32;'>
437
  <div style='font-size:28px; font-weight:bold; color:#1b5e20;'>{format_number(total_retweet)}</div>
438
- <div style='font-size:13px; color:#37474f; margin-top:6px;'>مجموع بازنشر</div>
439
  </div>
440
  <div style='flex:1; min-width:130px; background:#fff8e1; border-radius:10px;
441
  padding:16px 12px; text-align:center; border-top:4px solid #f9a825;'>
442
  <div style='font-size:28px; font-weight:bold; color:#e65100;'>{format_number(total_like)}</div>
443
- <div style='font-size:13px; color:#37474f; margin-top:6px;'>مجموع لایک</div>
444
  </div>
445
  <div style='flex:1; min-width:130px; background:#fce4ec; border-radius:10px;
446
  padding:16px 12px; text-align:center; border-top:4px solid #c62828;'>
447
  <div style='font-size:28px; font-weight:bold; color:#b71c1c;'>{format_number(unique_users)}</div>
448
- <div style='font-size:13px; color:#37474f; margin-top:6px;'>کاربران یکتا</div>
449
  </div>
450
  </div>
451
 
452
- {"<div style='background:#f5f5f5; border-radius:8px; padding:12px 16px; margin:10px 0 20px 0; font-size:14px; color:#212121;'>🎬 نوع محتوا: " + content_dist + "</div>" if content_dist else ""}
453
 
454
- <!-- ===== تفکیک نوع تعامل با ایسنا ===== -->
455
- <h3 style='color:#1a237e; margin-top:28px; font-size:17px; border-right:4px solid #1565c0; padding-right:10px;'>
456
- 🔍 نوع تعامل با ایسنا
 
457
  </h3>
458
  <div style='display:flex; flex-wrap:wrap; gap:14px; margin:14px 0 24px 0;'>
459
  <div style='flex:1; min-width:140px; background:#e8f5e9; border-radius:10px;
460
  padding:16px 12px; text-align:center; border-top:4px solid #2e7d32;'>
461
  <div style='font-size:26px; font-weight:bold; color:#1b5e20;'>{format_number(count_news_share)}</div>
462
- <div style='font-size:13px; color:#37474f; margin-top:6px;'>بازنشر خبر ایسنا</div>
463
- <div style='font-size:11px; color:#546e7a; margin-top:3px;'>(محتوا با منبع ایسنا)</div>
464
  </div>
465
  <div style='flex:1; min-width:140px; background:#fff3e0; border-radius:10px;
466
  padding:16px 12px; text-align:center; border-top:4px solid #e65100;'>
467
  <div style='font-size:26px; font-weight:bold; color:#bf360c;'>{format_number(count_comment)}</div>
468
- <div style='font-size:13px; color:#37474f; margin-top:6px;'>کامنت به توییت ایسنا</div>
469
- <div style='font-size:11px; color:#546e7a; margin-top:3px;'>(ریپلای مستقیم)</div>
470
  </div>
471
  <div style='flex:1; min-width:140px; background:#f3e5f5; border-radius:10px;
472
  padding:16px 12px; text-align:center; border-top:4px solid #6a1b9a;'>
473
  <div style='font-size:26px; font-weight:bold; color:#4a148c;'>{format_number(count_mention)}</div>
474
- <div style='font-size:13px; color:#37474f; margin-top:6px;'>تگ مستقل ایسنا</div>
475
- <div style='font-size:11px; color:#546e7a; margin-top:3px;'>(منشن بدون ریپلای)</div>
476
  </div>
477
  </div>
478
 
479
- <!-- ===== پرتعامل‌ترین توییت‌ها با متن ===== -->
480
- <h3 style='color:#1a237e; margin-top:28px; font-size:17px; border-right:4px solid #1565c0; padding-right:10px;'>
481
- 🔥 پرتعامل‌ترین توییت‌ها
 
482
  </h3>
483
  <div style='overflow-x:auto; margin:14px 0 24px 0;'>
484
  <table style='width:100%; border-collapse:collapse; font-size:13px;'>
@@ -495,33 +525,31 @@ def process_twitter_data(file):
495
  """
496
 
497
  for i, (_, row) in enumerate(top_tweets.iterrows()):
498
- bg = '#e3f2fd' if i % 2 == 0 else '#f5f5f5'
499
  username = row.get('نام کاربری', '—')
500
- text = str(row.get('متن', '')).replace('\n', ' ')[:160]
501
- if len(str(row.get('متن', ''))) > 160:
502
- text += '...'
503
  rt = format_number(row.get('تعداد بازنشر', 0))
504
  lk = format_number(row.get('تعداد لایک', 0))
505
- followers_cell = f"<td {TD}>{format_number(row[follower_col])}</td>" if follower_col in df.columns else ""
506
- date_cell = f"<td {TD}>{row['روز انتشار شمسی']}</td>" if 'روز انتشار شمسی' in df.columns else ""
507
  html += f"""
508
  <tr style='background:{bg};'>
509
  <td {TD}><b style='color:#0d47a1;'>@{username}</b></td>
510
- <td {TD} style='max-width:320px; font-size:12px; color:#212121;'>{text}</td>
511
  <td {TD}><b style='color:#1b5e20;'>{rt}</b></td>
512
  <td {TD}><b style='color:#b71c1c;'>{lk}</b></td>
513
- {followers_cell}
514
- {date_cell}
515
  </tr>"""
516
-
517
  html += "</tbody></table></div>"
518
 
519
  # ===== فعال‌ترین کاربران =====
520
  html += f"""
521
- <h3 style='color:#1a237e; margin-top:28px; font-size:17px; border-right:4px solid #1565c0; padding-right:10px;'>
522
- 👥 فعال‌ترین کاربران
 
523
  </h3>
524
- <p style='color:#424242; font-size:13px; margin:4px 0 12px 0;'>سورت بر اساس تعداد توییت و فالوور</p>
525
  <div style='overflow-x:auto; margin:0 0 24px 0;'>
526
  <table style='width:100%; border-collapse:collapse; font-size:13px;'>
527
  <thead>
@@ -534,13 +562,13 @@ def process_twitter_data(file):
534
  </thead><tbody>"""
535
 
536
  for i, (_, row) in enumerate(user_agg.head(10).iterrows()):
537
- bg = '#e8f5e9' if i % 2 == 0 else '#f5f5f5'
538
- followers_cell = f"<td {TD}>{format_number(row.get('فالوور', 0))}</td>" if follower_col in df.columns else ""
539
  html += f"""
540
  <tr style='background:{bg};'>
541
  <td {TD}><b style='color:#0d47a1;'>@{row['نام کاربری']}</b></td>
542
  <td {TD}><b style='color:#1b5e20;'>{row['تعداد_توییت']}</b></td>
543
- {followers_cell}
544
  <td {TD}>{format_number(row['تعامل_کل'])}</td>
545
  </tr>"""
546
  html += "</tbody></table></div>"
@@ -548,10 +576,11 @@ def process_twitter_data(file):
548
  # ===== بازنشردهندگان خبر ایسنا =====
549
  if not news_sharers.empty:
550
  html += f"""
551
- <h3 style='color:#1a237e; margin-top:28px; font-size:17px; border-right:4px solid #1565c0; padding-right:10px;'>
552
- 📡 صفحات مهم بازنشردهنده خبر ایسنا
 
553
  </h3>
554
- <p style='color:#424242; font-size:13px; margin:4px 0 12px 0;'>سورت بر اساس تعداد دنبال‌کننده (دامنه انتشار)</p>
555
  <div style='overflow-x:auto; margin:0 0 24px 0;'>
556
  <table style='width:100%; border-collapse:collapse; font-size:13px;'>
557
  <thead>
@@ -563,12 +592,12 @@ def process_twitter_data(file):
563
  </tr>
564
  </thead><tbody>"""
565
  for i, (_, row) in enumerate(news_sharers.iterrows()):
566
- bg = '#fff8e1' if i % 2 == 0 else '#f5f5f5'
567
  html += f"""
568
  <tr style='background:{bg};'>
569
  <td {TD}><b style='color:#0d47a1;'>@{row['نام کاربری']}</b></td>
570
  <td {TD}><b style='color:#e65100;'>{format_number(row['فالوور'])}</b></td>
571
- <td {TD}>{row['تعداد_توییت']}</td>
572
  <td {TD}>{format_number(row['بازنشر_کل'])}</td>
573
  </tr>"""
574
  html += "</tbody></table></div>"
@@ -576,8 +605,9 @@ def process_twitter_data(file):
576
  # ===== توییت‌های ایسنا با بیشترین کامنت =====
577
  if not isna_tweet_comments.empty:
578
  html += f"""
579
- <h3 style='color:#1a237e; margin-top:28px; font-size:17px; border-right:4px solid #1565c0; padding-right:10px;'>
580
- 💬 توییت‌های ایسنا با بیشترین واکنش (کامنت)
 
581
  </h3>
582
  <div style='overflow-x:auto; margin:14px 0 24px 0;'>
583
  <table style='width:100%; border-collapse:collapse; font-size:13px;'>
@@ -588,7 +618,7 @@ def process_twitter_data(file):
588
  </tr>
589
  </thead><tbody>"""
590
  for i, (_, row) in enumerate(isna_tweet_comments.iterrows()):
591
- bg = '#fce4ec' if i % 2 == 0 else '#f5f5f5'
592
  html += f"""
593
  <tr style='background:{bg};'>
594
  <td {TD}>{row['تیتر_توییت_ایسنا']}</td>
@@ -596,22 +626,39 @@ def process_twitter_data(file):
596
  </tr>"""
597
  html += "</tbody></table></div>"
598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
599
  html += "</div>"
600
 
601
  # ==================== نمودارها ====================
602
- chart_hourly = create_hourly_chart(df) if 'زمان انتشار' in df.columns else go.Figure()
603
- chart_heatmap = create_hourly_words_heatmap(df) if 'زمان انتشار' in df.columns and 'متن' in df.columns else go.Figure()
604
- chart_content = create_content_type_chart(df) if 'نوع محتوا' in df.columns else go.Figure()
605
- chart_words = create_words_chart(df) if 'متن' in df.columns else go.Figure()
606
 
607
  return html, chart_hourly, chart_heatmap, chart_content, chart_words
608
 
609
  except Exception as e:
610
  import traceback
611
  err = f"""<div style='direction:rtl;font-family:Tahoma;padding:20px;color:#b71c1c;'>
612
- <h3>❌ خطا در پردازش فایل</h3>
613
- <p style='background:#ffebee;padding:15px;border-right:4px solid #b71c1c;'>{str(e)}</p>
614
- <pre style='font-size:11px;color:#555;'>{traceback.format_exc()}</pre>
615
  </div>"""
616
  return err, None, None, None, None
617
 
@@ -632,7 +679,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
632
  background:rgba(255,255,255,0.97); border-radius:12px; margin-bottom:10px;
633
  box-shadow:0 2px 10px rgba(0,0,0,0.1);'>
634
  <h1 style='color:#0d47a1; margin-bottom:10px; font-size:26px;'>
635
- 🐦 دستیار هوشمند تحلیل توییتر ایسنا
636
  </h1>
637
  <p style='color:#37474f; font-size:15px;'>فایل اکسل توییتر را آپلود کنید تا گزارش کامل دریافت نمایید</p>
638
  <hr style='border:1px solid #1565c0; width:40%; margin:15px auto;'>
@@ -641,33 +688,33 @@ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
641
 
642
  with gr.Row():
643
  with gr.Column():
644
- input_file = gr.File(label="📁 آپلود فایل اکسل توییتر",
645
  file_types=[".xlsx", ".xls"], type="binary")
646
- submit_btn = gr.Button("🚀 شروع تحلیل", variant="primary", size="lg")
647
 
648
  with gr.Row():
649
  with gr.Column():
650
- output_html = gr.HTML(label="📊 گزارش")
651
 
652
  with gr.Row():
653
  with gr.Column():
654
- chart_hourly = gr.Plot(label="⏰ توزیع ساعتی")
655
  with gr.Column():
656
- chart_content = gr.Plot(label="🎬 نوع محتوا")
657
 
658
  with gr.Row():
659
  with gr.Column():
660
- chart_words = gr.Plot(label="📝 پرتکرارترین عبارات")
661
 
662
  with gr.Row():
663
  with gr.Column():
664
- chart_heatmap = gr.Plot(label="🕐 موضوع به تفکیک ساعت")
665
 
666
  gr.Markdown("""
667
  <div style='text-align:center; direction:rtl; margin-top:20px; padding:12px;
668
- color:#546e7a; border-top:1px solid #e0e0e0; font-family:Tahoma;'>
669
- <p style='font-size:13px;'>💡 فایل باید شامل ستون‌های «متن»، «نام کاربری»، «تعداد بازنشر» و «تعداد لایک» باشد</p>
670
- <p style='font-size:11px; margin-top:4px;'>سامانه هوشمند ایسنا | تحلیل توییتر | نسخه ۲.۰</p>
671
  </div>
672
  """)
673
 
 
21
  'بین', 'زیر', 'بالای', 'طی', 'حتی', 'مورد', 'جز', 'علیه', 'روی',
22
  'هنوز', 'فقط', 'هم‌چنین', 'همچنین', 'البته', 'اکنون', 'دیگر',
23
  'ایسنا', 'isna', 'isna_farsi', 'خبرگزاری', 'گزارش', 'اعلام',
24
+ 'خبر', 'منتشر', 'اینکه', 'گفته', 'طبق', 'براساس',
25
  'https', 'http', 'rt', 'co', 'amp', 't', 'the', 'of', 'in',
26
  'a', 'to', 'is', 'and', 'for', 'on', 'that', 'are', 'was',
27
  'it', 'with', 'he', 'she', 'they', 'we', 'i', 'you', 'at',
 
68
  text = re.sub(r'\s+', ' ', text)
69
  return text.strip()
70
 
71
+ def is_valid_word(w):
72
+ """کلمه معتبر: حداقل ۳ حرف و در لیست stop words نباشد"""
73
+ return len(w) >= 3 and w.lower() not in PERSIAN_STOP_WORDS
74
+
75
  def get_ngrams_adjusted(df, top_n=20):
76
  """
77
+ استخراج عبارات پرتکرار ۱ تا ۴ کلمه‌ای.
78
+ تعداد تکرار عبارات بلندتر از اجزای کوتاه‌تر کسر می‌شود.
79
+ حداقل طول کلمه: ۳ حرف.
80
  """
81
  all_texts = df['متن'].apply(clean_text).tolist()
82
 
 
83
  unigrams = Counter()
84
  bigrams = Counter()
85
  trigrams = Counter()
86
  fourgrams = Counter()
87
 
88
  for text in all_texts:
89
+ words = [w for w in text.split() if is_valid_word(w)]
90
  for w in words:
91
  unigrams[w] += 1
92
  for i in range(len(words) - 1):
 
96
  for i in range(len(words) - 3):
97
  fourgrams[' '.join(words[i:i+4])] += 1
98
 
99
+ # فیلتر: حداقل ۲ بار تکرار
100
+ bigrams = Counter({k: v for k, v in bigrams.items() if v >= 2})
101
+ trigrams = Counter({k: v for k, v in trigrams.items() if v >= 2})
102
  fourgrams = Counter({k: v for k, v in fourgrams.items() if v >= 2})
103
 
104
+ # کسر تکرار عبارات بلند از اجزای کوتاه‌تر
 
105
  for phrase, count in fourgrams.items():
106
+ ws = phrase.split()
107
+ for i in range(len(ws)-2):
108
+ tri = ' '.join(ws[i:i+3])
109
+ if tri in trigrams: trigrams[tri] = max(0, trigrams[tri] - count)
110
+ for i in range(len(ws)-1):
111
+ bi = ' '.join(ws[i:i+2])
112
+ if bi in bigrams: bigrams[bi] = max(0, bigrams[bi] - count)
113
+ for w in ws:
114
+ if w in unigrams: unigrams[w] = max(0, unigrams[w] - count)
 
 
 
115
 
 
116
  for phrase, count in trigrams.items():
117
+ if count == 0: continue
118
+ ws = phrase.split()
119
+ for i in range(len(ws)-1):
120
+ bi = ' '.join(ws[i:i+2])
121
+ if bi in bigrams: bigrams[bi] = max(0, bigrams[bi] - count)
122
+ for w in ws:
123
+ if w in unigrams: unigrams[w] = max(0, unigrams[w] - count)
 
 
 
124
 
 
125
  for phrase, count in bigrams.items():
126
+ if count == 0: continue
 
127
  for w in phrase.split():
128
+ if w in unigrams: unigrams[w] = max(0, unigrams[w] - count)
 
129
 
 
130
  all_phrases = Counter()
131
+ all_phrases.update({k: v for k, v in unigrams.items() if v >= 2})
132
+ all_phrases.update({k: v for k, v in bigrams.items() if v >= 2})
133
+ all_phrases.update({k: v for k, v in trigrams.items() if v >= 2})
134
  all_phrases.update({k: v for k, v in fourgrams.items() if v >= 2})
135
 
136
  return all_phrases.most_common(top_n)
137
 
138
+ def get_hourly_top_words(df, hour, top_n=3):
139
+ """پرتکرارترین کلمات در یک ساعت مشخص"""
140
+ texts = df[df['ساعت'] == hour]['متن'].apply(clean_text)
141
+ words = []
142
+ for t in texts:
143
+ words += [w for w in t.split() if is_valid_word(w)]
144
+ return [w for w, _ in Counter(words).most_common(top_n)]
145
+
146
+ def generate_heatmap_insights(df):
147
+ """تولید توضیح داینامیک برای heatmap"""
148
+ df = df.copy()
149
+ df['ساعت'] = df['زمان انتشار'].apply(
150
+ lambda x: int(str(x).split(':')[0]) if pd.notna(x) and ':' in str(x) else None
151
+ )
152
+ df = df.dropna(subset=['ساعت'])
153
+ df['ساعت'] = df['ساعت'].astype(int)
154
+
155
+ hourly_counts = df['ساعت'].value_counts()
156
+ if hourly_counts.empty:
157
+ return ''
158
+
159
+ # پیک ساعتی
160
+ peak_hour = int(hourly_counts.idxmax())
161
+ peak_count = int(hourly_counts.max())
162
+ peak_words = get_hourly_top_words(df, peak_hour)
163
+
164
+ # سه ساعت پرتوییت
165
+ top3_hours = hourly_counts.nlargest(3)
166
+
167
+ bullets = []
168
+ bullets.append(
169
+ f"پیک توییت در ساعت <b>{peak_hour}:00</b> با <b>{peak_count}</b> توییت بوده؛ "
170
+ f"پرتکرارترین موضوعات: {' ، '.join(peak_words) if peak_words else '—'}"
171
+ )
172
+
173
+ for h, cnt in top3_hours.items():
174
+ h = int(h)
175
+ if h == peak_hour:
176
+ continue
177
+ words = get_hourly_top_words(df, h)
178
+ if words:
179
+ bullets.append(
180
+ f"ساعت <b>{h}:00</b> ({cnt} توییت): بیشتر درباره {' ، '.join(words)} صحبت شد"
181
+ )
182
+
183
+ # ساعت با کمترین فعالیت
184
+ low_hour = int(hourly_counts.idxmin())
185
+ low_count = int(hourly_counts.min())
186
+ if low_count == 0:
187
+ bullets.append(f"در ساعت <b>{low_hour}:00</b> هیچ توییتی ثبت نشده است")
188
+ else:
189
+ bullets.append(f"کمترین فعالیت در ساعت <b>{low_hour}:00</b> با <b>{low_count}</b> توییت")
190
+
191
+ return bullets
192
+
193
  def classify_tweets(df):
 
194
  df = df.copy()
195
  df['نوع_تعامل'] = 'سایر'
 
 
196
  df.loc[
197
  df['متن'].str.contains(ISNA_PATTERN_COMBINED, case=False, na=False, regex=True),
198
  'نوع_تعامل'
199
  ] = 'بازنشر_خبر'
 
 
200
  df.loc[
201
  (df['نوع_تعامل'] == 'سایر') &
202
  df['در پاسخ به کاربر'].str.contains('isna_farsi', case=False, na=False),
203
  'نوع_تعامل'
204
  ] = 'کامنت_ایسنا'
 
 
205
  df.loc[
206
  (df['نوع_تعامل'] == 'سایر') &
207
  df['منشن ها'].str.contains('isna_farsi', case=False, na=False),
208
  'نوع_تعامل'
209
  ] = 'منشن_مستقل'
 
210
  return df
211
 
212
  # ==================== نمودارها ====================
 
223
 
224
  fig = go.Figure()
225
  fig.add_trace(go.Bar(
226
+ x=hourly['ساعت'], y=hourly['تعداد'],
 
227
  marker=dict(color=hourly['تعداد'], colorscale='Blues', showscale=False,
228
  line=dict(width=0.5, color='#1565c0')),
229
  hovertemplate='<b>ساعت %{x}</b>: %{y} توییت<extra></extra>'
230
  ))
231
  fig.update_layout(
232
+ title={'text': 'توزیع توییت‌ها بر اساس ساعت انتشار',
233
  'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'},
234
  'x': 0.5, 'xanchor': 'center'},
235
  xaxis_title='ساعت', yaxis_title='تعداد توییت',
236
  font=dict(family='Tahoma', size=13, color='#212121'),
237
+ height=370, plot_bgcolor='rgba(240,245,255,0.6)', paper_bgcolor='white',
 
 
238
  xaxis=dict(tickmode='linear', dtick=1, gridcolor='rgba(150,150,150,0.2)',
239
  tickfont=dict(color='#212121')),
240
  yaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121')),
 
243
  return fig
244
 
245
  def create_hourly_words_heatmap(df, top_n_words=10):
 
246
  df = df.copy()
247
  df['ساعت'] = df['زمان انتشار'].apply(
248
  lambda x: int(str(x).split(':')[0]) if pd.notna(x) and ':' in str(x) else None
 
250
  df = df.dropna(subset=['ساعت'])
251
  df['ساعت'] = df['ساعت'].astype(int)
252
 
 
253
  top_phrases = get_ngrams_adjusted(df, top_n=top_n_words)
254
  if not top_phrases:
255
  return go.Figure()
256
  top_words = [p[0] for p in top_phrases]
257
 
 
258
  hours = sorted(df['ساعت'].unique())
259
  matrix = []
260
  for word in top_words:
 
270
  x=[f'{h}:00' for h in hours],
271
  y=top_words,
272
  colorscale='Blues',
273
+ hovertemplate='ساعت %{x}<br>عبارت: %{y}<br>تعداد توییت: %{z}<extra></extra>',
274
  colorbar=dict(title='تعداد', tickfont=dict(color='#212121'))
275
  ))
276
  fig.update_layout(
277
+ title={'text': 'در هر ساعت بیشتر از چه صحبت شد؟',
278
  'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'},
279
  'x': 0.5, 'xanchor': 'center'},
280
  font=dict(family='Tahoma', size=12, color='#212121'),
281
+ height=420, paper_bgcolor='white', plot_bgcolor='white',
 
 
282
  xaxis=dict(tickfont=dict(color='#212121'), title='ساعت'),
283
  yaxis=dict(tickfont=dict(color='#212121', size=11)),
284
  margin=dict(l=130, r=30, t=60, b=60)
 
293
  labels = [p[0] for p in top_phrases][::-1]
294
  counts = [p[1] for p in top_phrases][::-1]
295
  colors = ['#1565c0' if ' ' not in l else '#00897b' if len(l.split()) == 2
296
+ else '#6a1b9a' if len(l.split()) == 3 else '#c62828' for l in labels]
 
297
 
298
  fig = go.Figure()
299
  fig.add_trace(go.Bar(
300
+ y=labels, x=counts, orientation='h',
 
301
  marker=dict(color=colors, line=dict(width=0.5, color='white')),
302
  text=counts, textposition='outside',
303
  textfont=dict(color='#212121', size=11),
304
  hovertemplate='<b>%{y}</b>: %{x} بار<extra></extra>'
305
  ))
 
 
306
  for color, label in [('#1565c0', 'تک‌کلمه'), ('#00897b', 'دوکلمه‌ای'),
307
  ('#6a1b9a', 'سه‌کلمه‌ای'), ('#c62828', 'چهارکلمه‌ای')]:
308
  fig.add_trace(go.Bar(x=[None], y=[None], orientation='h',
309
  marker=dict(color=color), name=label, showlegend=True))
 
310
  fig.update_layout(
311
+ title={'text': 'پرتکرارترین عبارات در توییت‌ها',
312
  'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'},
313
  'x': 0.5, 'xanchor': 'center'},
314
  xaxis_title='تعداد تکرار',
315
  font=dict(family='Tahoma', size=13, color='#212121'),
316
+ height=580, plot_bgcolor='rgba(240,245,255,0.6)', paper_bgcolor='white',
 
 
317
  xaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121')),
318
  yaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121', size=11)),
319
  legend=dict(orientation='h', yanchor='bottom', y=1.01, xanchor='center', x=0.5,
320
  font=dict(color='#212121')),
321
+ margin=dict(l=150, r=80, t=80, b=50), barmode='overlay'
 
322
  )
323
  return fig
324
 
 
326
  content_counts = df['نوع محتوا'].value_counts()
327
  labels_map = {'text': 'متن', 'photo': 'عکس', 'video': 'ویدئو'}
328
  labels = [labels_map.get(l, l) for l in content_counts.index]
 
329
  fig = go.Figure(go.Pie(
330
+ labels=labels, values=content_counts.values, hole=0.45,
 
 
331
  marker=dict(colors=['#1565c0', '#2e7d32', '#e65100'],
332
  line=dict(color='white', width=2)),
333
  textinfo='label+percent',
 
335
  hovertemplate='%{label}: %{value} توییت (%{percent})<extra></extra>'
336
  ))
337
  fig.update_layout(
338
+ title={'text': 'توزیع نوع محتوای توییت‌ها',
339
  'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'},
340
  'x': 0.5, 'xanchor': 'center'},
341
  font=dict(family='Tahoma', size=13, color='#212121'),
342
+ height=360, paper_bgcolor='white',
 
343
  margin=dict(l=20, r=20, t=60, b=20),
344
  legend=dict(font=dict(family='Tahoma', size=13, color='#212121'))
345
  )
 
355
  except Exception:
356
  df = pd.read_excel(io.BytesIO(file) if isinstance(file, bytes) else file, engine='openpyxl')
357
 
 
358
  required = ['متن', 'نام کاربری', 'تعداد بازنشر', 'تعداد لایک']
359
  missing = [c for c in required if c not in df.columns]
360
  if missing:
 
363
 
364
  # پاکسازی
365
  df['تعداد بازنشر'] = pd.to_numeric(df['تعداد بازنشر'], errors='coerce').fillna(0)
366
+ df['تعداد لایک'] = pd.to_numeric(df['تعداد لایک'], errors='coerce').fillna(0)
367
  follower_col = 'تعداد دنبال کننده\u200cها'
368
  if follower_col in df.columns:
369
  df[follower_col] = pd.to_numeric(df[follower_col], errors='coerce').fillna(0)
 
371
 
372
  # تفکیک نوع تعامل
373
  df = classify_tweets(df)
 
374
  count_news_share = (df['نوع_تعامل'] == 'بازنشر_خبر').sum()
375
+ count_comment = (df['نوع_تعامل'] == 'کامنت_ایسنا').sum()
376
+ count_mention = (df['نوع_تعامل'] == 'منشن_مستقل').sum()
377
 
 
378
  date_from, date_to = parse_date_range(df)
379
+ total = len(df)
380
  total_retweet = int(df['تعداد بازنشر'].sum())
381
+ total_like = int(df['تعداد لایک'].sum())
382
+ unique_users = df['نام کاربری'].nunique()
383
 
384
  # نوع محتوا
385
  content_dist = ''
 
389
  pct = round(cnt / total * 100)
390
  content_dist += f"<span style='margin-left:18px; color:#212121;'>{label}: <b>{cnt}</b> ({pct}%)</span>"
391
 
392
+ # پرتعامل‌ترین توییت‌ها
393
  top_tweets = df.nlargest(10, 'تعامل_کل').copy()
394
 
395
+ # فعال‌ترین کاربران
396
+ agg_dict = {'متن': 'count', 'تعامل_کل': 'sum'}
 
 
 
 
397
  if follower_col in df.columns:
398
+ agg_dict[follower_col] = 'max'
399
+ user_agg = df.groupby('نام کاربری').agg(agg_dict).reset_index()
400
+ user_agg.columns = ['نام کاربری', 'تعداد_توییت', 'تعامل_کل'] + ([follower_col] if follower_col in df.columns else [])
401
+ sort_cols = ['تعداد_توییت', follower_col] if follower_col in df.columns else ['تعداد_توییت']
402
+ user_agg = user_agg.sort_values(sort_cols, ascending=False)
403
 
404
+ # بازنشردهندگان خبر ایسنا
405
  df_news = df[df['نوع_تعامل'] == 'بازنشر_خبر']
406
+ news_sharers = pd.DataFrame()
407
  if follower_col in df.columns and len(df_news) > 0:
408
+ ns = df_news.groupby('نام کاربری').agg(
409
  تعداد_توییت=('متن', 'count'),
410
  فالوور=(follower_col, 'max'),
411
  بازنشر_کل=('تعداد بازنشر', 'sum')
412
  ).reset_index().sort_values('فالوور', ascending=False).head(10)
413
+ news_sharers = ns
 
414
 
415
  # توییت‌های ایسنا با بیشترین کامنت
416
  df_comments = df[df['نوع_تعامل'] == 'کامنت_ایسنا'].copy()
417
  isna_tweet_comments = pd.DataFrame()
418
  if 'در پاسخ به این پیام' in df_comments.columns and len(df_comments) > 0:
419
+ cc = df_comments.groupby('در پاسخ به این پیام').size().reset_index()
420
+ cc.columns = ['تیتر_توییت_ایسنا', 'تعداد_کامنت']
421
+ isna_tweet_comments = cc.sort_values('تعداد_کامنت', ascending=False).head(8)
422
+
423
+ # توضیح داینامیک heatmap
424
+ heatmap_bullets = []
425
+ if 'زمان انتشار' in df.columns:
426
+ heatmap_bullets = generate_heatmap_insights(df)
427
 
428
  # ==================== ساخت HTML ====================
429
+ C = "#212121" # رنگ متن اصلی - تقریباً مشکی
430
+ CS = "#37474f" # رنگ متن ثانوی
431
+ TD = f"style='padding:10px 14px; border:1px solid #cfd8dc; text-align:right; color:{C};'"
432
+ TH = f"style='padding:11px 14px; border:1px solid #1565c0; text-align:right; color:white; font-weight:bold;'"
433
 
434
  html = f"""
435
  <div style='direction:rtl; font-family:Tahoma,Arial; text-align:right; padding:24px;
436
+ background:white; color:{C}; line-height:1.8;'>
437
 
438
  <h2 style='text-align:center; color:#0d47a1; border-bottom:3px solid #1565c0;
439
+ padding-bottom:12px; font-size:22px; margin-bottom:6px;'>
440
+ گزارش تحلیل توییتر ایسنا
441
  </h2>
442
+ <p style='text-align:center; color:{CS}; font-size:14px; margin-top:4px;'>
443
+ بازه زمانی: <b style='color:{C};'>{date_from}</b> تا <b style='color:{C};'>{date_to}</b>
444
+ </p>
445
+ <p style='text-align:center; color:{CS}; font-size:12px; margin-top:6px; margin-bottom:0;'>
446
+ تدوین: فاطمه نظرمحمدی &nbsp;|&nbsp; بازبینی: مهناز محمدی‌زادگان
447
+ <br>اداره نظارت و ارزیابی، خبرگزاری دانشجویان ایران (ایسنا)
448
  </p>
449
 
450
+ <hr style='border:none; border-top:1px solid #e0e0e0; margin:20px 0;'>
451
+
452
  <!-- ===== آمار کلی ===== -->
453
+ <h3 style='color:#1a237e; margin-top:20px; font-size:17px;
454
+ border-right:4px solid #1565c0; padding-right:10px;'>
455
+ آمار کلی
456
  </h3>
457
  <div style='display:flex; flex-wrap:wrap; gap:14px; margin:14px 0 20px 0;'>
458
  <div style='flex:1; min-width:130px; background:#e3f2fd; border-radius:10px;
459
  padding:16px 12px; text-align:center; border-top:4px solid #1565c0;'>
460
  <div style='font-size:28px; font-weight:bold; color:#0d47a1;'>{format_number(total)}</div>
461
+ <div style='font-size:13px; color:{CS}; margin-top:6px;'>کل توییت‌ها</div>
462
  </div>
463
  <div style='flex:1; min-width:130px; background:#e8f5e9; border-radius:10px;
464
  padding:16px 12px; text-align:center; border-top:4px solid #2e7d32;'>
465
  <div style='font-size:28px; font-weight:bold; color:#1b5e20;'>{format_number(total_retweet)}</div>
466
+ <div style='font-size:13px; color:{CS}; margin-top:6px;'>مجموع بازنشر</div>
467
  </div>
468
  <div style='flex:1; min-width:130px; background:#fff8e1; border-radius:10px;
469
  padding:16px 12px; text-align:center; border-top:4px solid #f9a825;'>
470
  <div style='font-size:28px; font-weight:bold; color:#e65100;'>{format_number(total_like)}</div>
471
+ <div style='font-size:13px; color:{CS}; margin-top:6px;'>مجموع لایک</div>
472
  </div>
473
  <div style='flex:1; min-width:130px; background:#fce4ec; border-radius:10px;
474
  padding:16px 12px; text-align:center; border-top:4px solid #c62828;'>
475
  <div style='font-size:28px; font-weight:bold; color:#b71c1c;'>{format_number(unique_users)}</div>
476
+ <div style='font-size:13px; color:{CS}; margin-top:6px;'>کاربران یکتا</div>
477
  </div>
478
  </div>
479
 
480
+ {"<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 ""}
481
 
482
+ <!-- ===== تفکیک نوع تعامل ===== -->
483
+ <h3 style='color:#1a237e; margin-top:28px; font-size:17px;
484
+ border-right:4px solid #1565c0; padding-right:10px;'>
485
+ نوع تعامل با ایسنا
486
  </h3>
487
  <div style='display:flex; flex-wrap:wrap; gap:14px; margin:14px 0 24px 0;'>
488
  <div style='flex:1; min-width:140px; background:#e8f5e9; border-radius:10px;
489
  padding:16px 12px; text-align:center; border-top:4px solid #2e7d32;'>
490
  <div style='font-size:26px; font-weight:bold; color:#1b5e20;'>{format_number(count_news_share)}</div>
491
+ <div style='font-size:13px; color:{CS}; margin-top:6px;'>بازنشر خبر ایسنا</div>
492
+ <div style='font-size:11px; color:#546e7a; margin-top:3px;'>محتوا با منبع ایسنا</div>
493
  </div>
494
  <div style='flex:1; min-width:140px; background:#fff3e0; border-radius:10px;
495
  padding:16px 12px; text-align:center; border-top:4px solid #e65100;'>
496
  <div style='font-size:26px; font-weight:bold; color:#bf360c;'>{format_number(count_comment)}</div>
497
+ <div style='font-size:13px; color:{CS}; margin-top:6px;'>کامنت به توییت ایسنا</div>
498
+ <div style='font-size:11px; color:#546e7a; margin-top:3px;'>ریپلای مستقیم</div>
499
  </div>
500
  <div style='flex:1; min-width:140px; background:#f3e5f5; border-radius:10px;
501
  padding:16px 12px; text-align:center; border-top:4px solid #6a1b9a;'>
502
  <div style='font-size:26px; font-weight:bold; color:#4a148c;'>{format_number(count_mention)}</div>
503
+ <div style='font-size:13px; color:{CS}; margin-top:6px;'>تگ مستقل ایسنا</div>
504
+ <div style='font-size:11px; color:#546e7a; margin-top:3px;'>منشن بدون ریپلای</div>
505
  </div>
506
  </div>
507
 
508
+ <!-- ===== پرتعامل‌ترین توییت‌ها ===== -->
509
+ <h3 style='color:#1a237e; margin-top:28px; font-size:17px;
510
+ border-right:4px solid #1565c0; padding-right:10px;'>
511
+ پرتعامل‌ترین توییت‌ها
512
  </h3>
513
  <div style='overflow-x:auto; margin:14px 0 24px 0;'>
514
  <table style='width:100%; border-collapse:collapse; font-size:13px;'>
 
525
  """
526
 
527
  for i, (_, row) in enumerate(top_tweets.iterrows()):
528
+ bg = '#e3f2fd' if i % 2 == 0 else '#f9f9f9'
529
  username = row.get('نام کاربری', '—')
530
+ text_raw = str(row.get('متن', ''))
531
+ text_cut = text_raw.replace('\n', ' ')[:160] + ('...' if len(text_raw) > 160 else '')
 
532
  rt = format_number(row.get('تعداد بازنشر', 0))
533
  lk = format_number(row.get('تعداد لایک', 0))
534
+ f_cell = f"<td {TD}>{format_number(row[follower_col])}</td>" if follower_col in df.columns else ""
535
+ d_cell = f"<td {TD}>{row['روز انتشار شمسی']}</td>" if 'روز انتشار شمسی' in df.columns else ""
536
  html += f"""
537
  <tr style='background:{bg};'>
538
  <td {TD}><b style='color:#0d47a1;'>@{username}</b></td>
539
+ <td {TD} style='max-width:320px; font-size:12px; color:{C};'>{text_cut}</td>
540
  <td {TD}><b style='color:#1b5e20;'>{rt}</b></td>
541
  <td {TD}><b style='color:#b71c1c;'>{lk}</b></td>
542
+ {f_cell}{d_cell}
 
543
  </tr>"""
 
544
  html += "</tbody></table></div>"
545
 
546
  # ===== فعال‌ترین کاربران =====
547
  html += f"""
548
+ <h3 style='color:#1a237e; margin-top:28px; font-size:17px;
549
+ border-right:4px solid #1565c0; padding-right:10px;'>
550
+ فعال‌ترین کاربران
551
  </h3>
552
+ <p style='color:{CS}; font-size:13px; margin:4px 0 12px 0;'>سورت بر اساس تعداد توییت و فالوور</p>
553
  <div style='overflow-x:auto; margin:0 0 24px 0;'>
554
  <table style='width:100%; border-collapse:collapse; font-size:13px;'>
555
  <thead>
 
562
  </thead><tbody>"""
563
 
564
  for i, (_, row) in enumerate(user_agg.head(10).iterrows()):
565
+ bg = '#e8f5e9' if i % 2 == 0 else '#f9f9f9'
566
+ f_cell = f"<td {TD}>{format_number(row.get(follower_col, 0))}</td>" if follower_col in df.columns else ""
567
  html += f"""
568
  <tr style='background:{bg};'>
569
  <td {TD}><b style='color:#0d47a1;'>@{row['نام کاربری']}</b></td>
570
  <td {TD}><b style='color:#1b5e20;'>{row['تعداد_توییت']}</b></td>
571
+ {f_cell}
572
  <td {TD}>{format_number(row['تعامل_کل'])}</td>
573
  </tr>"""
574
  html += "</tbody></table></div>"
 
576
  # ===== بازنشردهندگان خبر ایسنا =====
577
  if not news_sharers.empty:
578
  html += f"""
579
+ <h3 style='color:#1a237e; margin-top:28px; font-size:17px;
580
+ border-right:4px solid #1565c0; padding-right:10px;'>
581
+ صفحات مهم بازنشردهنده خبر ایسنا
582
  </h3>
583
+ <p style='color:{CS}; font-size:13px; margin:4px 0 12px 0;'>سورت بر اساس تعداد دنبال‌کننده (دامنه انتشار)</p>
584
  <div style='overflow-x:auto; margin:0 0 24px 0;'>
585
  <table style='width:100%; border-collapse:collapse; font-size:13px;'>
586
  <thead>
 
592
  </tr>
593
  </thead><tbody>"""
594
  for i, (_, row) in enumerate(news_sharers.iterrows()):
595
+ bg = '#fff8e1' if i % 2 == 0 else '#f9f9f9'
596
  html += f"""
597
  <tr style='background:{bg};'>
598
  <td {TD}><b style='color:#0d47a1;'>@{row['نام کاربری']}</b></td>
599
  <td {TD}><b style='color:#e65100;'>{format_number(row['فالوور'])}</b></td>
600
+ <td {TD}><b style='color:{C};'>{row['تعداد_توییت']}</b></td>
601
  <td {TD}>{format_number(row['بازنشر_کل'])}</td>
602
  </tr>"""
603
  html += "</tbody></table></div>"
 
605
  # ===== توییت‌های ایسنا با بیشترین کامنت =====
606
  if not isna_tweet_comments.empty:
607
  html += f"""
608
+ <h3 style='color:#1a237e; margin-top:28px; font-size:17px;
609
+ border-right:4px solid #1565c0; padding-right:10px;'>
610
+ توییت‌های ایسنا با بیشترین واکنش (کامنت)
611
  </h3>
612
  <div style='overflow-x:auto; margin:14px 0 24px 0;'>
613
  <table style='width:100%; border-collapse:collapse; font-size:13px;'>
 
618
  </tr>
619
  </thead><tbody>"""
620
  for i, (_, row) in enumerate(isna_tweet_comments.iterrows()):
621
+ bg = '#fce4ec' if i % 2 == 0 else '#f9f9f9'
622
  html += f"""
623
  <tr style='background:{bg};'>
624
  <td {TD}>{row['تیتر_توییت_ایسنا']}</td>
 
626
  </tr>"""
627
  html += "</tbody></table></div>"
628
 
629
+ # ===== توضیح heatmap =====
630
+ if heatmap_bullets:
631
+ bullets_html = ''.join(
632
+ f"<li style='margin-bottom:6px; color:{C};'>{b}</li>"
633
+ for b in heatmap_bullets
634
+ )
635
+ html += f"""
636
+ <div style='background:#e8f5e9; border-radius:8px; padding:14px 18px;
637
+ margin:10px 0 24px 0; border-right:4px solid #2e7d32;'>
638
+ <p style='font-size:13px; font-weight:bold; color:#1b5e20; margin:0 0 8px 0;'>
639
+ نکات کلیدی نمودار موضوع به تفکیک ساعت:
640
+ </p>
641
+ <ul style='margin:0; padding-right:20px; font-size:13px; line-height:1.9;'>
642
+ {bullets_html}
643
+ </ul>
644
+ </div>"""
645
+
646
  html += "</div>"
647
 
648
  # ==================== نمودارها ====================
649
+ chart_hourly = create_hourly_chart(df) if 'زمان انتشار' in df.columns else go.Figure()
650
+ chart_heatmap = create_hourly_words_heatmap(df) if 'زمان انتشار' in df.columns else go.Figure()
651
+ chart_content = create_content_type_chart(df) if 'نوع محتوا' in df.columns else go.Figure()
652
+ chart_words = create_words_chart(df) if 'متن' in df.columns else go.Figure()
653
 
654
  return html, chart_hourly, chart_heatmap, chart_content, chart_words
655
 
656
  except Exception as e:
657
  import traceback
658
  err = f"""<div style='direction:rtl;font-family:Tahoma;padding:20px;color:#b71c1c;'>
659
+ <h3>خطا در پردازش فایل</h3>
660
+ <p style='background:#ffebee;padding:15px;border-right:4px solid #b71c1c;color:#212121;'>{str(e)}</p>
661
+ <pre style='font-size:11px;color:#424242;'>{traceback.format_exc()}</pre>
662
  </div>"""
663
  return err, None, None, None, None
664
 
 
679
  background:rgba(255,255,255,0.97); border-radius:12px; margin-bottom:10px;
680
  box-shadow:0 2px 10px rgba(0,0,0,0.1);'>
681
  <h1 style='color:#0d47a1; margin-bottom:10px; font-size:26px;'>
682
+ دستیار هوشمند تحلیل توییتر ایسنا
683
  </h1>
684
  <p style='color:#37474f; font-size:15px;'>فایل اکسل توییتر را آپلود کنید تا گزارش کامل دریافت نمایید</p>
685
  <hr style='border:1px solid #1565c0; width:40%; margin:15px auto;'>
 
688
 
689
  with gr.Row():
690
  with gr.Column():
691
+ input_file = gr.File(label="آپلود فایل اکسل توییتر",
692
  file_types=[".xlsx", ".xls"], type="binary")
693
+ submit_btn = gr.Button("شروع تحلیل", variant="primary", size="lg")
694
 
695
  with gr.Row():
696
  with gr.Column():
697
+ output_html = gr.HTML(label="گزارش")
698
 
699
  with gr.Row():
700
  with gr.Column():
701
+ chart_hourly = gr.Plot(label="توزیع ساعتی")
702
  with gr.Column():
703
+ chart_content = gr.Plot(label="نوع محتوا")
704
 
705
  with gr.Row():
706
  with gr.Column():
707
+ chart_words = gr.Plot(label="پرتکرارترین عبارات")
708
 
709
  with gr.Row():
710
  with gr.Column():
711
+ chart_heatmap = gr.Plot(label="موضوع به تفکیک ساعت")
712
 
713
  gr.Markdown("""
714
  <div style='text-align:center; direction:rtl; margin-top:20px; padding:12px;
715
+ color:#424242; border-top:1px solid #e0e0e0; font-family:Tahoma;'>
716
+ <p style='font-size:13px;'>فایل باید شامل ستون‌های «متن»، «نام کاربری»، «تعداد بازنشر» و «تعداد لایک» باشد</p>
717
+ <p style='font-size:11px; margin-top:4px; color:#546e7a;'>سامانه هوشمند ایسنا | تحلیل توییتر | نسخه ۲.۱</p>
718
  </div>
719
  """)
720