aysan98 commited on
Commit
ae4193e
·
verified ·
1 Parent(s): 29671f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +473 -673
app.py CHANGED
@@ -3,136 +3,104 @@ import pandas as pd
3
  import numpy as np
4
  import warnings
5
  import plotly.graph_objects as go
6
- import base64
7
- from io import BytesIO
8
- from PIL import Image, ImageDraw, ImageFont
9
  import plotly.io as pio
10
  from xhtml2pdf import pisa
11
  warnings.filterwarnings('ignore')
12
 
 
 
 
 
13
  def extract_service_name(service_text):
14
  """استخراج نام سرویس و زیرسرویس (قبل و بعد از علامت >)"""
15
  if pd.isna(service_text):
16
  return 'نامشخص', 'نامشخص'
17
-
18
  service_str = str(service_text).strip()
19
-
20
- # جستجو برای انواع مختلف علامت >
21
  separators = ['>', '&gt;', '›', '>', ' > ', '<', '&lt;', '‹', '<', ' < ']
22
-
23
  for sep in separators:
24
  if sep in service_str:
25
  parts = service_str.split(sep)
26
  main_service = parts[0].strip()
27
  sub_service = parts[1].strip() if len(parts) > 1 else 'نامشخص'
28
  return main_service, sub_service
29
-
30
  return service_str, 'ندارد'
31
 
 
32
  def categorize_service(main_service, sub_service, site_value):
33
  """دسته‌بندی سرویس‌ها"""
34
  service_lower = str(main_service).lower().strip()
35
-
36
- # چندرسانه‌ای: عکس، ویدئو، گرافیک، صوت
37
  multimedia_keywords = ['عکس', 'ویدئو', 'ویدیو', 'گرافیک', 'صوت']
38
  if any(keyword in service_lower for keyword in multimedia_keywords):
39
  return 'چندرسانه‌ای', sub_service
40
-
41
- # زبان‌های خارجی: اگر در ستون سایت "ایسنا" نباشد
42
  site_str = str(site_value).lower().strip()
43
  if 'ایسنا' not in site_str and site_str != 'nan':
44
  final_sub = main_service if sub_service == 'ندارد' else sub_service
45
  return 'زبان‌های خارجی', final_sub
46
-
47
  return main_service, sub_service
48
 
 
49
  def categorize_for_isna_table(row):
50
  """دسته‌بندی اخبار برای جدول کل ایسنا"""
51
  service_str = str(row['سرویس_نهایی']).lower().strip()
52
  site_str = str(row.get('سایت', '')).lower().strip()
53
-
54
- # بازار
55
  if 'بازار' in service_str:
56
  return 'بازار'
57
-
58
- # ایسنا+
59
  if 'ایسنا' in service_str and '+' in service_str:
60
  return 'ایسنا+'
61
-
62
- # زبان‌های خارجی
63
  if 'ایسنا' not in site_str and site_str != 'nan' and site_str != '':
64
  return 'زبان‌های خارجی'
65
-
66
- # استان‌ها
67
  if 'استان' in service_str:
68
  return 'استان‌ها'
69
-
70
- # تهران (بقیه اخبار)
71
  return 'تهران'
72
 
 
73
  def custom_round(value):
74
- """گرد کردن سفارشی: کمتر از 0.5 به پایین، بیشتر یا مساوی 0.5 به بالا"""
75
  if value - int(value) < 0.5:
76
  return int(value)
77
  else:
78
  return int(value) + 1
79
 
 
80
  def extract_date_only(datetime_str):
81
- """استخراج فقط تاریخ (روز، ماه، سال) از تاریخ و زمان"""
82
  if pd.isna(datetime_str):
83
  return 'نامشخص'
84
-
85
  try:
86
- # تبدیل به string
87
  date_str = str(datetime_str)
88
-
89
- # اگر datetime object است
90
  if hasattr(datetime_str, 'strftime'):
91
  return datetime_str.strftime('%Y/%m/%d')
92
-
93
- # اگر string است و شامل فاصله است (فرمت تاریخ و زمان)
94
  if ' ' in date_str:
95
- date_part = date_str.split(' ')[0]
96
- return date_part
97
-
98
- # اگر فقط تاریخ است
99
  return date_str
100
  except:
101
  return str(datetime_str)
102
 
 
 
 
 
 
103
  def create_traffic_chart(service_stats):
104
  """ایجاد نمودار میله‌ای stacked با درصدها"""
105
-
106
- # مرتب‌سازی براساس تعداد اخبار برای نمایش بهتر
107
- service_stats_sorted = service_stats.sort_values('تعداد_اخبار_ارسالی', ascending=True)
108
-
109
- # محاسبه اخبار بین 200 تا 1000
110
- service_stats_sorted['تعداد_اخبار_متوسط'] = (
111
- service_stats_sorted['تعداد_اخبار_ارسالی'] -
112
- service_stats_sorted['تعداد_اخبار_پربازدید'] -
113
- service_stats_sorted['ت��داد_اخبار_کم_بازدید']
114
- )
115
-
116
- # محاسبه درصد متوسط به صورتی که جمع کل 100 شود
117
  service_stats_sorted['درصد_اخبار_متوسط'] = (
118
  100 - service_stats_sorted['درصد_اخبار_کم_بازدید'] - service_stats_sorted['درصد_اخبار_پربازدید']
119
  )
120
-
121
  fig = go.Figure()
122
-
123
- # میله اخبار کم‌بازدید (قرمز) - 200 و زیر
124
  fig.add_trace(go.Bar(
125
  y=service_stats_sorted['سرویس'],
126
  x=service_stats_sorted['درصد_اخبار_کم_بازدید'],
127
- name='200 بازدید و کم‌تر',
128
  orientation='h',
129
  marker=dict(color='#ef5350'),
130
  text=[f"{int(p)}%" for p in service_stats_sorted['درصد_اخبار_کم_بازدید']],
131
  textposition='inside',
132
- hovertemplate='<b>%{y}</b><br>200 و زیر: %{x}%<extra></extra>'
133
  ))
134
-
135
- # میله اخبار متوسط (آبی)
136
  fig.add_trace(go.Bar(
137
  y=service_stats_sorted['سرویس'],
138
  x=service_stats_sorted['درصد_اخبار_متوسط'],
@@ -143,8 +111,6 @@ def create_traffic_chart(service_stats):
143
  textposition='inside',
144
  hovertemplate='<b>%{y}</b><br>200-1000: %{x}%<extra></extra>'
145
  ))
146
-
147
- # میله اخبار پربازدید (سبز) - 1000 و بالاتر
148
  fig.add_trace(go.Bar(
149
  y=service_stats_sorted['سرویس'],
150
  x=service_stats_sorted['درصد_اخبار_پربازدید'],
@@ -155,93 +121,76 @@ def create_traffic_chart(service_stats):
155
  textposition='inside',
156
  hovertemplate='<b>%{y}</b><br>1000 و بالاتر: %{x}%<extra></extra>'
157
  ))
158
-
159
  fig.update_layout(
160
  title={
161
  'text': 'نمودار توزیع درصد بازدید اخبار به تفکیک سرویس‌ها',
162
  'font': {'size': 19, 'family': 'Tahoma', 'color': '#1976d2'},
163
- 'x': 0.5,
164
- 'xanchor': 'center'
165
  },
166
  barmode='stack',
167
  xaxis_title='درصد',
168
  yaxis_title='سرویس',
169
  font=dict(family='Tahoma', size=14),
170
  height=max(500, len(service_stats_sorted) * 50),
171
- legend=dict(
172
- orientation="h",
173
- yanchor="bottom",
174
- y=1.02,
175
- xanchor="center",
176
- x=0.5,
177
- font=dict(size=15)
178
- ),
179
  plot_bgcolor='rgba(240,240,240,0.5)',
180
  hovermode='closest',
181
  margin=dict(l=150, r=50, t=100, b=80),
182
  xaxis=dict(range=[0, 100])
183
  )
184
-
185
  fig.update_xaxes(gridcolor='rgba(200,200,200,0.3)')
186
  fig.update_yaxes(gridcolor='rgba(200,200,200,0.3)')
187
-
188
  return fig
189
 
 
 
 
 
 
190
  def html_to_pdf(html_string, pdf_filename):
191
- """تبدیل HTML به PDF"""
192
  with open(pdf_filename, "wb") as pdf_file:
193
  pisa.CreatePDF(html_string, dest=pdf_file)
194
 
 
 
 
 
 
195
  def process_news_data(file):
196
- """پردازش و تحلیل داده‌های خبری - نسخه ماهانه"""
197
-
198
  try:
199
- # خواندن لیست شیت‌ها
200
  excel_file = pd.ExcelFile(file)
201
  sheet_names = excel_file.sheet_names
202
-
203
- # انتخاب شیت مناسب
204
- if 'کلی' in sheet_names:
205
- sheet_name = 'کلی'
206
- else:
207
- sheet_name = sheet_names[0]
208
-
209
- # تشخیص ردیف هدر
210
  df_test = pd.read_excel(file, sheet_name=sheet_name, header=None, nrows=5)
211
  header_row = 0
212
  for i, row in df_test.iterrows():
213
  if 'تیتر' in str(row.values) or 'ناشر' in str(row.values) or 'بازدید' in str(row.values):
214
  header_row = i
215
  break
216
-
217
- # خواندن داده‌ها با هدر صحیح
218
  df = pd.read_excel(file, sheet_name=sheet_name, header=header_row)
219
-
220
- # بررسی ستون‌های مورد نیاز
221
  required_columns = ['بازد��د', 'تیتر', 'سرویس']
222
  missing_columns = [col for col in required_columns if col not in df.columns]
223
-
224
  if missing_columns:
225
- available_info = f"""
226
- <div style='text-align: right; direction: rtl; font-family: Tahoma; padding: 20px;'>
227
  <h3>❌ ستون‌های مورد نیاز یافت نشد</h3>
228
  <p><strong>ستون‌های مفقود:</strong> {', '.join(missing_columns)}</p>
229
  <p><strong>ستون‌های موجود:</strong> {', '.join(list(df.columns))}</p>
230
- </div>
231
- """
232
- return None, available_info, None, None
233
-
234
- # پاکسازی داده‌ها
235
- df_clean = df.dropna(subset=['بازدید', 'تیتر'])
236
  df_clean['بازدید'] = pd.to_numeric(df_clean['بازدید'], errors='coerce')
237
  df_clean = df_clean[df_clean['بازدید'] >= 0]
238
-
239
- # استخراج نام سرویس و زیرسرویس
240
  df_clean[['سرویس_اصلی', 'زیرسرویس']] = df_clean['سرویس'].apply(
241
  lambda x: pd.Series(extract_service_name(x))
242
  )
243
-
244
- # دسته‌بندی سرویس‌ها (چندرسانه‌ای و زبان‌های خارجی)
245
  if 'سایت' in df_clean.columns:
246
  df_clean[['سرویس_نهایی', 'زیرسرویس_نهایی']] = df_clean.apply(
247
  lambda row: pd.Series(categorize_service(row['سرویس_اصلی'], row['زیرسرویس'], row['سایت'])), axis=1
@@ -249,72 +198,33 @@ def process_news_data(file):
249
  else:
250
  df_clean['سرویس_نهایی'] = df_clean['سرویس_اصلی']
251
  df_clean['زیرسرویس_نهایی'] = df_clean['زیرسرویس']
252
-
253
- # دسته‌بندی برای جدول کل ایسنا
254
  df_clean['دسته_ایسنا'] = df_clean.apply(categorize_for_isna_table, axis=1)
255
-
256
- # بررسی وجود ستون تاریخ انتشار
257
- publish_date_col = None
258
- possible_date_cols = ['تاریخ انتشار', 'تاریخ', 'زمان انتشار']
259
- for col in possible_date_cols:
260
- if col in df_clean.columns:
261
- publish_date_col = col
262
- break
263
-
264
- # بررسی وجود ستون نام خبرنگار
265
- reporter_col = None
266
- possible_reporter_cols = ['نام خبرنگار', 'خبرنگار', 'نویسنده']
267
- for col in possible_reporter_cols:
268
- if col in df_clean.columns:
269
- reporter_col = col
270
- break
271
-
272
- # بررسی وجود ستون ناشر
273
- publisher_col = None
274
- possible_publisher_cols = ['ناشر', 'منتشرکننده']
275
- for col in possible_publisher_cols:
276
- if col in df_clean.columns:
277
- publisher_col = col
278
- break
279
-
280
- # بررسی ستون‌های کامنت
281
- comment_cols = {}
282
- comment_col_names = {
283
- 'تعداد_کامنت_ثبت_شده': ['کامنت', 'تعداد کامنت', 'نظرات', 'کامنت ثبت شده'],
284
- 'تعداد_کامنت_منتشرشده': ['کامنت منتشرشده', 'منتشرشده', 'کامنت تایید شده'],
285
- 'تعداد_کامنت_بایگانی': ['کامنت بایگانی', 'بایگانی شده', 'کامنت بایگانی شده']
286
- }
287
-
288
- for key, possible_names in comment_col_names.items():
289
- for col_name in possible_names:
290
- if col_name in df_clean.columns:
291
- comment_cols[key] = col_name
292
- break
293
-
294
- # === آمار کلی ===
295
- total_news_all = len(df_clean)
296
-
297
- # اخبار 1000 و بالاتر - کل
298
- high_traffic_all = df_clean[df_clean['بازدید'] >= 1000]
299
- high_traffic_count_all = len(high_traffic_all)
300
-
301
- # اخبار 200 و زیر - کل
302
- low_traffic_all = df_clean[df_clean['بازدید'] <= 200]
303
- low_traffic_count_all = len(low_traffic_all)
304
-
305
- # === جدول کل ایسنا ===
306
  isna_categories = ['تهران', 'استان‌ها', 'زبان‌های خارجی', 'ایسنا+', 'بازار']
307
  isna_stats_list = []
308
-
309
  for category in isna_categories:
310
  df_cat = df_clean[df_clean['دسته_ایسنا'] == category]
311
-
312
  if len(df_cat) > 0:
313
  count = len(df_cat)
314
- high = len(df_cat[df_cat['بازدید'] >= 1000])
315
- low = len(df_cat[df_cat['بازدید'] <= 200])
316
  share = custom_round((count / total_news_all * 100) if total_news_all > 0 else 0)
317
-
318
  isna_stats_list.append({
319
  'شاخص‌ها': category,
320
  'تعداد_اخبار_ارسالی': count,
@@ -322,8 +232,6 @@ def process_news_data(file):
322
  'تعداد_اخبار_پربازدید': high,
323
  'تعداد_اخبار_کم_بازدید': low
324
  })
325
-
326
- # سطر جمع کل
327
  isna_stats_list.append({
328
  'شاخص‌ها': 'جمع کل',
329
  'تعداد_اخبار_ارسالی': total_news_all,
@@ -331,577 +239,477 @@ def process_news_data(file):
331
  'تعداد_اخبار_پربازدید': high_traffic_count_all,
332
  'تعداد_اخبار_کم_بازدید': low_traffic_count_all
333
  })
334
-
335
  isna_table = pd.DataFrame(isna_stats_list)
336
-
337
- # === آمار تفصیلی سرویس‌ها (بدون ایسنا+، بازار، زبان‌های خارجی) - مثل روزانه ===
 
 
338
  df_services = df_clean[
339
- ~df_clean['سرویس_نهایی'].str.contains('ایسنا\+|بازار|زبان', case=False, na=False)
340
  ]
341
-
342
- total_news = len(df_services)
343
- high_traffic_count = len(df_services[df_services['بازدید'] >= 1000])
344
- high_traffic_percent = (high_traffic_count / total_news * 100) if total_news > 0 else 0
345
- low_traffic_count = len(df_services[df_services['بازدید'] <= 200])
346
- low_traffic_percent = (low_traffic_count / total_news * 100) if total_news > 0 else 0
347
-
348
- service_stats = df_services.groupby('سرویس_نهایی').agg({
349
- 'بازدید': ['count', 'sum', 'mean']
350
- })
351
- service_stats.columns = ['تعداد_اخبار_ارسالی', 'مجموع_بازدید', 'میانگین_بازدید']
352
  service_stats['میانگین_بازدید'] = service_stats['میانگین_بازدید'].round(0).astype(int)
353
-
354
  high_by_service = df_services[df_services['بازدید'] >= 1000].groupby('سرویس_نهایی').size()
355
- service_stats['تعداد_اخبار_پربازدید'] = high_by_service
356
- service_stats['تعداد_اخبار_پربازدید'] = service_stats['تعداد_اخبار_پربازدید'].fillna(0).astype(int)
357
-
358
- service_stats['درصد_اخبار_پربازدید'] = (
359
  service_stats['تعداد_اخبار_پربازدید'] / service_stats['تعداد_اخبار_ارسالی'] * 100
360
  ).apply(custom_round)
361
-
362
- low_by_service = df_services[df_services['بازدید'] <= 200].groupby('سرویس_نهایی').size()
363
- service_stats['تعداد_اخبار_کم_بازدید'] = low_by_service
364
- service_stats['تعداد_اخبار_کم_بازدید'] = service_stats['تعداد_اخبار_کم_بازدید'].fillna(0).astype(int)
365
-
366
- service_stats['درصد_اخبار_کم_بازدید'] = (
367
  service_stats['تعداد_اخبار_کم_بازدید'] / service_stats['تعداد_اخبار_ارسالی'] * 100
368
  ).apply(custom_round)
369
-
370
- service_stats = service_stats.sort_values('تعداد_اخبار_ارسالی', ascending=False)
371
- service_stats = service_stats.reset_index()
372
  service_stats = service_stats.rename(columns={'سرویس_نهایی': 'سرویس'})
373
-
374
- # === نمودار توزیع درصد بازدید (همه سرویس‌ها) ===
375
- all_service_stats = df_clean.groupby('سرویس_نهایی').agg({
376
- 'بازدید': ['count']
377
- })
378
- all_service_stats.columns = ['تعداد_اخبار_ارسالی']
379
-
380
- high_by_all_service = df_clean[df_clean['بازدید'] >= 1000].groupby('سرویس_نهایی').size()
381
- all_service_stats['تعداد_اخبار_پربازدید'] = high_by_all_service
382
- all_service_stats['تعداد_اخبار_پربازدید'] = all_service_stats['تعداد_اخبار_پربازدید'].fillna(0).astype(int)
383
-
384
- all_service_stats['درصد_اخبار_پربازدید'] = (
385
  all_service_stats['تعداد_اخبار_پربازدید'] / all_service_stats['تعداد_اخبار_ارسالی'] * 100
386
  ).apply(custom_round)
387
-
388
- low_by_all_service = df_clean[df_clean['بازدید'] <= 200].groupby('سرویس_نهایی').size()
389
- all_service_stats['تعداد_اخبار_کم_بازدید'] = low_by_all_service
390
- all_service_stats['تعداد_اخبار_کم_بازدید'] = all_service_stats['تعداد_اخبار_کم_بازدید'].fillna(0).astype(int)
391
-
392
- all_service_stats['درصد_اخبار_کم_بازدید'] = (
393
  all_service_stats['تعداد_اخبار_کم_بازدید'] / all_service_stats['تعداد_اخبار_ارسالی'] * 100
394
  ).apply(custom_round)
395
-
396
- all_service_stats = all_service_stats.reset_index()
397
- all_service_stats = all_service_stats.rename(columns={'سرویس_نهایی': 'سرویس'})
398
-
399
  chart = create_traffic_chart(all_service_stats)
400
-
401
- # === 100 خبر پربازدید ===
 
 
402
  top_100_cols = ['تیتر', 'زیرسرویس_نهایی', 'بازدید']
403
- if publish_date_col:
404
- top_100_cols.insert(2, publish_date_col)
405
- if reporter_col:
406
- top_100_cols.append(reporter_col)
407
- if publisher_col:
408
- top_100_cols.append(publisher_col)
409
-
410
  top_100_news = df_clean.nlargest(100, 'بازدید')[top_100_cols].copy()
411
-
412
  if publish_date_col:
413
  top_100_news['تاریخ_انتشار'] = top_100_news[publish_date_col].apply(extract_date_only)
414
  top_100_news = top_100_news.drop(columns=[publish_date_col])
415
-
416
- top_100_news = top_100_news.rename(columns={
417
- 'زیرسرویس_نهایی': 'زیرسرویس',
418
- reporter_col: 'نام خبرنگار' if reporter_col else 'نام خبرنگار',
419
- publisher_col: 'ناشر' if publisher_col else 'ناشر'
420
- })
421
-
422
- # === میانگین بازدید (بدون زبان‌ها، بازار، ایسنا+) ===
 
423
  df_avg = df_clean[
424
- ~df_clean['سرویس_نهایی'].str.contains('ایسنا\+|بازار|زبان', case=False, na=False)
425
  ]
426
-
427
- avg_stats = df_avg.groupby('سرویس_نهایی').agg({
428
- 'بازدید': ['count', 'sum', 'mean']
429
- })
430
- avg_stats.columns = ['تعداد_خبر', 'مجموع_بازدید', 'میانگین_بازدید']
431
  avg_stats['میانگین_بازدید'] = avg_stats['میانگین_بازدید'].round(0).astype(int)
432
- avg_stats = avg_stats.sort_values('تعداد_خبر', ascending=False)
433
- avg_stats = avg_stats.reset_index()
434
  avg_stats = avg_stats.rename(columns={'سرویس_نهایی': 'عنوان_اداره'})
435
-
436
- # === آمار کامنت ===
437
- comment_stats_list = []
438
- if comment_cols:
439
- for service in df_clean['سرویس_نهایی'].unique():
440
- df_service = df_clean[df_clean['سرویس_نهایی'] == service]
441
-
442
- total_news_service = len(df_service)
443
-
444
- # تعداد اخبار دارای کامنت
445
- if 'تعداد_کامنت_ثبت_شده' in comment_cols:
446
- df_service['کامنت_عددی'] = pd.to_numeric(df_service[comment_cols['تعداد_کامنت_ثبت_شده']], errors='coerce').fillna(0)
447
- news_with_comment = len(df_service[df_service['کامنت_عددی'] > 0])
448
- total_comments = int(df_service['کامنت_عددی'].sum())
449
- else:
450
- news_with_comment = 0
451
- total_comments = 0
452
-
453
- # کامنت منتشرشده
454
- if 'تعداد_کامنت_منتشرشده' in comment_cols:
455
- df_service['منتشرشده_عددی'] = pd.to_numeric(df_service[comment_cols['تعداد_کامنت_منتشرشده']], errors='coerce').fillna(0)
456
- published_comments = int(df_service['منتشرشده_عددی'].sum())
457
- else:
458
- published_comments = 0
459
-
460
- # کامنت بایگانی
461
- if 'تعداد_کامنت_بایگانی' in comment_cols:
462
- df_service['بایگانی_عددی'] = pd.to_numeric(df_service[comment_cols['تعداد_کامنت_بایگانی']], errors='coerce').fillna(0)
463
- archived_comments = int(df_service['بایگانی_عددی'].sum())
464
- else:
465
- archived_comments = 0
466
-
467
- # کامنت دیده نشده
468
- unseen_comments = total_comments - published_comments - archived_comments
469
-
470
- comment_stats_list.append({
471
- 'عنوان_اداره': service,
472
- 'تعداد_اخبار_ارسالی': total_news_service,
473
- 'تعداد_اخبار_دارای_کامنت': news_with_comment,
474
- 'تعداد_کامنت_ثبت_شده': total_comments,
475
- 'تعداد_کامنت_منتشرشده': published_comments,
476
- 'تعداد_کامنت_بایگانی': archived_comments,
477
- 'تعداد_کامنت_دیده_نشده': unseen_comments
478
- })
479
-
480
- comment_stats = pd.DataFrame(comment_stats_list) if comment_stats_list else None
481
-
482
- # === آمار زیرسرویس‌ها براساس سرویس اصلی ===
483
- subservice_by_service = []
484
-
485
  for service in df_clean['سرویس_نهایی'].unique():
486
  df_service = df_clean[df_clean['سرویس_نهایی'] == service]
487
-
488
  for subservice in df_service['زیرسرویس_نهایی'].unique():
489
  df_sub = df_service[df_service['زیرسرویس_نهایی'] == subservice]
490
-
491
- count = len(df_sub)
492
- high = len(df_sub[df_sub['بازدید'] >= 1000])
493
- low = len(df_sub[df_sub['بازدید'] <= 200])
494
-
495
- high_percent = custom_round((high / count * 100) if count > 0 else 0)
496
- low_percent = custom_round((low / count * 100) if count > 0 else 0)
497
-
498
- subservice_by_service.append({
499
- 'سرویس_اصلی': service,
500
- 'زیرسرویس': subservice,
501
  'تعداد_اخبار_ارسالی': count,
502
- 'اخبار_بالای_هزار': high,
503
- 'سهم_بازدید_به_کل': high_percent,
504
- 'اخبار_زیر_200': low,
505
- 'سهم_کم_بازدید_به_کل': low_percent
506
  })
507
-
508
- subservice_table = pd.DataFrame(subservice_by_service)
509
- subservice_table = subservice_table.sort_values(['سرویس_اصلی', 'تعداد_اخبار_ارسالی'], ascending=[True, False])
510
-
511
- # ذخیره در فایل اکسل
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
512
  output_filename = 'نتایج_تحلیل_ماهانه.xlsx'
513
  with pd.ExcelWriter(output_filename, engine='openpyxl') as writer:
514
- isna_table.to_excel(writer, sheet_name='کل_ایسنا', index=False)
515
- service_stats.to_excel(writer, sheet_name='آمار_تفصیلی_سرویس_ها', index=False)
516
- all_service_stats.to_excel(writer, sheet_name='آمار_همه_سرویس_ها', index=False)
517
- top_100_news.to_excel(writer, sheet_name='100_خبر_پربازدید', index=False)
518
- avg_stats.to_excel(writer, sheet_name='میانگین_بازدید', index=False)
519
- if comment_stats is not None:
520
- comment_stats.to_excel(writer, sheet_name='آمار_کامنت', index=False)
521
- subservice_table.to_excel(writer, sheet_name='زیرسرویس_ها_براساس_سرویس', index=False)
522
-
523
- # === تولید گزارش HTML ===
524
- summary_html = f"""
525
- <div style='direction: rtl; font-family: Tahoma, Arial; text-align: right; padding: 20px; background-color: white; page-break-inside: avoid;'>
526
- <h2 style='text-align: center; color: #1976d2; border-bottom: 3px solid #1976d2; padding-bottom: 10px;'>
 
 
 
 
527
  گزارش ماهانه عملکرد ایسنا
528
  </h2>
529
-
530
- <h3 style='color: #388e3c; margin-top: 30px;'>📈 آمار کلی</h3>
531
- <h4 style='color: #0d47a1; margin-top: 20px; background-color: #e3f2fd; padding: 15px; border-radius: 8px;'>
 
 
 
532
  📊 جدول تعداد کل اخبار ارسالی و وضعیت بازدید کل ایسنا
533
  </h4>
 
 
 
 
 
 
 
 
 
 
 
534
  """
535
-
536
- # جدول کل ایسنا
537
- isna_html = """
538
- <div style='overflow-x: auto; margin: 20px 0; page-break-inside: avoid;'>
539
- <table style='width: 100%; min-width: 900px; border-collapse: collapse; box-shadow: 0 2px 8px rgba(0,0,0,0.15); font-size: 15px; background-color: white;'>
540
- <thead>
541
- <tr style='background-color: #1976d2;'>
542
- <th style='padding: 15px 20px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; min-width: 120px; color: white;'>شاخص‌ها</th>
543
- <th style='padding: 15px 20px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; min-width: 150px; color: white;'>تعداد اخبار ارسالی</th>
544
- <th style='padding: 15px 20px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; min-width: 120px; color: white;'>سهم از کل</th>
545
- <th style='padding: 15px 20px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; min-width: 170px; color: white;'>تعداد اخبار پربازدید</th>
546
- <th style='padding: 15px 20px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; min-width: 170px; color: white;'>تعداد اخبار کم‌بازدید</th>
547
- </tr>
548
- </thead>
549
- <tbody>
550
- """
551
-
552
- for idx, row in isna_table.iterrows():
553
- if row['شاخص‌ها'] == 'جمع کل':
554
- bg_color = '#1976d2'
555
- text_color = 'white'
556
- font_weight = 'bold'
557
- border_color = '#1565c0'
558
- else:
559
- bg_color = '#e3f2fd'
560
- text_color = '#000000'
561
- font_weight = 'normal'
562
- border_color = '#90caf9'
563
-
564
- isna_html += f"""
565
- <tr style='background-color: {bg_color};'>
566
- <td style='padding: 12px 20px; border: 2px solid {border_color}; text-align: right; font-weight: {font_weight}; color: {text_color};'>{row['شاخص‌ها']}</td>
567
- <td style='padding: 12px 20px; border: 2px solid {border_color}; text-align: right; font-weight: {font_weight}; color: {text_color};'>{int(row['تعداد_اخبار_ارسالی']):,}</td>
568
- <td style='padding: 12px 20px; border: 2px solid {border_color}; text-align: right; font-weight: {font_weight}; color: {text_color};'>{int(row['سهم_از_کل'])}%</td>
569
- <td style='padding: 12px 20px; border: 2px solid {border_color}; text-align: right; font-weight: {font_weight}; color: {text_color};'>{int(row['تعداد_اخبار_پربازدید']):,}</td>
570
- <td style='padding: 12px 20px; border: 2px solid {border_color}; text-align: right; font-weight: {font_weight}; color: {text_color};'>{int(row['تعداد_اخبار_کم_بازدید']):,}</td>
571
- </tr>
572
- """
573
-
574
- isna_html += """
575
- </tbody>
576
- </table>
577
- </div>
578
- """
579
- summary_html += isna_html
580
-
581
- # آمار تفصیلی سرویس‌ها (مثل روزانه)
582
  summary_html += """
583
- <h3 style='color: #7b1fa2; margin-top: 30px;'>📋 آمار تفصیلی سرویس‌ها</h3>
584
- <p style='color: #666; font-size: 13px; margin-bottom: 10px;'>(بدون احتساب ایسنا+، بازار و زبان‌های خارجی)</p>
 
 
 
 
 
 
 
 
 
 
 
 
585
  """
586
-
587
- # محاسبه مجموع برای ردیف جمع کل
588
- total_news_count = service_stats['تعداد_اخبار_ارسالی'].sum()
589
- total_high_traffic = service_stats['تعداد_اخبار_پربازدید'].sum()
590
- total_low_traffic = service_stats['تعداد_اخبار_کم_بازدید'].sum()
591
- total_high_percent = custom_round((total_high_traffic / total_news_count * 100) if total_news_count > 0 else 0)
592
- total_low_percent = custom_round((total_low_traffic / total_news_count * 100) if total_news_count > 0 else 0)
593
-
594
- service_html = """
595
- <div style='overflow-x: auto; margin: 20px 0; page-break-inside: avoid;'>
596
- <table style='width: 100%; min-width: 900px; border-collapse: collapse; box-shadow: 0 2px 4px rgba(0,0,0,0.1); font-size: 14px; background-color: white;'>
597
- <thead>
598
- <tr style='background-color: #1976d2;'>
599
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; color: white;'>سرویس</th>
600
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; color: white;'>تعداد اخبار</th>
601
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; color: white;'>اخبار پربازدید</th>
602
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; color: white;'>درصد پربازدید</th>
603
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; color: white;'>اخبار کم‌بازدید</th>
604
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; color: white;'>درصد کم‌بازدید</th>
605
- </tr>
606
- </thead>
607
- <tbody>
608
- """
609
-
610
- for idx, row in service_stats.iterrows():
611
- service_html += f"""
612
- <tr style='background-color: #e3f2fd;'>
613
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; font-weight: bold; color: #000;'>{row['سرویس']}</td>
614
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>{int(row['تعداد_اخبار_ارسالی']):,}</td>
615
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; background-color: #c8e6c9; color: #000;'>{int(row['تعداد_اخبار_پربازدید']):,}</td>
616
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; background-color: #c8e6c9; color: #000;'>{int(row['درصد_اخبار_پربازدید'])}%</td>
617
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; background-color: #ffcdd2; color: #000;'>{int(row['تعداد_اخبار_کم_بازدید']):,}</td>
618
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; background-color: #ffcdd2; color: #000;'>{int(row['درصد_اخبار_کم_بازدید'])}%</td>
619
- </tr>
620
- """
621
-
622
- # اضافه کردن ردیف جمع کل
623
- service_html += f"""
624
- <tr style='background-color: #1976d2;'>
625
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>جمع کل</td>
626
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_news_count):,}</td>
627
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_high_traffic):,}</td>
628
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_high_percent)}%</td>
629
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_low_traffic):,}</td>
630
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_low_percent)}%</td>
631
- </tr>
632
- </tbody>
633
- </table>
634
- </div>
635
- """
636
-
637
- summary_html += service_html
638
-
639
- # آمار زیرسرویس‌ها براساس سرویس اصلی
640
  summary_html += """
641
- <h3 style='color: #d32f2f; margin-top: 30px;'>⭐ تعداد اخبار ارسالی زیرسرویس‌ها، پربازدید و کم‌بازدید</h3>
642
- <div style='overflow-x: auto; margin: 20px 0; page-break-inside: avoid;'>
643
- <table style='width: 100%; min-width: 900px; border-collapse: collapse; box-shadow: 0 2px 4px rgba(0,0,0,0.1); font-size: 14px; background-color: white;'>
644
- <thead>
645
- <tr style='background-color: #1976d2;'>
646
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; color: white;'>زیرسرویس</th>
647
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; color: white;'>تعداد اخبار ارسالی</th>
648
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; color: white;'>اخبار بالای هزار بازدید</th>
649
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; color: white;'>سهم بازدید به کل اخبار</th>
650
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; color: white;'>اخبار زیر 200 بازدید</th>
651
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; white-space: nowrap; color: white;'>سهم کم بازدید به کل اخبار</th>
652
- </tr>
653
- </thead>
654
- <tbody>
 
655
  """
656
-
657
- # محاسبه جمع کل برای زیرسرویس‌ها
658
- total_subservice_news = subservice_table['تعداد_اخبار_ارسالی'].sum()
659
- total_subservice_high = subservice_table['اخبار_بالای_هزار'].sum()
660
- total_subservice_low = subservice_table['اخبار_زیر_200'].sum()
661
- total_subservice_high_percent = custom_round((total_subservice_high / total_subservice_news * 100) if total_subservice_news > 0 else 0)
662
- total_subservice_low_percent = custom_round((total_subservice_low / total_subservice_news * 100) if total_subservice_news > 0 else 0)
663
-
664
  current_service = None
665
- for idx, row in subservice_table.iterrows():
666
- # اگر سرویس جدید است، خط جدا کننده اضافه کن
667
- if current_service != row['سرویس_اصلی']:
668
- if current_service is not None:
669
- summary_html += """
670
- <tr style='background-color: #37474f; height: 3px;'>
671
- <td colspan='6' style='padding: 0; border: none;'></td>
672
- </tr>
673
- """
674
- current_service = row['سرویس_اصلی']
675
-
676
- summary_html += f"""
677
- <tr style='background-color: #e3f2fd;'>
678
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; font-weight: bold; color: #000;'>{row['زیرسرویس']}</td>
679
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>{int(row['تعداد_اخبار_ارسالی']):,}</td>
680
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; background-color: #c8e6c9; color: #000;'>{int(row['اخبار_بالای_هزار']):,}</td>
681
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; background-color: #c8e6c9; color: #000;'>{int(row['سهم_بازدید_به_کل'])}%</td>
682
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; background-color: #ffcdd2; color: #000;'>{int(row['اخبار_زیر_200']):,}</td>
683
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; background-color: #ffcdd2; color: #000;'>{int(row['سهم_کم_بازدید_به_کل'])}%</td>
684
- </tr>
685
- """
686
-
687
- # اضافه کردن ردیف جمع کل
 
 
 
 
 
 
 
 
 
688
  summary_html += f"""
689
- <tr style='background-color: #1976d2;'>
690
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>جمع کل</td>
691
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_subservice_news):,}</td>
692
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_subservice_high):,}</td>
693
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_subservice_high_percent)}%</td>
694
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_subservice_low):,}</td>
695
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_subservice_low_percent)}%</td>
696
- </tr>
697
- </tbody>
698
- </table>
699
- </div>
700
- """
701
-
702
- # 100 خبر پربازدید
703
  summary_html += """
704
- <h3 style='color: #ff6f00; margin-top: 30px;'>🏆 100 خبر پربازدید ایسنا</h3>
705
- <div style='overflow-x: auto; margin: 20px 0; page-break-inside: avoid;'>
706
- <table style='width: 100%; min-width: 900px; border-collapse: collapse; box-shadow: 0 2px 4px rgba(0,0,0,0.1); font-size: 14px; background-color: white;'>
707
- <thead>
708
- <tr style='background-color: #1976d2;'>
709
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>تیتر خبر</th>
710
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>زیرسرویس</th>
711
  """
712
-
713
  if publish_date_col:
714
- summary_html += "<th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>تاریخ انتشار</th>"
715
-
716
- summary_html += "<th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>بازدید</th>"
717
-
718
  if reporter_col:
719
- summary_html += "<th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>نام خبرنگار</th>"
720
-
721
  if publisher_col:
722
- summary_html += "<th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>ناشر</th>"
723
-
724
- summary_html += """
725
- </tr>
726
- </thead>
727
- <tbody>
728
- """
729
-
730
- for idx, row in top_100_news.iterrows():
731
  summary_html += f"""
732
- <tr style='background-color: #e3f2fd;'>
733
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>{row['تیتر']}</td>
734
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>{row['زیرسرویس']}</td>
735
- """
736
-
737
- if 'تاریخ_انتشار' in row:
738
- summary_html += f"<td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>{row['تاریخ_انتشار']}</td>"
739
-
740
- summary_html += f"<td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; font-weight: bold; color: #d32f2f;'>{int(row['بازدید']):,}</td>"
741
-
742
- if 'نام خبرنگار' in row and pd.notna(row['نام خبرنگار']):
743
- summary_html += f"<td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>{row['نام خبرنگار']}</td>"
744
- elif reporter_col:
745
- summary_html += "<td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>-</td>"
746
-
747
- if 'ناشر' in row and pd.notna(row['ناشر']):
748
- summary_html += f"<td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>{row['ناشر']}</td>"
749
- elif publisher_col:
750
- summary_html += "<td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>-</td>"
751
-
752
  summary_html += "</tr>"
753
-
 
 
754
  summary_html += """
755
- </tbody>
756
- </table>
757
- </div>
 
 
 
 
 
758
  """
759
-
760
- # میانگین بازدید
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
761
  summary_html += """
762
- <h3 style='color: #00695c; margin-top: 30px;'>📊 میانگین بازدید</h3>
763
- <div style='overflow-x: auto; margin: 20px 0; page-break-inside: avoid;'>
764
- <table style='width: 100%; min-width: 900px; border-collapse: collapse; box-shadow: 0 2px 4px rgba(0,0,0,0.1); font-size: 14px; background-color: white;'>
765
- <thead>
766
- <tr style='background-color: #1976d2;'>
767
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>عنوان اداره</th>
768
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>تعداد خبر</th>
769
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>مجموع بازدید</th>
770
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>میانگین بازدید</th>
771
- </tr>
772
- </thead>
773
- <tbody>
774
  """
775
-
776
- total_avg_news = avg_stats['تعداد_خبر'].sum()
777
- total_avg_visits = avg_stats['مجموع_بازدید'].sum()
778
- total_avg_average = custom_round(total_avg_visits / total_avg_news) if total_avg_news > 0 else 0
779
-
780
- for idx, row in avg_stats.iterrows():
781
  summary_html += f"""
782
- <tr style='background-color: #e3f2fd;'>
783
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; font-weight: bold; color: #000;'>{row['عنوان_اداره']}</td>
784
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>{int(row['تعداد_خبر']):,}</td>
785
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>{int(row['مجموع_بازدید']):,}</td>
786
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; font-weight: bold; color: #1976d2;'>{int(row['میانگین_بازدید']):,}</td>
787
- </tr>
788
- """
789
-
790
- # ردیف جمع کل
791
  summary_html += f"""
792
- <tr style='background-color: #1976d2;'>
793
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>جمع کل</td>
794
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_avg_news):,}</td>
795
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_avg_visits):,}</td>
796
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_avg_average):,}</td>
797
- </tr>
798
- </tbody>
799
- </table>
800
- </div>
801
- """
802
-
803
- # آمار کامنت
804
- if comment_stats is not None and len(comment_stats) > 0:
805
- summary_html += """
806
- <h3 style='color: #6a1b9a; margin-top: 30px;'>💬 کامنت</h3>
807
- <div style='overflow-x: auto; margin: 20px 0; page-break-inside: avoid;'>
808
- <table style='width: 100%; min-width: 900px; border-collapse: collapse; box-shadow: 0 2px 4px rgba(0,0,0,0.1); font-size: 14px; background-color: white;'>
809
- <thead>
810
- <tr style='background-color: #1976d2;'>
811
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>عنوان اداره</th>
812
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>تعداد اخبار ارسالی</th>
813
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>تعداد اخبار دارای کامنت</th>
814
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>تعداد کامنت ثبت شده</th>
815
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>تعداد کامنت منتشرشده</th>
816
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>تعداد کامنت بایگانی شده</th>
817
- <th style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; font-weight: bold; color: white;'>تعداد کامنت دیده نشده</th>
818
- </tr>
819
- </thead>
820
- <tbody>
821
- """
822
-
823
- total_comment_news = comment_stats['تعداد_اخبار_ارسالی'].sum()
824
- total_news_with_comment = comment_stats['تعداد_اخبار_دارای_کامنت'].sum()
825
- total_comments_submitted = comment_stats['تعداد_کامنت_ثبت_شده'].sum()
826
- total_comments_published = comment_stats['تعداد_کامنت_منتشرشده'].sum()
827
- total_comments_archived = comment_stats['تعداد_کامنت_بایگانی'].sum()
828
- total_comments_unseen = comment_stats['تعداد_کامنت_دیده_نشده'].sum()
829
-
830
- for idx, row in comment_stats.iterrows():
831
- summary_html += f"""
832
- <tr style='background-color: #e3f2fd;'>
833
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; font-weight: bold; color: #000;'>{row['عنوان_اداره']}</td>
834
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>{int(row['تعداد_اخبار_ارسالی']):,}</td>
835
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>{int(row['تعداد_اخبار_دارای_کامنت']):,}</td>
836
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; color: #000;'>{int(row['تعداد_کامنت_ثبت_شده']):,}</td>
837
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; background-color: #c8e6c9; color: #000;'>{int(row['تعداد_کامنت_منتشرشده']):,}</td>
838
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; background-color: #fff9c4; color: #000;'>{int(row['تعداد_کامنت_بایگانی']):,}</td>
839
- <td style='padding: 10px 15px; border: 1px solid #90caf9; text-align: right; background-color: #ffcdd2; color: #000;'>{int(row['تعداد_کامنت_دیده_نشده']):,}</td>
840
- </tr>
841
- """
842
-
843
- # ردیف جمع کل
844
- summary_html += f"""
845
- <tr style='background-color: #1976d2;'>
846
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>جمع کل</td>
847
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_comment_news):,}</td>
848
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_news_with_comment):,}</td>
849
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_comments_submitted):,}</td>
850
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_comments_published):,}</td>
851
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_comments_archived):,}</td>
852
- <td style='padding: 12px 15px; border: 2px solid #1565c0; text-align: right; color: white; font-weight: bold;'>{int(total_comments_unseen):,}</td>
853
- </tr>
854
- </tbody>
855
- </table>
856
- </div>
857
- """
858
-
859
  summary_html += """
860
- <div style='text-align: center; margin-top: 40px; padding: 20px; background-color: #e8f5e9; border-radius: 8px;'>
861
- <h3 style='color: #2e7d32;'>✅ فایل اکسل با جزئیات کامل آماده دانلود است</h3>
862
- <p style='color: #555;'>شامل: جدول کل ایسنا | آمار تفصیلی سرویس‌ها | 100 خبر پربازدید | میانگین بازدید | آمار کامنت | زیرسرویس‌ها</p>
 
863
  </div>
864
- </div>
865
- """
866
-
867
- # تولید فایل PDF
868
  pdf_filename = 'گزارش_ماهانه_ایسنا.pdf'
869
  try:
870
  html_to_pdf(summary_html, pdf_filename)
871
  except Exception as e:
872
  print(f"خطا در تولید PDF: {str(e)}")
873
  pdf_filename = None
874
-
875
  return output_filename, summary_html, chart, pdf_filename
876
-
877
  except Exception as e:
 
878
  error_html = f"""
879
- <div style='direction: rtl; text-align: right; font-family: Tahoma; padding: 20px;'>
880
- <h3 style='color: #d32f2f;'>❌ خطا در پردازش فایل</h3>
881
- <p style='background-color: #ffebee; padding: 15px; border-right: 4px solid #d32f2f;'>{str(e)}</p>
882
- <p>لطفاً فرمت فایل را بررسی کنید و مجدداً تلاش نمایید.</p>
883
- </div>
884
- """
885
  return None, error_html, None, None
886
 
 
 
887
  # رابط کاربری Gradio
 
 
888
  custom_css = """
889
  .gradio-container {
890
  direction: rtl;
891
- background-image: url('https://img.freepik.com/free-vector/gradient-brain-background_23-2150516335.jpg?semt=ais_hybrid&w=740&q=80');
892
  background-size: cover;
893
  background-position: center;
894
  background-repeat: no-repeat;
895
  background-attachment: fixed;
896
  }
897
  .contain {
898
- background-color: rgba(255, 255, 255, 0.95);
899
  border-radius: 15px;
900
  padding: 30px;
901
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
902
  }
903
  #header-box {
904
- background-color: rgba(255, 255, 255, 0.98);
905
  border-radius: 10px;
906
  padding: 25px;
907
  margin-bottom: 20px;
@@ -910,16 +718,14 @@ custom_css = """
910
  """
911
 
912
  with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
913
- gr.HTML(
914
- """
915
- <div id="header-box" style='text-align: center; direction: rtl; font-family: Tahoma;'>
916
- <h1 style='color: #1976d2; margin-bottom: 15px; font-size: 28px;'>دستیار هوشمند اتاق خبر - گزارشگیری ماهانه</h1>
917
- <p style='font-size: 16px; color: #555; line-height: 1.8;'>برای شروع گزارشگیری روی باکس زیر کلیک کرده و فایل لیست تولید و آمار بازدید را وارد نمایید</p>
918
- <hr style='border: 1px solid #1976d2; width: 50%; margin: 20px auto;'>
919
  </div>
920
- """
921
- )
922
-
923
  with gr.Row():
924
  with gr.Column():
925
  input_file = gr.File(
@@ -927,34 +733,28 @@ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
927
  file_types=[".xlsx", ".xls"],
928
  type="binary"
929
  )
930
- submit_btn = gr.Button(
931
- "🚀 شروع تحلیل آماری",
932
- variant="primary",
933
- size="lg",
934
- elem_id="submit-button"
935
- )
936
-
937
  with gr.Row():
938
  with gr.Column():
939
- output_html = gr.HTML(label="📊 نتایج تحلیل")
940
  output_chart = gr.Plot(label="📊 نمودار توزیع درصد بازدید اخبار به تفکیک سرویس‌ها")
941
- output_file = gr.File(label="💾 دانلود فایل اکسل نتایج کامل")
942
- output_pdf = gr.File(label="📄 دانلود گزارش PDF")
943
-
944
  submit_btn.click(
945
  fn=process_news_data,
946
  inputs=input_file,
947
  outputs=[output_file, output_html, output_chart, output_pdf]
948
  )
949
-
950
- gr.Markdown(
951
- """
952
- <div style='text-align: center; direction: rtl; margin-top: 40px; padding: 20px; color: #777; border-top: 2px solid #e0e0e0; background-color: rgba(255, 255, 255, 0.95); border-radius: 10px;'>
953
- <p style='font-size: 14px;'>💡 <strong>راهنما:</strong> فایل باید شامل ستون‌های «تیتر»، «بازدید» و «سرویس» باشد</p>
954
- <p style='font-size: 12px; margin-top: 10px;'>سامانه هوشمند ایسنا - نسخه ماهانه 1.0 | طراحی شده با ❤️</p>
955
  </div>
956
- """
957
- )
958
 
959
  if __name__ == "__main__":
960
  demo.launch()
 
3
  import numpy as np
4
  import warnings
5
  import plotly.graph_objects as go
 
 
 
6
  import plotly.io as pio
7
  from xhtml2pdf import pisa
8
  warnings.filterwarnings('ignore')
9
 
10
+ # ─────────────────────────────────────────────
11
+ # توابع کمکی
12
+ # ─────────────────────────────────────────────
13
+
14
  def extract_service_name(service_text):
15
  """استخراج نام سرویس و زیرسرویس (قبل و بعد از علامت >)"""
16
  if pd.isna(service_text):
17
  return 'نامشخص', 'نامشخص'
 
18
  service_str = str(service_text).strip()
 
 
19
  separators = ['>', '&gt;', '›', '>', ' > ', '<', '&lt;', '‹', '<', ' < ']
 
20
  for sep in separators:
21
  if sep in service_str:
22
  parts = service_str.split(sep)
23
  main_service = parts[0].strip()
24
  sub_service = parts[1].strip() if len(parts) > 1 else 'نامشخص'
25
  return main_service, sub_service
 
26
  return service_str, 'ندارد'
27
 
28
+
29
  def categorize_service(main_service, sub_service, site_value):
30
  """دسته‌بندی سرویس‌ها"""
31
  service_lower = str(main_service).lower().strip()
 
 
32
  multimedia_keywords = ['عکس', 'ویدئو', 'ویدیو', 'گرافیک', 'صوت']
33
  if any(keyword in service_lower for keyword in multimedia_keywords):
34
  return 'چندرسانه‌ای', sub_service
 
 
35
  site_str = str(site_value).lower().strip()
36
  if 'ایسنا' not in site_str and site_str != 'nan':
37
  final_sub = main_service if sub_service == 'ندارد' else sub_service
38
  return 'زبان‌های خارجی', final_sub
 
39
  return main_service, sub_service
40
 
41
+
42
  def categorize_for_isna_table(row):
43
  """دسته‌بندی اخبار برای جدول کل ایسنا"""
44
  service_str = str(row['سرویس_نهایی']).lower().strip()
45
  site_str = str(row.get('سایت', '')).lower().strip()
 
 
46
  if 'بازار' in service_str:
47
  return 'بازار'
 
 
48
  if 'ایسنا' in service_str and '+' in service_str:
49
  return 'ایسنا+'
 
 
50
  if 'ایسنا' not in site_str and site_str != 'nan' and site_str != '':
51
  return 'زبان‌های خارجی'
 
 
52
  if 'استان' in service_str:
53
  return 'استان‌ها'
 
 
54
  return 'تهران'
55
 
56
+
57
  def custom_round(value):
58
+ """گرد کردن سفارشی"""
59
  if value - int(value) < 0.5:
60
  return int(value)
61
  else:
62
  return int(value) + 1
63
 
64
+
65
  def extract_date_only(datetime_str):
66
+ """استخراج فقط تاریخ از تاریخ و زمان"""
67
  if pd.isna(datetime_str):
68
  return 'نامشخص'
 
69
  try:
 
70
  date_str = str(datetime_str)
 
 
71
  if hasattr(datetime_str, 'strftime'):
72
  return datetime_str.strftime('%Y/%m/%d')
 
 
73
  if ' ' in date_str:
74
+ return date_str.split(' ')[0]
 
 
 
75
  return date_str
76
  except:
77
  return str(datetime_str)
78
 
79
+
80
+ # ─────────────────────────────────────────────
81
+ # نمودار
82
+ # ─────────────────────────────────────────────
83
+
84
  def create_traffic_chart(service_stats):
85
  """ایجاد نمودار میله‌ای stacked با درصدها"""
86
+ service_stats_sorted = service_stats.sort_values('تعداد_اخبار_ارسالی', ascending=True).copy()
 
 
 
 
 
 
 
 
 
 
 
87
  service_stats_sorted['درصد_اخبار_متوسط'] = (
88
  100 - service_stats_sorted['درصد_اخبار_کم_بازدید'] - service_stats_sorted['درصد_اخبار_پربازدید']
89
  )
90
+
91
  fig = go.Figure()
92
+
93
+ # FIX: label now says "زیر 200" (strictly less than 200)
94
  fig.add_trace(go.Bar(
95
  y=service_stats_sorted['سرویس'],
96
  x=service_stats_sorted['درصد_اخبار_کم_بازدید'],
97
+ name='زیر 200 بازدید',
98
  orientation='h',
99
  marker=dict(color='#ef5350'),
100
  text=[f"{int(p)}%" for p in service_stats_sorted['درصد_اخبار_کم_بازدید']],
101
  textposition='inside',
102
+ hovertemplate='<b>%{y}</b><br>زیر 200: %{x}%<extra></extra>'
103
  ))
 
 
104
  fig.add_trace(go.Bar(
105
  y=service_stats_sorted['سرویس'],
106
  x=service_stats_sorted['درصد_اخبار_متوسط'],
 
111
  textposition='inside',
112
  hovertemplate='<b>%{y}</b><br>200-1000: %{x}%<extra></extra>'
113
  ))
 
 
114
  fig.add_trace(go.Bar(
115
  y=service_stats_sorted['سرویس'],
116
  x=service_stats_sorted['درصد_اخبار_پربازدید'],
 
121
  textposition='inside',
122
  hovertemplate='<b>%{y}</b><br>1000 و بالاتر: %{x}%<extra></extra>'
123
  ))
124
+
125
  fig.update_layout(
126
  title={
127
  'text': 'نمودار توزیع درصد بازدید اخبار به تفکیک سرویس‌ها',
128
  'font': {'size': 19, 'family': 'Tahoma', 'color': '#1976d2'},
129
+ 'x': 0.5, 'xanchor': 'center'
 
130
  },
131
  barmode='stack',
132
  xaxis_title='درصد',
133
  yaxis_title='سرویس',
134
  font=dict(family='Tahoma', size=14),
135
  height=max(500, len(service_stats_sorted) * 50),
136
+ legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="center", x=0.5, font=dict(size=15)),
 
 
 
 
 
 
 
137
  plot_bgcolor='rgba(240,240,240,0.5)',
138
  hovermode='closest',
139
  margin=dict(l=150, r=50, t=100, b=80),
140
  xaxis=dict(range=[0, 100])
141
  )
 
142
  fig.update_xaxes(gridcolor='rgba(200,200,200,0.3)')
143
  fig.update_yaxes(gridcolor='rgba(200,200,200,0.3)')
 
144
  return fig
145
 
146
+
147
+ # ─────────────────────────────────────────────
148
+ # PDF
149
+ # ─────────────────────────────────────────────
150
+
151
  def html_to_pdf(html_string, pdf_filename):
 
152
  with open(pdf_filename, "wb") as pdf_file:
153
  pisa.CreatePDF(html_string, dest=pdf_file)
154
 
155
+
156
+ # ─────────────────────────────────────────────
157
+ # پردازش اصلی
158
+ # ─────────────────────────────────────────────
159
+
160
  def process_news_data(file):
 
 
161
  try:
 
162
  excel_file = pd.ExcelFile(file)
163
  sheet_names = excel_file.sheet_names
164
+ sheet_name = 'کلی' if 'کلی' in sheet_names else sheet_names[0]
165
+
 
 
 
 
 
 
166
  df_test = pd.read_excel(file, sheet_name=sheet_name, header=None, nrows=5)
167
  header_row = 0
168
  for i, row in df_test.iterrows():
169
  if 'تیتر' in str(row.values) or 'ناشر' in str(row.values) or 'بازدید' in str(row.values):
170
  header_row = i
171
  break
172
+
 
173
  df = pd.read_excel(file, sheet_name=sheet_name, header=header_row)
174
+
 
175
  required_columns = ['بازد��د', 'تیتر', 'سرویس']
176
  missing_columns = [col for col in required_columns if col not in df.columns]
 
177
  if missing_columns:
178
+ return None, f"""
179
+ <div style='text-align:right;direction:rtl;font-family:Tahoma;padding:20px;'>
180
  <h3>❌ ستون‌های مورد نیاز یافت نشد</h3>
181
  <p><strong>ستون‌های مفقود:</strong> {', '.join(missing_columns)}</p>
182
  <p><strong>ستون‌های موجود:</strong> {', '.join(list(df.columns))}</p>
183
+ </div>""", None, None
184
+
185
+ # پاکسازی
186
+ df_clean = df.dropna(subset=['بازدید', 'تیتر']).copy()
 
 
187
  df_clean['بازدید'] = pd.to_numeric(df_clean['بازدید'], errors='coerce')
188
  df_clean = df_clean[df_clean['بازدید'] >= 0]
189
+
190
+ # سرویس‌ها
191
  df_clean[['سرویس_اصلی', 'زیرسرویس']] = df_clean['سرویس'].apply(
192
  lambda x: pd.Series(extract_service_name(x))
193
  )
 
 
194
  if 'سایت' in df_clean.columns:
195
  df_clean[['سرویس_نهایی', 'زیرسرویس_نهایی']] = df_clean.apply(
196
  lambda row: pd.Series(categorize_service(row['سرویس_اصلی'], row['زیرسرویس'], row['سایت'])), axis=1
 
198
  else:
199
  df_clean['سرویس_نهایی'] = df_clean['سرویس_اصلی']
200
  df_clean['زیرسرویس_نهایی'] = df_clean['زیرسرویس']
201
+
 
202
  df_clean['دسته_ایسنا'] = df_clean.apply(categorize_for_isna_table, axis=1)
203
+
204
+ publish_date_col = next((c for c in ['تاریخ انتشار', 'تاریخ', 'زمان انتشار'] if c in df_clean.columns), None)
205
+ reporter_col = next((c for c in ['نام خبرنگار', 'خبرنگار', 'نویسنده'] if c in df_clean.columns), None)
206
+ publisher_col = next((c for c in ['ناشر', 'منتشرکننده'] if c in df_clean.columns), None)
207
+
208
+ # ══════════════════════════════════════
209
+ # آمار کلی
210
+ # ══════════════════════════════════════
211
+ total_news_all = len(df_clean)
212
+ high_traffic_count_all = len(df_clean[df_clean['بازدید'] >= 1000])
213
+ # FIX: strictly < 200 (news with exactly 200 views are NOT counted as low-traffic)
214
+ low_traffic_count_all = len(df_clean[df_clean['بازدید'] < 200])
215
+
216
+ # ══════════════════════════════════════
217
+ # جدول کل ایسنا
218
+ # ══════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  isna_categories = ['تهران', 'استان‌ها', 'زبان‌های خارجی', 'ایسنا+', 'بازار']
220
  isna_stats_list = []
 
221
  for category in isna_categories:
222
  df_cat = df_clean[df_clean['دسته_ایسنا'] == category]
 
223
  if len(df_cat) > 0:
224
  count = len(df_cat)
225
+ high = len(df_cat[df_cat['بازدید'] >= 1000])
226
+ low = len(df_cat[df_cat['بازدید'] < 200]) # FIX
227
  share = custom_round((count / total_news_all * 100) if total_news_all > 0 else 0)
 
228
  isna_stats_list.append({
229
  'شاخص‌ها': category,
230
  'تعداد_اخبار_ارسالی': count,
 
232
  'تعداد_اخبار_پربازدید': high,
233
  'تعداد_اخبار_کم_بازدید': low
234
  })
 
 
235
  isna_stats_list.append({
236
  'شاخص‌ها': 'جمع کل',
237
  'تعداد_اخبار_ارسالی': total_news_all,
 
239
  'تعداد_اخبار_پربازدید': high_traffic_count_all,
240
  'تعداد_اخبار_کم_بازدید': low_traffic_count_all
241
  })
 
242
  isna_table = pd.DataFrame(isna_stats_list)
243
+
244
+ # ══════════════════════════════════════
245
+ # آمار تفصیلی سرویس‌ها
246
+ # ══════════════════════════════════════
247
  df_services = df_clean[
248
+ ~df_clean['سرویس_نهایی'].str.contains('ایسنا[+]|بازار|زبان', case=False, na=False)
249
  ]
250
+ service_stats = df_services.groupby('سرویس_نهایی').agg(
251
+ تعداد_اخبار_ارسالی=('بازدید','count'),
252
+ مجموع_بازدید=('بازدید','sum'),
253
+ میانگین_بازدید=('بازدید','mean')
254
+ )
 
 
 
 
 
 
255
  service_stats['میانگین_بازدید'] = service_stats['میانگین_بازدید'].round(0).astype(int)
256
+
257
  high_by_service = df_services[df_services['بازدید'] >= 1000].groupby('سرویس_نهایی').size()
258
+ service_stats['تعداد_اخبار_پربازدید'] = high_by_service.reindex(service_stats.index, fill_value=0).astype(int)
259
+ service_stats['درصد_اخبار_پربازدید'] = (
 
 
260
  service_stats['تعداد_اخبار_پربازدید'] / service_stats['تعداد_اخبار_ارسالی'] * 100
261
  ).apply(custom_round)
262
+
263
+ low_by_service = df_services[df_services['بازدید'] < 200].groupby('سرویس_نهایی').size() # FIX
264
+ service_stats['تعداد_اخبار_کم_بازدید'] = low_by_service.reindex(service_stats.index, fill_value=0).astype(int)
265
+ service_stats['درصد_اخبار_کم_بازدید'] = (
 
 
266
  service_stats['تعداد_اخبار_کم_بازدید'] / service_stats['تعداد_اخبار_ارسالی'] * 100
267
  ).apply(custom_round)
268
+
269
+ service_stats = service_stats.sort_values('تعداد_اخبار_ارسالی', ascending=False).reset_index()
 
270
  service_stats = service_stats.rename(columns={'سرویس_نهایی': 'سرویس'})
271
+
272
+ # ══════════════════════════════════════
273
+ # نمودار (همه سرویس‌ها)
274
+ # ══════════════════════════════════════
275
+ all_service_stats = df_clean.groupby('سرویس_نهایی').agg(تعداد_اخبار_ارسالی=('بازدید','count'))
276
+ high_all = df_clean[df_clean['بازدید'] >= 1000].groupby('سرویس_نهایی').size()
277
+ all_service_stats['تعداد_اخبار_پربازدید'] = high_all.reindex(all_service_stats.index, fill_value=0).astype(int)
278
+ all_service_stats['درصد_اخبار_پربازدید'] = (
 
 
 
 
279
  all_service_stats['تعداد_اخبار_پربازدید'] / all_service_stats['تعداد_اخبار_ارسالی'] * 100
280
  ).apply(custom_round)
281
+ low_all = df_clean[df_clean['بازدید'] < 200].groupby('سرویس_نهایی').size() # FIX
282
+ all_service_stats['تعداد_اخبار_کم_بازدید'] = low_all.reindex(all_service_stats.index, fill_value=0).astype(int)
283
+ all_service_stats['درصد_اخبار_کم_بازدید'] = (
 
 
 
284
  all_service_stats['تعداد_اخبار_کم_بازدید'] / all_service_stats['تعداد_اخبار_ارسالی'] * 100
285
  ).apply(custom_round)
286
+ all_service_stats = all_service_stats.reset_index().rename(columns={'سرویس_نهایی': 'سرویس'})
 
 
 
287
  chart = create_traffic_chart(all_service_stats)
288
+
289
+ # ══════════════════════════════════════
290
+ # 100 خبر پربازدید
291
+ # ══════════════════════════════════════
292
  top_100_cols = ['تیتر', 'زیرسرویس_نهایی', 'بازدید']
293
+ if publish_date_col: top_100_cols.insert(2, publish_date_col)
294
+ if reporter_col: top_100_cols.append(reporter_col)
295
+ if publisher_col: top_100_cols.append(publisher_col)
296
+
 
 
 
297
  top_100_news = df_clean.nlargest(100, 'بازدید')[top_100_cols].copy()
 
298
  if publish_date_col:
299
  top_100_news['تاریخ_انتشار'] = top_100_news[publish_date_col].apply(extract_date_only)
300
  top_100_news = top_100_news.drop(columns=[publish_date_col])
301
+
302
+ rename_map = {'زیرسرویس_نهایی': 'زیرسرویس'}
303
+ if reporter_col: rename_map[reporter_col] = 'نام خبرنگار'
304
+ if publisher_col: rename_map[publisher_col] = 'ناشر'
305
+ top_100_news = top_100_news.rename(columns=rename_map)
306
+
307
+ # ══════════════════════════════════════
308
+ # میانگین بازدید
309
+ # ══════════════════════════════════════
310
  df_avg = df_clean[
311
+ ~df_clean['سرویس_نهایی'].str.contains('ایسنا[+]|بازار|زبان', case=False, na=False)
312
  ]
313
+ avg_stats = df_avg.groupby('سرویس_نهایی').agg(
314
+ تعداد_خبر=('بازدید','count'),
315
+ مجموع_بازدید=('بازدید','sum'),
316
+ میانگین_بازدید=('بازدید','mean')
317
+ )
318
  avg_stats['میانگین_بازدید'] = avg_stats['میانگین_بازدید'].round(0).astype(int)
319
+ avg_stats = avg_stats.sort_values('تعداد_خبر', ascending=False).reset_index()
 
320
  avg_stats = avg_stats.rename(columns={'سرویس_نهایی': 'عنوان_اداره'})
321
+
322
+ # ══════════════════════════════════════
323
+ # جدول Word-style: نام اداره | زیرسرویس | ...
324
+ # (دقیقاً مطابق فرمت فایل ورد ارسالی)
325
+ # ══════════════════════════════════════
326
+ subservice_rows = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327
  for service in df_clean['سرویس_نهایی'].unique():
328
  df_service = df_clean[df_clean['سرویس_نهایی'] == service]
 
329
  for subservice in df_service['زیرسرویس_نهایی'].unique():
330
  df_sub = df_service[df_service['زیرسرویس_نهایی'] == subservice]
331
+ count = len(df_sub)
332
+ high = len(df_sub[df_sub['بازدید'] >= 1000])
333
+ low = len(df_sub[df_sub['بازدید'] < 200]) # FIX
334
+ high_pct = custom_round((high / count * 100) if count > 0 else 0)
335
+ low_pct = custom_round((low / count * 100) if count > 0 else 0)
336
+ subservice_rows.append({
337
+ 'نام_اداره': service,
338
+ 'زیرسرویس': subservice,
 
 
 
339
  'تعداد_اخبار_ارسالی': count,
340
+ 'اخبار_بالای_هزار': high,
341
+ 'سهم_پربازدید': high_pct,
342
+ 'اخبار_زیر_200': low,
343
+ 'سهم_کم_بازدید': low_pct
344
  })
345
+
346
+ word_style_table = pd.DataFrame(subservice_rows).sort_values(
347
+ ['نام_اداره', 'تعداد_اخبار_ارسالی'], ascending=[True, False]
348
+ ).reset_index(drop=True)
349
+
350
+ # ══════════════════════════════════════
351
+ # پربازدیدترین خبر هر اداره
352
+ # ══════════════════════════════════════
353
+ top_news_per_service = []
354
+ for service in df_clean['سرویس_نهایی'].unique():
355
+ df_service = df_clean[df_clean['سرویس_نهایی'] == service]
356
+ if len(df_service) == 0:
357
+ continue
358
+ top_row = df_service.nlargest(1, 'بازدید').iloc[0]
359
+ entry = {
360
+ 'نام_اداره': service,
361
+ 'تیتر_خبر': top_row['تیتر'],
362
+ 'زیرسرویس': top_row['زیرسرویس_نهایی'],
363
+ 'بازدید': int(top_row['بازدید'])
364
+ }
365
+ if publish_date_col and publish_date_col in top_row.index:
366
+ entry['تاریخ_انتشار'] = extract_date_only(top_row[publish_date_col])
367
+ if reporter_col and reporter_col in top_row.index:
368
+ entry['نام_خبرنگار'] = top_row[reporter_col]
369
+ top_news_per_service.append(entry)
370
+
371
+ top_news_df = pd.DataFrame(top_news_per_service).sort_values('بازدید', ascending=False).reset_index(drop=True)
372
+
373
+ # ══════════════════════════════════════
374
+ # ذخیره اکسل
375
+ # ══════════════════════════════════════
376
  output_filename = 'نتایج_تحلیل_ماهانه.xlsx'
377
  with pd.ExcelWriter(output_filename, engine='openpyxl') as writer:
378
+ isna_table.to_excel(writer, sheet_name='کل_ایسنا', index=False)
379
+ service_stats.to_excel(writer, sheet_name='آمار_تفصیلی_سرویس_ها', index=False)
380
+ all_service_stats.to_excel(writer,sheet_name='آمار_همه_سرویس_ها', index=False)
381
+ top_100_news.to_excel(writer, sheet_name='100_خبر_پربازدید', index=False)
382
+ avg_stats.to_excel(writer, sheet_name='میانگین_بازدید', index=False)
383
+ word_style_table.to_excel(writer, sheet_name='جدول_ورد_زیرسرویس_ها', index=False)
384
+ top_news_df.to_excel(writer, sheet_name='پربازدیدترین_هر_اداره', index=False)
385
+ # آمار کامنت - غیرفعال شده
386
+ # if comment_stats is not None:
387
+ # comment_stats.to_excel(writer, sheet_name='آمار_کامنت', index=False)
388
+
389
+ # ══════════════════════════════════════
390
+ # HTML گزارش
391
+ # ══════════════════════════════════════
392
+ summary_html = """
393
+ <div style='direction:rtl;font-family:Tahoma,Arial;text-align:right;padding:20px;background-color:white;'>
394
+ <h2 style='text-align:center;color:#1976d2;border-bottom:3px solid #1976d2;padding-bottom:10px;'>
395
  گزارش ماهانه عملکرد ایسنا
396
  </h2>
397
+ """
398
+
399
+ # ── جدول کل ایسنا ──────────────────────────────────────────────
400
+ summary_html += """
401
+ <h3 style='color:#388e3c;margin-top:30px;'>📈 آمار کلی</h3>
402
+ <h4 style='color:#0d47a1;margin-top:20px;background-color:#e3f2fd;padding:15px;border-radius:8px;'>
403
  📊 جدول تعداد کل اخبار ارسالی و وضعیت بازدید کل ایسنا
404
  </h4>
405
+ <div style='overflow-x:auto;margin:20px 0;'>
406
+ <table style='width:100%;border-collapse:collapse;box-shadow:0 2px 8px rgba(0,0,0,.15);font-size:15px;background:#fff;'>
407
+ <thead>
408
+ <tr style='background:#1976d2;'>
409
+ <th style='padding:15px 20px;border:2px solid #1565c0;text-align:right;color:#fff;'>شاخص‌ها</th>
410
+ <th style='padding:15px 20px;border:2px solid #1565c0;text-align:right;color:#fff;'>تعداد اخبار ارسالی</th>
411
+ <th style='padding:15px 20px;border:2px solid #1565c0;text-align:right;color:#fff;'>سهم از کل</th>
412
+ <th style='padding:15px 20px;border:2px solid #1565c0;text-align:right;color:#fff;'>تعداد اخبار پربازدید</th>
413
+ <th style='padding:15px 20px;border:2px solid #1565c0;text-align:right;color:#fff;'>تعداد اخبار کم‌بازدید (زیر 200)</th>
414
+ </tr>
415
+ </thead><tbody>
416
  """
417
+ for _, row in isna_table.iterrows():
418
+ is_total = row['شاخص‌ها'] == 'جمع کل'
419
+ bg = '#1976d2' if is_total else '#e3f2fd'
420
+ tc = '#fff' if is_total else '#000'
421
+ fw = 'bold' if is_total else 'normal'
422
+ bc = '#1565c0' if is_total else '#90caf9'
423
+ summary_html += f"""
424
+ <tr style='background:{bg};'>
425
+ <td style='padding:12px 20px;border:2px solid {bc};text-align:right;font-weight:{fw};color:{tc};'>{row['شاخص‌ها']}</td>
426
+ <td style='padding:12px 20px;border:2px solid {bc};text-align:right;font-weight:{fw};color:{tc};'>{int(row['تعداد_اخبار_ارسالی']):,}</td>
427
+ <td style='padding:12px 20px;border:2px solid {bc};text-align:right;font-weight:{fw};color:{tc};'>{int(row['سهم_از_کل'])}%</td>
428
+ <td style='padding:12px 20px;border:2px solid {bc};text-align:right;font-weight:{fw};color:{tc};'>{int(row['تعداد_اخبار_پربازدید']):,}</td>
429
+ <td style='padding:12px 20px;border:2px solid {bc};text-align:right;font-weight:{fw};color:{tc};'>{int(row['تعداد_اخبار_کم_بازدید']):,}</td>
430
+ </tr>"""
431
+ summary_html += "</tbody></table></div>"
432
+
433
+ # ── آمار تفصیلی سرویس‌ها ──────────────────────────────────────
434
+ tot_cnt = service_stats['تعداد_اخبار_ارسالی'].sum()
435
+ tot_high = service_stats['تعداد_اخبار_پربازدید'].sum()
436
+ tot_low = service_stats['تعداد_اخبار_کم_بازدید'].sum()
437
+ tot_hp = custom_round((tot_high / tot_cnt * 100) if tot_cnt > 0 else 0)
438
+ tot_lp = custom_round((tot_low / tot_cnt * 100) if tot_cnt > 0 else 0)
439
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
  summary_html += """
441
+ <h3 style='color:#7b1fa2;margin-top:30px;'>📋 آمار تفصیلی سرویس‌ها</h3>
442
+ <p style='color:#666;font-size:13px;'>(بدون احتساب ایسنا+، بازار و زبان‌های خارجی)</p>
443
+ <div style='overflow-x:auto;margin:20px 0;'>
444
+ <table style='width:100%;border-collapse:collapse;box-shadow:0 2px 4px rgba(0,0,0,.1);font-size:14px;background:#fff;'>
445
+ <thead>
446
+ <tr style='background:#1976d2;'>
447
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>سرویس</th>
448
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>تعداد اخبار</th>
449
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>اخبار پربازدید</th>
450
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>درصد پربازدید</th>
451
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>اخبار زیر 200</th>
452
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>درصد کم‌بازدید</th>
453
+ </tr>
454
+ </thead><tbody>
455
  """
456
+ for _, row in service_stats.iterrows():
457
+ summary_html += f"""
458
+ <tr style='background:#e3f2fd;'>
459
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;font-weight:bold;color:#000;'>{row['سرویس']}</td>
460
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;color:#000;'>{int(row['تعداد_اخبار_ارسالی']):,}</td>
461
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;background:#c8e6c9;color:#000;'>{int(row['تعداد_اخبار_پربازدید']):,}</td>
462
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;background:#c8e6c9;color:#000;'>{int(row['درصد_اخبار_پربازدید'])}%</td>
463
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;background:#ffcdd2;color:#000;'>{int(row['تعداد_اخبار_کم_بازدید']):,}</td>
464
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;background:#ffcdd2;color:#000;'>{int(row['درصد_اخبار_کم_بازدید'])}%</td>
465
+ </tr>"""
466
+ summary_html += f"""
467
+ <tr style='background:#1976d2;'>
468
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>جمع کل</td>
469
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_cnt):,}</td>
470
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_high):,}</td>
471
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_hp)}%</td>
472
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_low):,}</td>
473
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_lp)}%</td>
474
+ </tr>
475
+ </tbody></table></div>"""
476
+
477
+ # ── جدول Word-style: نام اداره | زیرسرویس ─────────────────────
478
+ tot_ws_news = word_style_table['تعداد_اخبار_ارسالی'].sum()
479
+ tot_ws_high = word_style_table['اخبار_بالای_هزار'].sum()
480
+ tot_ws_low = word_style_table['اخبار_زیر_200'].sum()
481
+ tot_ws_hp = custom_round((tot_ws_high / tot_ws_news * 100) if tot_ws_news > 0 else 0)
482
+ tot_ws_lp = custom_round((tot_ws_low / tot_ws_news * 100) if tot_ws_news > 0 else 0)
483
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
484
  summary_html += """
485
+ <h3 style='color:#d32f2f;margin-top:30px;'>⭐ تعداد اخبار ارسالی زیرسرویس‌ها، پربازدید و کم‌بازدید</h3>
486
+ <p style='color:#666;font-size:13px;'>(بالای 1000 بازدید و زیر 200 بازدید)</p>
487
+ <div style='overflow-x:auto;margin:20px 0;'>
488
+ <table style='width:100%;border-collapse:collapse;box-shadow:0 2px 4px rgba(0,0,0,.1);font-size:14px;background:#fff;'>
489
+ <thead>
490
+ <tr style='background:#1976d2;'>
491
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;min-width:110px;'>نام اداره</th>
492
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;min-width:140px;'>زیر سرویس</th>
493
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>تعداد اخبار ارسالی</th>
494
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>اخبار بالای 1000 بازدید</th>
495
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>سهم پربازدید به کل اخبار (درصد)</th>
496
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>اخبار زیر 200 بازدید</th>
497
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>سهم کم‌بازدید به کل اخبار (درصد)</th>
498
+ </tr>
499
+ </thead><tbody>
500
  """
501
+ # مرتب‌سازی سرویس‌ها بر اساس مجموع تعداد اخبار (بزرگ‌تر اول)
502
+ service_order = (
503
+ word_style_table.groupby('نام_اداره')['تعداد_اخبار_ارسالی']
504
+ .sum().sort_values(ascending=False).index
505
+ )
 
 
 
506
  current_service = None
507
+ for service_name in service_order:
508
+ group = word_style_table[word_style_table['نام_اداره'] == service_name]
509
+ row_count = len(group)
510
+ first_row = True
511
+
512
+ for _, row in group.iterrows():
513
+ if first_row:
514
+ if current_service is not None:
515
+ summary_html += """
516
+ <tr style='background:#37474f;height:3px;'>
517
+ <td colspan='7' style='padding:0;border:none;'></td>
518
+ </tr>"""
519
+ current_service = service_name
520
+ service_cell = f"""
521
+ <td rowspan='{row_count}' style='padding:10px 15px;border:2px solid #1565c0;
522
+ text-align:right;font-weight:bold;color:#fff;background:#1565c0;
523
+ vertical-align:middle;'>{service_name}</td>"""
524
+ first_row = False
525
+ else:
526
+ service_cell = ""
527
+
528
+ summary_html += f"""
529
+ <tr style='background:#e3f2fd;'>
530
+ {service_cell}
531
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;color:#000;'>{row['زیرسرویس']}</td>
532
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;color:#000;'>{int(row['تعداد_اخبار_ارسالی']):,}</td>
533
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;background:#c8e6c9;color:#000;'>{int(row['اخبار_بالای_هزار']):,}</td>
534
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;background:#c8e6c9;color:#000;'>{int(row['سهم_پربازدید'])}%</td>
535
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;background:#ffcdd2;color:#000;'>{int(row['اخبار_زیر_200']):,}</td>
536
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;background:#ffcdd2;color:#000;'>{int(row['سهم_کم_بازدید'])}%</td>
537
+ </tr>"""
538
+
539
  summary_html += f"""
540
+ <tr style='background:#1976d2;'>
541
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>جمع کل</td>
542
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>—</td>
543
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_ws_news):,}</td>
544
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_ws_high):,}</td>
545
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_ws_hp)}%</td>
546
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_ws_low):,}</td>
547
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_ws_lp)}%</td>
548
+ </tr>
549
+ </tbody></table></div>"""
550
+
551
+ # ── 100 خبر پربازدید ──────────────────────────────────────────
 
 
552
  summary_html += """
553
+ <h3 style='color:#ff6f00;margin-top:30px;'>🏆 100 خبر پربازدید ایسنا</h3>
554
+ <div style='overflow-x:auto;margin:20px 0;'>
555
+ <table style='width:100%;border-collapse:collapse;box-shadow:0 2px 4px rgba(0,0,0,.1);font-size:14px;background:#fff;'>
556
+ <thead>
557
+ <tr style='background:#1976d2;'>
558
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>تیتر خبر</th>
559
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>زیرسرویس</th>
560
  """
 
561
  if publish_date_col:
562
+ summary_html += "<th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>تاریخ انتشار</th>"
563
+ summary_html += "<th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>بازدید</th>"
 
 
564
  if reporter_col:
565
+ summary_html += "<th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>نام خبرنگار</th>"
 
566
  if publisher_col:
567
+ summary_html += "<th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>ناشر</th>"
568
+ summary_html += "</tr></thead><tbody>"
569
+
570
+ for _, row in top_100_news.iterrows():
 
 
 
 
 
571
  summary_html += f"""
572
+ <tr style='background:#e3f2fd;'>
573
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;color:#000;'>{row['تیتر']}</td>
574
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;color:#000;'>{row['زیرسرویس']}</td>"""
575
+ if 'تاریخ_انتشار' in row.index:
576
+ summary_html += f"<td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;color:#000;'>{row['تاریخ_انتشار']}</td>"
577
+ summary_html += f"<td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;font-weight:bold;color:#d32f2f;'>{int(row['بازدید']):,}</td>"
578
+ if reporter_col:
579
+ val = row.get('نام خبرنگار', '-')
580
+ summary_html += f"<td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;color:#000;'>{val if pd.notna(val) else '-'}</td>"
581
+ if publisher_col:
582
+ val = row.get('ناشر', '-')
583
+ summary_html += f"<td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;color:#000;'>{val if pd.notna(val) else '-'}</td>"
 
 
 
 
 
 
 
 
584
  summary_html += "</tr>"
585
+ summary_html += "</tbody></table></div>"
586
+
587
+ # ── پربازدیدترین خبر هر اداره ────────────────────────────────
588
  summary_html += """
589
+ <h3 style='color:#6a1b9a;margin-top:30px;'>🌟 پربازدیدترین خبر هر اداره</h3>
590
+ <div style='overflow-x:auto;margin:20px 0;'>
591
+ <table style='width:100%;border-collapse:collapse;box-shadow:0 2px 4px rgba(0,0,0,.1);font-size:14px;background:#fff;'>
592
+ <thead>
593
+ <tr style='background:#1976d2;'>
594
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>نام اداره</th>
595
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>تیتر خبر</th>
596
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>زیرسرویس</th>
597
  """
598
+ if 'تاریخ_انتشار' in top_news_df.columns:
599
+ summary_html += "<th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>تاریخ انتشار</th>"
600
+ if 'نام_خبرنگار' in top_news_df.columns:
601
+ summary_html += "<th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>نام خبرنگار</th>"
602
+ summary_html += "<th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>بازدید</th>"
603
+ summary_html += "</tr></thead><tbody>"
604
+
605
+ for _, row in top_news_df.iterrows():
606
+ summary_html += f"""
607
+ <tr style='background:#f3e5f5;'>
608
+ <td style='padding:10px 15px;border:1px solid #ce93d8;text-align:right;font-weight:bold;color:#4a148c;'>{row['نام_اداره']}</td>
609
+ <td style='padding:10px 15px;border:1px solid #ce93d8;text-align:right;color:#000;'>{row['تیتر_خبر']}</td>
610
+ <td style='padding:10px 15px;border:1px solid #ce93d8;text-align:right;color:#000;'>{row['زیرسرویس']}</td>"""
611
+ if 'تاریخ_انتشار' in row.index:
612
+ summary_html += f"<td style='padding:10px 15px;border:1px solid #ce93d8;text-align:right;color:#000;'>{row.get('تاریخ_انتشار', '-')}</td>"
613
+ if 'نام_خبرنگار' in row.index:
614
+ summary_html += f"<td style='padding:10px 15px;border:1px solid #ce93d8;text-align:right;color:#000;'>{row.get('نام_خبرنگار', '-')}</td>"
615
+ summary_html += f"<td style='padding:10px 15px;border:1px solid #ce93d8;text-align:right;font-weight:bold;color:#d32f2f;'>{int(row['بازدید']):,}</td>"
616
+ summary_html += "</tr>"
617
+ summary_html += "</tbody></table></div>"
618
+
619
+ # ── میانگین بازدید ────────────────────────────────────────────
620
+ tot_avg_news = avg_stats['تعداد_خبر'].sum()
621
+ tot_avg_vis = avg_stats['مجموع_بازدید'].sum()
622
+ tot_avg_avg = custom_round(tot_avg_vis / tot_avg_news) if tot_avg_news > 0 else 0
623
+
624
  summary_html += """
625
+ <h3 style='color:#00695c;margin-top:30px;'>📊 میانگین بازدید</h3>
626
+ <div style='overflow-x:auto;margin:20px 0;'>
627
+ <table style='width:100%;border-collapse:collapse;box-shadow:0 2px 4px rgba(0,0,0,.1);font-size:14px;background:#fff;'>
628
+ <thead>
629
+ <tr style='background:#1976d2;'>
630
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>عنوان اداره</th>
631
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>تعداد خبر</th>
632
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>مجموع بازدید</th>
633
+ <th style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;'>میانگین بازدید</th>
634
+ </tr>
635
+ </thead><tbody>
 
636
  """
637
+ for _, row in avg_stats.iterrows():
 
 
 
 
 
638
  summary_html += f"""
639
+ <tr style='background:#e3f2fd;'>
640
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;font-weight:bold;color:#000;'>{row['عنوان_اداره']}</td>
641
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;color:#000;'>{int(row['تعداد_خبر']):,}</td>
642
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;color:#000;'>{int(row['مجموع_بازدید']):,}</td>
643
+ <td style='padding:10px 15px;border:1px solid #90caf9;text-align:right;font-weight:bold;color:#1976d2;'>{int(row['میانگین_بازدید']):,}</td>
644
+ </tr>"""
 
 
 
645
  summary_html += f"""
646
+ <tr style='background:#1976d2;'>
647
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>جمع کل</td>
648
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_avg_news):,}</td>
649
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_avg_vis):,}</td>
650
+ <td style='padding:12px 15px;border:2px solid #1565c0;text-align:right;color:#fff;font-weight:bold;'>{int(tot_avg_avg):,}</td>
651
+ </tr>
652
+ </tbody></table></div>"""
653
+
654
+ # آمار کامنت - کاملاً غیرفعال شده طبق درخواست
655
+ # ─────────────────────────────────────────
656
+ # comment_col_names = { ... }
657
+ # comment_stats_list = []
658
+ # for service in df_clean['سرویس_نهایی'].unique():
659
+ # ... (کد کامنت اینجا بود)
660
+ # if comment_stats is not None and len(comment_stats) > 0:
661
+ # summary_html += "..." # جدول کامنت‌ها
662
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
663
  summary_html += """
664
+ <div style='text-align:center;margin-top:40px;padding:20px;background:#e8f5e9;border-radius:8px;'>
665
+ <h3 style='color:#2e7d32;'>✅ فایل اکسل با جزئیات کامل آماده دانلود است</h3>
666
+ <p style='color:#555;'>شامل: جدول کل ایسنا | آمار تفصیلی سرویس‌ها | 100 خبر پربازدید |
667
+ میانگین بازدید | جدول ورد زیرسرویس‌ها | پربازدیدترین خبر هر اداره</p>
668
  </div>
669
+ </div>"""
670
+
671
+ # PDF
 
672
  pdf_filename = 'گزارش_ماهانه_ایسنا.pdf'
673
  try:
674
  html_to_pdf(summary_html, pdf_filename)
675
  except Exception as e:
676
  print(f"خطا در تولید PDF: {str(e)}")
677
  pdf_filename = None
678
+
679
  return output_filename, summary_html, chart, pdf_filename
680
+
681
  except Exception as e:
682
+ import traceback
683
  error_html = f"""
684
+ <div style='direction:rtl;text-align:right;font-family:Tahoma;padding:20px;'>
685
+ <h3 style='color:#d32f2f;'>❌ خطا در پردازش فایل</h3>
686
+ <p style='background:#ffebee;padding:15px;border-right:4px solid #d32f2f;'>{str(e)}</p>
687
+ <pre style='font-size:11px;color:#666;'>{traceback.format_exc()}</pre>
688
+ </div>"""
 
689
  return None, error_html, None, None
690
 
691
+
692
+ # ─────────────────────────────────────────────
693
  # رابط کاربری Gradio
694
+ # ─────────────────────────────────────────────
695
+
696
  custom_css = """
697
  .gradio-container {
698
  direction: rtl;
699
+ background-image: url('https://img.freepik.com/free-vector/gradient-brain-background_23-2150516335.jpg');
700
  background-size: cover;
701
  background-position: center;
702
  background-repeat: no-repeat;
703
  background-attachment: fixed;
704
  }
705
  .contain {
706
+ background-color: rgba(255,255,255,0.95);
707
  border-radius: 15px;
708
  padding: 30px;
709
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
710
  }
711
  #header-box {
712
+ background-color: rgba(255,255,255,0.98);
713
  border-radius: 10px;
714
  padding: 25px;
715
  margin-bottom: 20px;
 
718
  """
719
 
720
  with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
721
+ gr.HTML("""
722
+ <div id="header-box" style='text-align:center;direction:rtl;font-family:Tahoma;'>
723
+ <h1 style='color:#1976d2;margin-bottom:15px;font-size:28px;'>دستیار هوشمند اتاق خبر - گزارشگیری ماهانه</h1>
724
+ <p style='font-size:16px;color:#555;line-height:1.8;'>برای شروع گزارشگیری روی باکس زیر کلیک کرده و فایل لیست تولید و آمار بازدید را وارد نمایید</p>
725
+ <hr style='border:1px solid #1976d2;width:50%;margin:20px auto;'>
 
726
  </div>
727
+ """)
728
+
 
729
  with gr.Row():
730
  with gr.Column():
731
  input_file = gr.File(
 
733
  file_types=[".xlsx", ".xls"],
734
  type="binary"
735
  )
736
+ submit_btn = gr.Button("🚀 شروع تحلیل آماری", variant="primary", size="lg")
737
+
 
 
 
 
 
738
  with gr.Row():
739
  with gr.Column():
740
+ output_html = gr.HTML(label="📊 نتایج تحلیل")
741
  output_chart = gr.Plot(label="📊 نمودار توزیع درصد بازدید اخبار به تفکیک سرویس‌ها")
742
+ output_file = gr.File(label="💾 دانلود فایل اکسل نتایج کامل")
743
+ output_pdf = gr.File(label="📄 دانلود گزارش PDF")
744
+
745
  submit_btn.click(
746
  fn=process_news_data,
747
  inputs=input_file,
748
  outputs=[output_file, output_html, output_chart, output_pdf]
749
  )
750
+
751
+ gr.Markdown("""
752
+ <div style='text-align:center;direction:rtl;margin-top:40px;padding:20px;color:#777;
753
+ border-top:2px solid #e0e0e0;background:rgba(255,255,255,0.95);border-radius:10px;'>
754
+ <p style='font-size:14px;'>💡 <strong>راهنما:</strong> فایل باید شامل ستون‌های «تیتر»، «بازدید» و «سرویس» باشد</p>
755
+ <p style='font-size:12px;margin-top:10px;'>سامانه هوشمند ایسنا - نسخه ماهانه 2.0 | طراحی شده با ❤️</p>
756
  </div>
757
+ """)
 
758
 
759
  if __name__ == "__main__":
760
  demo.launch()