aysan98 commited on
Commit
050e400
·
verified ·
1 Parent(s): 4ef8be6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +572 -53
app.py CHANGED
@@ -26,6 +26,21 @@ DEPARTMENTS = [
26
  "بازار",
27
  ]
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  NEWS_TYPES = [
30
  "یادداشت",
31
  "فیلم",
@@ -37,6 +52,22 @@ NEWS_TYPES = [
37
  "ترجمه",
38
  ]
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  TYPE_ALIASES = {
41
  "یادداشت": ["یادداشت", "مقاله"],
42
  "فیلم": ["فیلم", "ویدئو", "ویدیو", "تصویری"],
@@ -57,6 +88,7 @@ DEPARTMENT_ALIASES = {
57
  "ورزشی": ["ورزشی", "ورزش"],
58
  "جهان": ["جهان", "بین الملل", "بین‌الملل", "خارجی"],
59
  "استانها": ["استانها", "استان‌ها", "استان", "استان ها"],
 
60
  "ایسنا +": ["ایسنا +", "ایسنا+", "ایسنا پلاس"],
61
  "بازار": ["بازار"],
62
  }
@@ -64,6 +96,7 @@ DEPARTMENT_ALIASES = {
64
  COLUMN_CANDIDATES = {
65
  "department": ["نام اداره", "اداره", "سرویس", "سرویس اصلی", "سرویس_نهایی", "گروه خبری", "گروه", "بخش"],
66
  "news_type": ["نوع خبر", "نوع مطلب", "نوع محتوا", "نوع", "قالب خبر", "قالب", "فرمت", "گونه خبر", "دسته خبر", "دسته‌بندی", "دسته بندی"],
 
67
  "site": ["سایت", "نام سایت", "پایگاه", "زبان"],
68
  "date": ["تاریخ انتشار", "تاریخ", "زمان انتشار", "تاریخ و زمان انتشار", "زمان"],
69
  }
@@ -249,14 +282,18 @@ def build_summary_table(df):
249
  work["news_type"] = work["news_type"].apply(canonical_news_type)
250
  work = work[(work["department"] != "") & (work["news_type"] != "")]
251
 
 
 
 
252
  detected_departments = [
253
- dep for dep in work["department"].dropna().unique().tolist() if dep not in DEPARTMENTS and dep != "نامشخص"
 
254
  ]
255
  departments = DEPARTMENTS + sorted(detected_departments)
256
 
257
  rows = []
258
  for dep in departments:
259
- dep_df = work[work["department"] == dep]
260
  total = int(len(dep_df))
261
 
262
  count_row = {"نام اداره": dep, "فراوانی / درصد": "تعداد", "تعداد خبر": total}
@@ -270,11 +307,11 @@ def build_summary_table(df):
270
 
271
  rows.extend([count_row, percent_row])
272
 
273
- total = int(len(work))
274
  total_count_row = {"نام اداره": "جمع کل", "فراوانی / درصد": "تعداد", "تعداد خبر": total}
275
  total_percent_row = {"نام اداره": "جمع کل", "فراوانی / درصد": "درصد", "تعداد خبر": "100%" if total else "0%"}
276
  for news_type in NEWS_TYPES:
277
- count = int((work["news_type"] == news_type).sum())
278
  percent = custom_round((count / total) * 100) if total else 0
279
  total_count_row[news_type] = count
280
  total_percent_row[news_type] = f"{percent:g}%"
@@ -284,6 +321,168 @@ def build_summary_table(df):
284
  return pd.DataFrame(rows, columns=output_columns)
285
 
286
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  def format_dataframe_for_html(summary_df, title):
288
  css = """
289
  <style>
@@ -359,8 +558,129 @@ def format_dataframe_for_html(summary_df, title):
359
  return html
360
 
361
 
362
- def save_summary_excel(summary_df, title):
363
- wb = Workbook()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
  ws = wb.active
365
  ws.title = "نوع خبر ادارات"
366
  ws.sheet_view.rightToLeft = True
@@ -374,12 +694,14 @@ def save_summary_excel(summary_df, title):
374
  normal_font = Font(name="Tahoma", size=12)
375
  bold_font = Font(name="Tahoma", size=12, bold=True)
376
 
 
377
  ws.merge_cells("A1:K1")
378
  ws["A1"] = title
379
  ws["A1"].font = title_font
380
  ws["A1"].alignment = center
381
  ws.row_dimensions[1].height = 34
382
 
 
383
  ws.merge_cells("A3:C3")
384
  ws["A3"] = "نوع خبر"
385
  ws.merge_cells("D3:H3")
@@ -430,49 +752,215 @@ def save_summary_excel(summary_df, title):
430
  ws.cell(row=row, column=1).font = bold_font
431
  ws.cell(row=row, column=2).font = bold_font
432
 
433
- def set_border(cell, left=None, right=None, top=None, bottom=None):
434
- current = cell.border
435
- cell.border = Border(
436
- left=left or current.left,
437
- right=right or current.right,
438
- top=top or current.top,
439
- bottom=bottom or current.bottom,
440
- )
441
-
442
  for col in range(1, max_col + 1):
443
- set_border(ws.cell(row=3, column=col), top=thick)
444
- set_border(ws.cell(row=4, column=col), bottom=thick)
445
- set_border(ws.cell(row=max_row, column=col), bottom=thick)
446
 
447
  for row in range(3, max_row + 1):
448
- set_border(ws.cell(row=row, column=1), right=thick)
449
- set_border(ws.cell(row=row, column=max_col), left=thick)
450
  for boundary_col in [3, 9]:
451
- set_border(ws.cell(row=row, column=boundary_col), left=thick)
452
 
453
  for row in range(5, max_row + 1, 2):
454
  for col in range(1, max_col + 1):
455
- set_border(ws.cell(row=row, column=col), top=thick)
456
- set_border(ws.cell(row=row + 1, column=col), bottom=thick)
457
-
458
- widths = {
459
- 1: 22,
460
- 2: 16,
461
- 3: 14,
462
- 4: 15,
463
- 5: 14,
464
- 6: 16,
465
- 7: 17,
466
- 8: 17,
467
- 9: 14,
468
- 10: 14,
469
- 11: 14,
470
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471
  for col_idx, width in widths.items():
472
  ws.column_dimensions[get_column_letter(col_idx)].width = width
473
  for row in range(3, max_row + 1):
474
  ws.row_dimensions[row].height = 28
475
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476
  output_dir = tempfile.mkdtemp(prefix="news_type_report_")
477
  output_path = os.path.join(output_dir, "جدول_نوع_خبر_ادارات.xlsx")
478
  wb.save(output_path)
@@ -481,7 +969,7 @@ def save_summary_excel(summary_df, title):
481
 
482
  def process_file(input_file, report_title):
483
  if input_file is None:
484
- return None, "<div style='direction:rtl; color:#c62828; font-family:Tahoma;'>لطفاً فایل اکسل را بارگذاری کنید.</div>"
485
 
486
  try:
487
  file_path = input_file if isinstance(input_file, str) else input_file.name
@@ -489,17 +977,40 @@ def process_file(input_file, report_title):
489
  base_title = normalize_text(report_title) or "نوع خبر ادارات"
490
  date_label = infer_date_label(filter_persian_isna_rows(df))
491
  title = f"{base_title} - {date_label}" if date_label and date_label not in base_title else base_title
 
492
  summary_df = build_summary_table(df)
493
- html = format_dataframe_for_html(summary_df, title)
494
- output_path = save_summary_excel(summary_df, title)
495
- return output_path, html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496
  except Exception as exc:
497
  error_html = f"""
498
  <div style="direction:rtl; text-align:right; font-family:Tahoma; padding:18px;
499
- background:#ffebee; border-right:4px solid #c62828; color:#222;">
500
- <h3 style="margin-top:0; color:#c62828;">خطا در ساخت جدول</h3>
501
  <p>{exc}</p>
502
- <p style="font-size:13px; color:#555;">فایل باید حداقل ستون‌های «نام اداره/سرویس» و «نوع خبر» را داشته باشد.</p>
503
  </div>
504
  """
505
  return None, error_html
@@ -510,18 +1021,22 @@ custom_css = """
510
  direction: rtl;
511
  font-family: Tahoma, Arial, sans-serif;
512
  background: #f5f7fb;
 
513
  }
514
  .contain {
515
  max-width: 1200px;
516
  }
517
  #header-box {
518
  background: white;
519
- border: 1px solid #e5e7eb;
520
  border-radius: 10px;
521
  padding: 22px;
522
  margin-bottom: 16px;
523
  text-align: center;
524
  }
 
 
 
525
  """
526
 
527
 
@@ -529,9 +1044,9 @@ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
529
  gr.HTML(
530
  """
531
  <div id="header-box">
532
- <h1 style="margin:0 0 10px 0; color:#111827;">سازنده جدول نوع خبر ادارات</h1>
533
- <p style="margin:0; color:#4b5563; line-height:1.8;">
534
- فایل اکسل کامل را بارگذاری کنید تا جدول فراوانی و درصد انواع خبر ساخته شود و خروجی اکسل راست‌چین بگیرید.
535
  </p>
536
  </div>
537
  """
@@ -544,20 +1059,24 @@ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
544
  type="filepath",
545
  )
546
  report_title = gr.Textbox(
547
- label="عنوان جدول",
548
  value="نوع خبر ادارات",
549
  )
550
 
551
- run_btn = gr.Button("ساخت جدول", variant="primary", size="lg")
552
 
553
  with gr.Row():
554
- output_file = gr.File(label="دانلود فایل اکسل خروجی")
555
 
556
- output_html = gr.HTML(label="پیش‌نمایش جدول")
557
 
558
  gr.HTML(
559
  """
560
- <div style="direction:rtl; font-family:Tahoma; color:#6b7280; font-size:13px; margin-top:18px; line-height:1.9;">
 
 
 
 
561
  ستون‌های قابل تشخیص برای اداره: «نام اداره»، «اداره»، «سرویس»، «گروه خبری».
562
  ستون‌های قابل تشخیص برای نوع خبر: «نوع خبر»، «قالب»، «فرمت»، «دسته خبر».
563
  اگر ستون «سایت» وجود داشته باشد، فقط ردیف‌هایی که مقدار سایت آن‌ها دقیقاً «ایسنا» است محاسبه می‌شوند.
 
26
  "بازار",
27
  ]
28
 
29
+ # ادارات جدول سهم (شامل چندرسانه‌ای)
30
+ DEPARTMENTS_SHARE = [
31
+ "علمی و دانشگاهی",
32
+ "سیاسی",
33
+ "فرهنگی و هنری",
34
+ "اقتصادی",
35
+ "اجتماعی",
36
+ "ورزشی",
37
+ "جهان",
38
+ "استانها",
39
+ "چندرسانه‌ای",
40
+ "ایسنا +",
41
+ "بازار",
42
+ ]
43
+
44
  NEWS_TYPES = [
45
  "یادداشت",
46
  "فیلم",
 
52
  "ترجمه",
53
  ]
54
 
55
+ # انواع خبر اختصاصی
56
+ EXCLUSIVE_TYPES = ["یادداشت", "فیلم", "اختصاصی خبر", "اختصاصی گفتگو", "اختصاصی گزارش"]
57
+ # انواع خبر غیراختصاصی
58
+ NON_EXCLUSIVE_TYPES = ["پوششی", "دریافتی", "ترجمه"]
59
+
60
+ PRODUCTION_COLUMNS = [
61
+ "عکس اختصاصی",
62
+ "عکس پوششی",
63
+ "عکس دریافتی",
64
+ "فیلم اختصاصی",
65
+ "فیلم پوششی",
66
+ "فیلم دریافتی",
67
+ "گرافیک اختصاصی",
68
+ "صوت اختصاصی",
69
+ ]
70
+
71
  TYPE_ALIASES = {
72
  "یادداشت": ["یادداشت", "مقاله"],
73
  "فیلم": ["فیلم", "ویدئو", "ویدیو", "تصویری"],
 
88
  "ورزشی": ["ورزشی", "ورزش"],
89
  "جهان": ["جهان", "بین الملل", "بین‌الملل", "خارجی"],
90
  "استانها": ["استانها", "استان‌ها", "استان", "استان ها"],
91
+ "چندرسانه‌ای": ["چندرسانه‌ای", "چند رسانه ای", "چندرسانه ای", "چند رسانه‌ای", "multimedia"],
92
  "ایسنا +": ["ایسنا +", "ایسنا+", "ایسنا پلاس"],
93
  "بازار": ["بازار"],
94
  }
 
96
  COLUMN_CANDIDATES = {
97
  "department": ["نام اداره", "اداره", "سرویس", "سرویس اصلی", "سرویس_نهایی", "گروه خبری", "گروه", "بخش"],
98
  "news_type": ["نوع خبر", "نوع مطلب", "نوع محتوا", "نوع", "قالب خبر", "قالب", "فرمت", "گونه خبر", "دسته خبر", "دسته‌بندی", "دسته بندی"],
99
+ "production": ["نوع تولید", "تولید", "تولیدات", "قالب تولید", "نوع رسانه", "رسانه"],
100
  "site": ["سایت", "نام سایت", "پایگاه", "زبان"],
101
  "date": ["تاریخ انتشار", "تاریخ", "زمان انتشار", "تاریخ و زمان انتشار", "زمان"],
102
  }
 
282
  work["news_type"] = work["news_type"].apply(canonical_news_type)
283
  work = work[(work["department"] != "") & (work["news_type"] != "")]
284
 
285
+ # فقط ادارات غیر چندرسانه‌ای در جدول اول
286
+ work_no_media = work[work["department"] != "چندرسانه‌ای"]
287
+
288
  detected_departments = [
289
+ dep for dep in work_no_media["department"].dropna().unique().tolist()
290
+ if dep not in DEPARTMENTS and dep != "نامشخص"
291
  ]
292
  departments = DEPARTMENTS + sorted(detected_departments)
293
 
294
  rows = []
295
  for dep in departments:
296
+ dep_df = work_no_media[work_no_media["department"] == dep]
297
  total = int(len(dep_df))
298
 
299
  count_row = {"نام اداره": dep, "فراوانی / درصد": "تعداد", "تعداد خبر": total}
 
307
 
308
  rows.extend([count_row, percent_row])
309
 
310
+ total = int(len(work_no_media))
311
  total_count_row = {"نام اداره": "جمع کل", "فراوانی / درصد": "تعداد", "تعداد خبر": total}
312
  total_percent_row = {"نام اداره": "جمع کل", "فراوانی / درصد": "درصد", "تعداد خبر": "100%" if total else "0%"}
313
  for news_type in NEWS_TYPES:
314
+ count = int((work_no_media["news_type"] == news_type).sum())
315
  percent = custom_round((count / total) * 100) if total else 0
316
  total_count_row[news_type] = count
317
  total_percent_row[news_type] = f"{percent:g}%"
 
321
  return pd.DataFrame(rows, columns=output_columns)
322
 
323
 
324
+ def build_share_table(df):
325
+ """سهم ادارات در اخبار اختصاصی و غیراختصاصی"""
326
+ df = filter_persian_isna_rows(df)
327
+ department_col = find_column(df, "department")
328
+ news_type_col = find_column(df, "news_type")
329
+
330
+ if department_col is None or news_type_col is None:
331
+ return None
332
+
333
+ work = df[[department_col, news_type_col]].copy()
334
+ work.columns = ["department", "news_type"]
335
+ work["department"] = work["department"].apply(canonical_department)
336
+ work["news_type"] = work["news_type"].apply(canonical_news_type)
337
+ work = work[(work["department"] != "") & (work["news_type"] != "")]
338
+
339
+ total_all = int(len(work))
340
+
341
+ detected_departments = [
342
+ dep for dep in work["department"].dropna().unique().tolist()
343
+ if dep not in DEPARTMENTS_SHARE and dep != "نامشخص"
344
+ ]
345
+ departments = DEPARTMENTS_SHARE + sorted(detected_departments)
346
+
347
+ rows = []
348
+ for dep in departments:
349
+ dep_df = work[work["department"] == dep]
350
+ total = int(len(dep_df))
351
+
352
+ exclusive = int(dep_df["news_type"].isin(EXCLUSIVE_TYPES).sum())
353
+ non_exclusive = int(dep_df["news_type"].isin(NON_EXCLUSIVE_TYPES).sum())
354
+
355
+ excl_pct = custom_round((exclusive / total) * 100) if total else 0
356
+ non_excl_pct = custom_round((non_exclusive / total) * 100) if total else 0
357
+
358
+ count_row = {
359
+ "نام اداره": dep,
360
+ "فراوانی / درصد": "تعداد",
361
+ "جمع کل": total,
362
+ "اخبار اختصاصی": exclusive,
363
+ "اخبار غیراختصاصی": non_exclusive,
364
+ }
365
+ percent_row = {
366
+ "نام اداره": dep,
367
+ "فراوانی / درصد": "درصد",
368
+ "جمع کل": "100%" if total else "0%",
369
+ "اخبار اختصاصی": f"{excl_pct:g}%",
370
+ "اخبار غیراختصاصی": f"{non_excl_pct:g}%",
371
+ }
372
+ rows.extend([count_row, percent_row])
373
+
374
+ # جمع کل
375
+ total_excl = int(work["news_type"].isin(EXCLUSIVE_TYPES).sum())
376
+ total_non_excl = int(work["news_type"].isin(NON_EXCLUSIVE_TYPES).sum())
377
+ excl_pct = custom_round((total_excl / total_all) * 100) if total_all else 0
378
+ non_excl_pct = custom_round((total_non_excl / total_all) * 100) if total_all else 0
379
+
380
+ rows.extend([
381
+ {
382
+ "نام اداره": "جمع کل",
383
+ "فراوانی / درصد": "تعداد",
384
+ "جمع کل": total_all,
385
+ "اخبار اختصاصی": total_excl,
386
+ "اخبار غیراختصاصی": total_non_excl,
387
+ },
388
+ {
389
+ "نام اداره": "جمع کل",
390
+ "فراوانی / درصد": "درصد",
391
+ "جمع کل": "100%" if total_all else "0%",
392
+ "اخبار اختصاصی": f"{excl_pct:g}%",
393
+ "اخبار غیراختصاصی": f"{non_excl_pct:g}%",
394
+ },
395
+ ])
396
+
397
+ output_columns = ["نام اداره", "فراوانی / درصد", "جمع کل", "اخبار اختصاصی", "اخبار غیراختصاصی"]
398
+ return pd.DataFrame(rows, columns=output_columns)
399
+
400
+
401
+ def type_related_columns(df):
402
+ related = []
403
+ candidate_words = COLUMN_CANDIDATES["news_type"] + COLUMN_CANDIDATES["production"]
404
+ for col in df.columns:
405
+ col_norm = normalize_text(col)
406
+ if any(normalize_text(word) in col_norm for word in candidate_words):
407
+ related.append(col)
408
+ return related
409
+
410
+
411
+ def classify_production(text):
412
+ text = normalize_text(text)
413
+ if not text:
414
+ return None
415
+
416
+ media = None
417
+ if any(word in text for word in ["عکس", "تصویر", "فتو"]):
418
+ media = "عکس"
419
+ elif any(word in text for word in ["فیلم", "ویدیو", "ویدئو"]):
420
+ media = "فیلم"
421
+ elif any(word in text for word in ["گرافیک", "اینفوگرافیک", "اینفو"]):
422
+ media = "گرافیک"
423
+ elif any(word in text for word in ["صوت", "صدا", "پادکست", "رادیو"]):
424
+ media = "صوت"
425
+
426
+ if media is None:
427
+ return None
428
+
429
+ subtype = None
430
+ if "اختصاصی" in text:
431
+ subtype = "اختصاصی"
432
+ elif "پوششی" in text or "پوشش" in text:
433
+ subtype = "پوششی"
434
+ elif "دریافتی" in text:
435
+ subtype = "دریافتی"
436
+
437
+ if media in ["گرافیک", "صوت"] and subtype is None:
438
+ subtype = "اختصاصی"
439
+
440
+ if subtype is None:
441
+ return None
442
+
443
+ production_type = f"{media} {subtype}"
444
+ return production_type if production_type in PRODUCTION_COLUMNS else None
445
+
446
+
447
+ def build_production_table(df):
448
+ """جدول تولیدات معاونت چندرسانه‌ای — فقط ردیف‌های اداره چندرسانه‌ای"""
449
+ df = filter_persian_isna_rows(df)
450
+
451
+ department_col = find_column(df, "department")
452
+ if department_col is not None:
453
+ df_media = df[df[department_col].apply(
454
+ lambda v: canonical_department(v) == "چندرسانه‌ای"
455
+ )].copy()
456
+ # اگر ردیف چندرسانه‌ای نبود، روی کل دیتا اعمال کن (backward compat)
457
+ if len(df_media) == 0:
458
+ df_media = df.copy()
459
+ else:
460
+ df_media = df.copy()
461
+
462
+ total = int(len(df_media))
463
+ production_cols = type_related_columns(df_media)
464
+
465
+ counts = {col: 0 for col in PRODUCTION_COLUMNS}
466
+ if production_cols:
467
+ for _, row in df_media.iterrows():
468
+ text = " ".join(normalize_text(row[col]) for col in production_cols)
469
+ production_type = classify_production(text)
470
+ if production_type:
471
+ counts[production_type] += 1
472
+
473
+ count_row = {"نام اداره": "جمع کل", "فراوانی / درصد": "تعداد", "تعداد خبر": total}
474
+ percent_row = {"نام اداره": "جمع کل", "فراوانی / درصد": "درصد", "تعداد خبر": "100%" if total else "0%"}
475
+ for col in PRODUCTION_COLUMNS:
476
+ count_row[col] = counts[col]
477
+ percent = custom_round((counts[col] / total) * 100) if total else 0
478
+ percent_row[col] = f"{percent:g}%"
479
+
480
+ output_columns = ["نام اداره", "فراوانی / درصد", "تعداد خبر"] + PRODUCTION_COLUMNS
481
+ return pd.DataFrame([count_row, percent_row], columns=output_columns)
482
+
483
+
484
+ # ─────────────────────── HTML formatters ───────────────────────
485
+
486
  def format_dataframe_for_html(summary_df, title):
487
  css = """
488
  <style>
 
558
  return html
559
 
560
 
561
+ def format_share_for_html(share_df, title):
562
+ """HTML پیش‌نمایش جدول سهم ادارات"""
563
+ body_rows = []
564
+ for i in range(0, len(share_df), 2):
565
+ count = share_df.iloc[i]
566
+ percent = share_df.iloc[i + 1]
567
+ body_rows.append(
568
+ "<tr>"
569
+ f"<td class='dept thick-right thick-top' rowspan='2'>{count['نام اداره']}</td>"
570
+ f"<td class='row-label thick-top'>{count['فراوانی / درصد']}</td>"
571
+ f"<td class='thick-top'>{count['جمع کل']}</td>"
572
+ f"<td class='thick-top'>{count['اخبار اختصاصی']}</td>"
573
+ f"<td class='thick-top thick-left'>{count['اخبار غیراختصاصی']}</td>"
574
+ "</tr>"
575
+ )
576
+ body_rows.append(
577
+ "<tr>"
578
+ f"<td class='row-label thick-bottom'>{percent['فراوانی / درصد']}</td>"
579
+ f"<td class='thick-bottom'>{percent['جمع کل']}</td>"
580
+ f"<td class='thick-bottom'>{percent['اخبار اختصاصی']}</td>"
581
+ f"<td class='thick-bottom thick-left'>{percent['اخبار غیراختصاصی']}</td>"
582
+ "</tr>"
583
+ )
584
+
585
+ html = f"""
586
+ <div class="report-wrap">
587
+ <div class="report-title">{title}</div>
588
+ <table class="report-table">
589
+ <thead>
590
+ <tr>
591
+ <th class="thick-top thick-right" colspan="2">نام اداره</th>
592
+ <th class="thick-top">جمع کل</th>
593
+ <th class="thick-top">اخبار اختصاصی</th>
594
+ <th class="thick-top thick-left">اخبار غیراختصاصی</th>
595
+ </tr>
596
+ <tr>
597
+ <th class="thick-right thick-bottom">نام اداره</th>
598
+ <th class="thick-bottom">فراوانی / درصد</th>
599
+ <th class="thick-bottom">جمع کل</th>
600
+ <th class="thick-bottom">اخبار اختصاصی</th>
601
+ <th class="thick-left thick-bottom">اخبار غیراختصاصی</th>
602
+ </tr>
603
+ </thead>
604
+ <tbody>
605
+ {''.join(body_rows)}
606
+ </tbody>
607
+ </table>
608
+ </div>
609
+ """
610
+ return html
611
+
612
+
613
+ def format_production_for_html(production_df, title):
614
+ count = production_df.iloc[0]
615
+ percent = production_df.iloc[1]
616
+ html = f"""
617
+ <div class="report-wrap">
618
+ <div class="report-title">{title}</div>
619
+ <table class="report-table">
620
+ <thead>
621
+ <tr>
622
+ <th class="thick-top thick-right" colspan="3">نوع خبر</th>
623
+ <th class="thick-top" colspan="3">عکس</th>
624
+ <th class="thick-top" colspan="3">فیلم</th>
625
+ <th class="thick-top">گرافیک</th>
626
+ <th class="thick-top thick-left">صوت</th>
627
+ </tr>
628
+ <tr>
629
+ <th class="thick-right thick-bottom">نام اداره</th>
630
+ <th class="thick-bottom">فراوانی / درصد</th>
631
+ <th class="thick-bottom">تعداد خبر</th>
632
+ <th class="thick-bottom">اختصاصی</th>
633
+ <th class="thick-bottom">پوششی</th>
634
+ <th class="thick-bottom">دریافتی</th>
635
+ <th class="thick-bottom">اختصاصی</th>
636
+ <th class="thick-bottom">پوششی</th>
637
+ <th class="thick-bottom">دریافتی</th>
638
+ <th class="thick-bottom">اختصاصی</th>
639
+ <th class="thick-left thick-bottom">اختصاصی</th>
640
+ </tr>
641
+ </thead>
642
+ <tbody>
643
+ <tr>
644
+ <td class="dept thick-right thick-top" rowspan="2">{count['نام اداره']}</td>
645
+ <td class="row-label thick-top">{count['فراوانی / درصد']}</td>
646
+ <td class="thick-top">{count['تعداد خبر']}</td>
647
+ {''.join(f"<td class='thick-top'>{count[col]}</td>" for col in PRODUCTION_COLUMNS)}
648
+ </tr>
649
+ <tr>
650
+ <td class="row-label thick-bottom">{percent['فراوانی / درصد']}</td>
651
+ <td class="thick-bottom">{percent['تعداد خبر']}</td>
652
+ {''.join(f"<td class='thick-bottom'>{percent[col]}</td>" for col in PRODUCTION_COLUMNS)}
653
+ </tr>
654
+ </tbody>
655
+ </table>
656
+ </div>
657
+ """
658
+ return html
659
+
660
+
661
+ # ─────────────────────── Excel builder ───────────────────────
662
+
663
+ def _apply_base_style(ws, row, col, value, font, alignment, fill=None):
664
+ cell = ws.cell(row=row, column=col, value=value)
665
+ cell.font = font
666
+ cell.alignment = alignment
667
+ if fill:
668
+ cell.fill = fill
669
+ return cell
670
+
671
+
672
+ def _set_border(cell, left=None, right=None, top=None, bottom=None):
673
+ current = cell.border
674
+ cell.border = Border(
675
+ left=left or current.left,
676
+ right=right or current.right,
677
+ top=top or current.top,
678
+ bottom=bottom or current.bottom,
679
+ )
680
+
681
+
682
+ def _add_summary_sheet(wb, summary_df, title):
683
+ """شیت اول: نوع خبر ادارات"""
684
  ws = wb.active
685
  ws.title = "نوع خبر ادارات"
686
  ws.sheet_view.rightToLeft = True
 
694
  normal_font = Font(name="Tahoma", size=12)
695
  bold_font = Font(name="Tahoma", size=12, bold=True)
696
 
697
+ # عنوان
698
  ws.merge_cells("A1:K1")
699
  ws["A1"] = title
700
  ws["A1"].font = title_font
701
  ws["A1"].alignment = center
702
  ws.row_dimensions[1].height = 34
703
 
704
+ # سطر ۳: گروه‌بندی ستون‌ها
705
  ws.merge_cells("A3:C3")
706
  ws["A3"] = "نوع خبر"
707
  ws.merge_cells("D3:H3")
 
752
  ws.cell(row=row, column=1).font = bold_font
753
  ws.cell(row=row, column=2).font = bold_font
754
 
 
 
 
 
 
 
 
 
 
755
  for col in range(1, max_col + 1):
756
+ _set_border(ws.cell(row=3, column=col), top=thick)
757
+ _set_border(ws.cell(row=4, column=col), bottom=thick)
758
+ _set_border(ws.cell(row=max_row, column=col), bottom=thick)
759
 
760
  for row in range(3, max_row + 1):
761
+ _set_border(ws.cell(row=row, column=1), right=thick)
762
+ _set_border(ws.cell(row=row, column=max_col), left=thick)
763
  for boundary_col in [3, 9]:
764
+ _set_border(ws.cell(row=row, column=boundary_col), left=thick)
765
 
766
  for row in range(5, max_row + 1, 2):
767
  for col in range(1, max_col + 1):
768
+ _set_border(ws.cell(row=row, column=col), top=thick)
769
+ _set_border(ws.cell(row=row + 1, column=col), bottom=thick)
770
+
771
+ widths = {1: 22, 2: 16, 3: 14, 4: 15, 5: 14, 6: 16, 7: 17, 8: 17, 9: 14, 10: 14, 11: 14}
772
+ for col_idx, width in widths.items():
773
+ ws.column_dimensions[get_column_letter(col_idx)].width = width
774
+ for row in range(3, max_row + 1):
775
+ ws.row_dimensions[row].height = 28
776
+
777
+
778
+ def _add_share_sheet(wb, share_df, title):
779
+ """شیت دوم: سهم ادارات در اخبار اختصاصی و غیراختصاصی"""
780
+ ws = wb.create_sheet("سهم ادارات")
781
+ ws.sheet_view.rightToLeft = True
782
+
783
+ thin = Side(style="thin", color="000000")
784
+ thick = Side(style="thick", color="000000")
785
+ header_fill = PatternFill("solid", fgColor="FFFFFF")
786
+ center = Alignment(horizontal="center", vertical="center", wrap_text=True)
787
+ title_font = Font(name="Tahoma", size=16, bold=True)
788
+ header_font = Font(name="Tahoma", size=13, bold=True)
789
+ normal_font = Font(name="Tahoma", size=12)
790
+ bold_font = Font(name="Tahoma", size=12, bold=True)
791
+
792
+ # عنوان
793
+ ws.merge_cells("A1:E1")
794
+ ws["A1"] = title
795
+ ws["A1"].font = title_font
796
+ ws["A1"].alignment = center
797
+ ws.row_dimensions[1].height = 34
798
+
799
+ # سطر ۳
800
+ ws.merge_cells("A3:B3")
801
+ ws["A3"] = "نام اداره"
802
+ ws["C3"] = "جمع کل"
803
+ ws["D3"] = "اخبار اختصاصی"
804
+ ws["E3"] = "اخبار غیراختصاصی"
805
+
806
+ headers = ["نام اداره", "فراوانی / درصد", "جمع کل", "اخبار اختصاصی", "اخب��ر غیراختصاصی"]
807
+ for col_idx, header in enumerate(headers, start=1):
808
+ cell = ws.cell(row=4, column=col_idx, value=header)
809
+ cell.font = header_font
810
+ cell.alignment = center
811
+ cell.fill = header_fill
812
+
813
+ row_idx = 5
814
+ for i in range(0, len(share_df), 2):
815
+ count = share_df.iloc[i]
816
+ percent = share_df.iloc[i + 1]
817
+
818
+ ws.merge_cells(start_row=row_idx, start_column=1, end_row=row_idx + 1, end_column=1)
819
+ ws.cell(row=row_idx, column=1, value=count["نام اداره"])
820
+
821
+ for offset, col in enumerate(["فراوانی / درصد", "جمع کل", "اخبار اختصاصی", "اخبار غیراختصاصی"], start=2):
822
+ ws.cell(row=row_idx, column=offset, value=count[col])
823
+ ws.cell(row=row_idx + 1, column=offset, value=percent[col])
824
+
825
+ row_idx += 2
826
+
827
+ max_row = ws.max_row
828
+ max_col = 5
829
+
830
+ for row in ws.iter_rows(min_row=3, max_row=max_row, min_col=1, max_col=max_col):
831
+ for cell in row:
832
+ cell.alignment = center
833
+ cell.font = normal_font
834
+ cell.border = Border(left=thin, right=thin, top=thin, bottom=thin)
835
+
836
+ for row in [3, 4]:
837
+ for col in range(1, max_col + 1):
838
+ ws.cell(row=row, column=col).font = header_font
839
+ ws.cell(row=row, column=col).fill = header_fill
840
+
841
+ for row in range(5, max_row + 1):
842
+ ws.cell(row=row, column=1).font = bold_font
843
+ ws.cell(row=row, column=2).font = bold_font
844
+
845
+ for col in range(1, max_col + 1):
846
+ _set_border(ws.cell(row=3, column=col), top=thick)
847
+ _set_border(ws.cell(row=4, column=col), bottom=thick)
848
+ _set_border(ws.cell(row=max_row, column=col), bottom=thick)
849
+
850
+ for row in range(3, max_row + 1):
851
+ _set_border(ws.cell(row=row, column=1), right=thick)
852
+ _set_border(ws.cell(row=row, column=max_col), left=thick)
853
+
854
+ for row in range(5, max_row + 1, 2):
855
+ for col in range(1, max_col + 1):
856
+ _set_border(ws.cell(row=row, column=col), top=thick)
857
+ _set_border(ws.cell(row=row + 1, column=col), bottom=thick)
858
+
859
+ widths = {1: 22, 2: 18, 3: 16, 4: 20, 5: 22}
860
  for col_idx, width in widths.items():
861
  ws.column_dimensions[get_column_letter(col_idx)].width = width
862
  for row in range(3, max_row + 1):
863
  ws.row_dimensions[row].height = 28
864
 
865
+
866
+ def _add_production_sheet(wb, production_df, title):
867
+ """شیت سوم: تولیدات معاونت چندرسانه‌ای"""
868
+ ws = wb.create_sheet("تولیدات چندرسانه‌ای")
869
+ ws.sheet_view.rightToLeft = True
870
+
871
+ thin = Side(style="thin", color="000000")
872
+ thick = Side(style="thick", color="000000")
873
+ header_fill = PatternFill("solid", fgColor="FFFFFF")
874
+ center = Alignment(horizontal="center", vertical="center", wrap_text=True)
875
+ title_font = Font(name="Tahoma", size=16, bold=True)
876
+ header_font = Font(name="Tahoma", size=13, bold=True)
877
+ normal_font = Font(name="Tahoma", size=12)
878
+ bold_font = Font(name="Tahoma", size=12, bold=True)
879
+
880
+ ws.merge_cells("A1:K1")
881
+ ws["A1"] = title
882
+ ws["A1"].font = title_font
883
+ ws["A1"].alignment = center
884
+ ws.row_dimensions[1].height = 34
885
+
886
+ ws.merge_cells("A3:C3")
887
+ ws["A3"] = "نوع خبر"
888
+ ws.merge_cells("D3:F3")
889
+ ws["D3"] = "عکس"
890
+ ws.merge_cells("G3:I3")
891
+ ws["G3"] = "فیلم"
892
+ ws["J3"] = "گرافیک"
893
+ ws["K3"] = "صوت"
894
+
895
+ production_headers = [
896
+ "نام اداره", "فراوانی / درصد", "تعداد خبر",
897
+ "اختصاصی", "پوششی", "دریافتی",
898
+ "اختصاصی", "پوششی", "دریافتی",
899
+ "اختصاصی", "اختصاصی",
900
+ ]
901
+ for col_idx, header in enumerate(production_headers, start=1):
902
+ cell = ws.cell(row=4, column=col_idx, value=header)
903
+ cell.font = header_font
904
+ cell.alignment = center
905
+ cell.fill = header_fill
906
+
907
+ count = production_df.iloc[0]
908
+ percent = production_df.iloc[1]
909
+ ws.merge_cells(start_row=5, start_column=1, end_row=6, end_column=1)
910
+ ws.cell(row=5, column=1, value=count["نام اداره"])
911
+
912
+ values_count = [count["فراوانی / درصد"], count["تعداد خبر"]] + [count[col] for col in PRODUCTION_COLUMNS]
913
+ values_percent = [percent["فراوانی / درصد"], percent["تعداد خبر"]] + [percent[col] for col in PRODUCTION_COLUMNS]
914
+ for offset, value in enumerate(values_count, start=2):
915
+ ws.cell(row=5, column=offset, value=value)
916
+ for offset, value in enumerate(values_percent, start=2):
917
+ ws.cell(row=6, column=offset, value=value)
918
+
919
+ for row in ws.iter_rows(min_row=3, max_row=6, min_col=1, max_col=11):
920
+ for cell in row:
921
+ cell.alignment = center
922
+ cell.font = normal_font
923
+ cell.border = Border(left=thin, right=thin, top=thin, bottom=thin)
924
+
925
+ for row in [3, 4]:
926
+ for col in range(1, 12):
927
+ ws.cell(row=row, column=col).font = header_font
928
+ ws.cell(row=row, column=col).fill = header_fill
929
+
930
+ for col in range(1, 12):
931
+ _set_border(ws.cell(row=3, column=col), top=thick)
932
+ _set_border(ws.cell(row=4, column=col), bottom=thick)
933
+ _set_border(ws.cell(row=6, column=col), bottom=thick)
934
+
935
+ for row in range(3, 7):
936
+ _set_border(ws.cell(row=row, column=1), right=thick)
937
+ _set_border(ws.cell(row=row, column=11), left=thick)
938
+ for boundary_col in [3, 6, 9, 10]:
939
+ _set_border(ws.cell(row=row, column=boundary_col), left=thick)
940
+
941
+ for row in range(5, 7):
942
+ for col in range(1, 12):
943
+ _set_border(ws.cell(row=row, column=col), top=thick if row == 5 else None)
944
+ _set_border(ws.cell(row=row, column=col), bottom=thick if row == 6 else None)
945
+
946
+ widths = {1: 22, 2: 16, 3: 14, 4: 15, 5: 14, 6: 16, 7: 17, 8: 17, 9: 14, 10: 14, 11: 14}
947
+ for col_idx, width in widths.items():
948
+ ws.column_dimensions[get_column_letter(col_idx)].width = width
949
+ for row in range(3, 7):
950
+ ws.row_dimensions[row].height = 28
951
+
952
+ ws.cell(row=5, column=1).font = bold_font
953
+ ws.cell(row=5, column=2).font = bold_font
954
+ ws.cell(row=6, column=2).font = bold_font
955
+
956
+
957
+ def save_all_excel(summary_df, title, share_df, share_title, production_df, production_title):
958
+ wb = Workbook()
959
+ _add_summary_sheet(wb, summary_df, title)
960
+ if share_df is not None:
961
+ _add_share_sheet(wb, share_df, share_title)
962
+ _add_production_sheet(wb, production_df, production_title)
963
+
964
  output_dir = tempfile.mkdtemp(prefix="news_type_report_")
965
  output_path = os.path.join(output_dir, "جدول_نوع_خبر_ادارات.xlsx")
966
  wb.save(output_path)
 
969
 
970
  def process_file(input_file, report_title):
971
  if input_file is None:
972
+ return None, "<div style='direction:rtl; color:#000; font-family:Tahoma;'>لطفاً فایل اکسل را بارگذاری کنید.</div>"
973
 
974
  try:
975
  file_path = input_file if isinstance(input_file, str) else input_file.name
 
977
  base_title = normalize_text(report_title) or "نوع خبر ادارات"
978
  date_label = infer_date_label(filter_persian_isna_rows(df))
979
  title = f"{base_title} - {date_label}" if date_label and date_label not in base_title else base_title
980
+
981
  summary_df = build_summary_table(df)
982
+ share_df = build_share_table(df)
983
+ production_df = build_production_table(df)
984
+
985
+ share_title = f"سهم ادارات در اخبار اختصاصی و غیراختصاصی - {date_label}" if date_label else "سهم ادارات در اخبار اختصاصی و غیراختصاصی"
986
+ production_title = f"نوع تولیدات معاونت چندرسانه‌ای - {date_label}" if date_label else "نوع تولیدات معاونت چندرسانه‌ای"
987
+
988
+ html_summary = format_dataframe_for_html(summary_df, title)
989
+ html_share = format_share_for_html(share_df, share_title) if share_df is not None else ""
990
+ html_production = format_production_for_html(production_df, production_title)
991
+
992
+ combined_html = f"""
993
+ <div style="direction:rtl; font-family:Tahoma; color:#000;">
994
+ <h2 style="color:#000; text-align:center;">شیت ۱: نوع خبر ادارات</h2>
995
+ {html_summary}
996
+ <hr style="margin:32px 0; border:2px solid #000;">
997
+ <h2 style="color:#000; text-align:center;">شیت ۲: سهم ادارات در اخبار اختصاصی و غیراختصاصی</h2>
998
+ {html_share}
999
+ <hr style="margin:32px 0; border:2px solid #000;">
1000
+ <h2 style="color:#000; text-align:center;">شیت ۳: تولیدات معاونت چندرسانه‌ای</h2>
1001
+ {html_production}
1002
+ </div>
1003
+ """
1004
+
1005
+ output_path = save_all_excel(summary_df, title, share_df, share_title, production_df, production_title)
1006
+ return output_path, combined_html
1007
  except Exception as exc:
1008
  error_html = f"""
1009
  <div style="direction:rtl; text-align:right; font-family:Tahoma; padding:18px;
1010
+ background:#f5f5f5; border-right:4px solid #000; color:#000;">
1011
+ <h3 style="margin-top:0; color:#000;">خطا در ساخت جدول</h3>
1012
  <p>{exc}</p>
1013
+ <p style="font-size:13px; color:#000;">فایل باید ��داقل ستون‌های «نام اداره/سرویس» و «نوع خبر» را داشته باشد.</p>
1014
  </div>
1015
  """
1016
  return None, error_html
 
1021
  direction: rtl;
1022
  font-family: Tahoma, Arial, sans-serif;
1023
  background: #f5f7fb;
1024
+ color: #000 !important;
1025
  }
1026
  .contain {
1027
  max-width: 1200px;
1028
  }
1029
  #header-box {
1030
  background: white;
1031
+ border: 1px solid #000;
1032
  border-radius: 10px;
1033
  padding: 22px;
1034
  margin-bottom: 16px;
1035
  text-align: center;
1036
  }
1037
+ label, .label-wrap, span, p, div {
1038
+ color: #000 !important;
1039
+ }
1040
  """
1041
 
1042
 
 
1044
  gr.HTML(
1045
  """
1046
  <div id="header-box">
1047
+ <h1 style="margin:0 0 10px 0; color:#000;">سازنده جدول نوع خبر ادارات</h1>
1048
+ <p style="margin:0; color:#000; line-height:1.8;">
1049
+ فایل اکسل کامل را بارگذاری کنید تا سه جدول (نوع خبر ادارات، سهم ادارات، تولیدات چندرسانه‌ای) ساخته شوند و خروجی اکسل سه‌شیته راست‌چین بگیرید.
1050
  </p>
1051
  </div>
1052
  """
 
1059
  type="filepath",
1060
  )
1061
  report_title = gr.Textbox(
1062
+ label="عنوان جدول اول",
1063
  value="نوع خبر ادارات",
1064
  )
1065
 
1066
+ run_btn = gr.Button("ساخت جداول", variant="primary", size="lg")
1067
 
1068
  with gr.Row():
1069
+ output_file = gr.File(label="دانلود فایل اکسل خروجی (سه شیت)")
1070
 
1071
+ output_html = gr.HTML(label="پیش‌نمایش جداول")
1072
 
1073
  gr.HTML(
1074
  """
1075
+ <div style="direction:rtl; font-family:Tahoma; color:#000; font-size:13px; margin-top:18px; line-height:1.9;">
1076
+ <b>شیت اول:</b> نوع خبر ادارات (بدون چندرسانه‌ای) |
1077
+ <b>شیت دوم:</b> سهم ادارات در اخبار اختصاصی و غیراختصاصی (شامل چندرسانه‌ای) |
1078
+ <b>شیت سوم:</b> تولیدات معاونت چندرسانه‌ای
1079
+ <br>
1080
  ستون‌های قابل تشخیص برای اداره: «نام اداره»، «اداره»، «سرویس»، «گروه خبری».
1081
  ستون‌های قابل تشخیص برای نوع خبر: «نوع خبر»، «قالب»، «فرمت»، «دسته خبر».
1082
  اگر ستون «سایت» وجود داشته باشد، فقط ردیف‌هایی که مقدار سایت آن‌ها دقیقاً «ایسنا» است محاسبه می‌شوند.