Download app.py from aysan98/sources: direct link, hf CLI and curl.
- Browser
- Download file 45.3 kB
-
https://huggingface.co/spaces/aysan98/sources/resolve/main/app.py
- Command line
-
hf download hf://spaces/aysan98/sources/app.py
-
curl -L -o app.py https://huggingface.co/spaces/aysan98/sources/resolve/main/app.py
45.3 kB
| import gradio as gr | |
| import pandas as pd | |
| import plotly.graph_objects as go | |
| import warnings | |
| warnings.filterwarnings('ignore') | |
| # ───────────────────────────────────────────── | |
| # ثابتها | |
| # ───────────────────────────────────────────── | |
| EXCLUDE_PREFIXES = ['استان ها', 'بازار', 'ایسنا+', 'صوت', 'گرافیک', 'ویدئو', 'عکس'] | |
| EXCLUDE_LABELS = { | |
| 'استان ها': 'استانها', | |
| 'بازار': 'بازار', | |
| 'ایسنا+': 'ایسنا+', | |
| 'صوت': 'صوت', | |
| 'گرافیک': 'گرافیک', | |
| 'ویدئو': 'ویدئو', | |
| 'عکس': 'عکس', | |
| } | |
| MONTH_NAMES = { | |
| '01': 'فروردین', '02': 'اردیبهشت', '03': 'خرداد', | |
| '04': 'تیر', '05': 'مرداد', '06': 'شهریور', | |
| '07': 'مهر', '08': 'آبان', '09': 'آذر', | |
| '10': 'دی', '11': 'بهمن', '12': 'اسفند', | |
| } | |
| COLORS = { | |
| 'primary': '#1a237e', | |
| 'accent': '#1565c0', | |
| 'green': '#2e7d32', | |
| 'amber': '#f57f17', | |
| 'red': '#b71c1c', | |
| 'teal': '#00695c', | |
| 'purple': '#6a1b9a', | |
| 'bg_blue': '#e8eaf6', | |
| 'bg_green': '#e8f5e9', | |
| 'bg_amber': '#fff8e1', | |
| 'bg_red': '#ffebee', | |
| 'bg_teal': '#e0f2f1', | |
| 'text': '#1a1a1a', | |
| 'subtext': '#1a1a1a', | |
| 'border': '#cfd8dc', | |
| 'row_even': '#f5f7ff', | |
| 'row_odd': '#ffffff', | |
| } | |
| # ───────────────────────────────────────────── | |
| # توابع کمکی | |
| # ───────────────────────────────────────────── | |
| def fmt(n): | |
| try: | |
| return f"{int(n):,}" | |
| except: | |
| return '۰' | |
| def pct(a, b): | |
| if b == 0: | |
| return '۰٪' | |
| return f"{round(a / b * 100, 1)}٪" | |
| def service_prefix(s): | |
| if pd.isna(s): | |
| return '' | |
| return str(s).split('>')[0].strip() | |
| def is_excluded(s): | |
| p = service_prefix(s) | |
| if any(p == ex for ex in EXCLUDE_PREFIXES): | |
| return True | |
| # حذف انگلیسی: اگر اکثر کاراکترها ASCII باشند | |
| if p and all(ord(c) < 128 or c == ' ' for c in p if c.strip()): | |
| return True | |
| # حذف عربی خالص: حروف مختص عربی (نه فارسی) | |
| arabic_only = set('ثذضظغؤئءةى') | |
| if p and any(c in arabic_only for c in p): | |
| return True | |
| return False | |
| def fa_to_en(s): | |
| """تبدیل ارقام فارسی/عربی به انگلیسی""" | |
| mapping = str.maketrans('۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩', '01234567890123456789') | |
| return s.translate(mapping) | |
| PERSIAN_MONTH_DAYS = {1: 31, 2: 31, 3: 31, 4: 31, 5: 31, 6: 31, | |
| 7: 30, 8: 30, 9: 30, 10: 30, 11: 30, 12: 29} | |
| def parse_period(df): | |
| """تشخیص انعطافپذیر بازه زمانی گزارش: یک روز / چند روز / یک ماه کامل""" | |
| col = 'تاریخ انتشار' | |
| if col not in df.columns: | |
| return '' | |
| raw = df[col].dropna().astype(str) | |
| if raw.empty: | |
| return '' | |
| dates = [] | |
| for s in raw: | |
| parts = fa_to_en(s).replace('،', '/').split('/') | |
| if len(parts) < 3: | |
| continue | |
| try: | |
| dates.append((int(parts[0]), int(parts[1]), int(parts[2]))) | |
| except ValueError: | |
| continue | |
| if not dates: | |
| return '' | |
| uniq = sorted(set(dates)) | |
| y0, m0, _ = uniq[0] | |
| y1, m1, _ = uniq[-1] | |
| if len(uniq) == 1: | |
| y, m, d = uniq[0] | |
| return f"{d} {MONTH_NAMES.get(str(m).zfill(2), m)} {y}" | |
| if (y0, m0) == (y1, m1): | |
| days = sorted(d for _, _, d in uniq) | |
| month_name = MONTH_NAMES.get(str(m0).zfill(2), m0) | |
| full_days = PERSIAN_MONTH_DAYS.get(m0, 31) | |
| if days[0] == 1 and days[-1] >= full_days: | |
| return f"{month_name} {y0}" | |
| if days[-1] - days[0] + 1 == len(days): | |
| return f"{days[0]} تا {days[-1]} {month_name} {y0}" | |
| return f"{'، '.join(str(x) for x in days[:-1])} و {days[-1]} {month_name} {y0}" | |
| d0, d1 = uniq[0][2], uniq[-1][2] | |
| mn0 = MONTH_NAMES.get(str(m0).zfill(2), m0) | |
| mn1 = MONTH_NAMES.get(str(m1).zfill(2), m1) | |
| return f"{d0} {mn0} {y0} تا {d1} {mn1} {y1}" | |
| def load_and_filter(file_bytes): | |
| import io | |
| df = pd.read_excel(io.BytesIO(file_bytes), sheet_name=0) | |
| df['_excluded'] = df['سرویس'].apply(is_excluded) | |
| df_main = df[~df['_excluded']].copy() | |
| df_main['_has_source'] = df_main['منبع'].notna() & (df_main['منبع'].astype(str).str.strip() != '') | |
| df_main['_non_received'] = df_main['_has_source'] & (df_main['نوع خبر'].astype(str).str.strip() != 'دریافتی') | |
| df_main['_journalist'] = df_main['خبرنگار'].astype(str).str.strip() | |
| df_main['_recv_with_journalist'] = (df_main['نوع خبر'].astype(str).str.strip() == 'دریافتی') & \ | |
| ~df_main['_journalist'].isin(['', '-', 'nan', 'None']) | |
| df_main['_service_prefix'] = df_main['سرویس'].apply(service_prefix) | |
| return df, df_main | |
| # ───────────────────────────────────────────── | |
| # HTML helpers | |
| # ───────────────────────────────────────────── | |
| TH_STYLE = f"padding:12px 16px;border:1px solid {COLORS['accent']};text-align:right;color:white;font-weight:bold;font-size:16px;background:{COLORS['accent']};" | |
| TD_STYLE = f"padding:11px 15px;border:1px solid {COLORS['border']};text-align:right;color:{COLORS['text']};font-size:15px;" | |
| def stat_card(value, label, bg, color, border_color, sub=''): | |
| sub_html = f"<div style='font-size:12px;color:{COLORS['subtext']};margin-top:4px;'>{sub}</div>" if sub else '' | |
| return f""" | |
| <div style='flex:1;min-width:150px;background:{bg};border-radius:12px; | |
| padding:18px 14px;text-align:center;border-top:5px solid {border_color}; | |
| box-shadow:0 2px 8px rgba(0,0,0,0.08);'> | |
| <div style='font-size:30px;font-weight:bold;color:{color};'>{value}</div> | |
| <div style='font-size:14px;color:{COLORS["subtext"]};margin-top:6px;font-weight:600;'>{label}</div> | |
| {sub_html} | |
| </div>""" | |
| def section_title(text, icon=''): | |
| return f""" | |
| <h3 style='color:{COLORS["primary"]};margin:32px 0 14px 0;font-size:19px; | |
| border-right:5px solid {COLORS["accent"]};padding-right:12px; | |
| display:flex;align-items:center;gap:6px;'> | |
| {icon} {text} | |
| </h3>""" | |
| def make_table(rows_html, headers): | |
| ths = ''.join(f"<th style='{TH_STYLE}'>{h}</th>" for h in headers) | |
| return f""" | |
| <div style='overflow-x:auto;margin:10px 0 28px 0;border-radius:8px; | |
| box-shadow:0 1px 6px rgba(0,0,0,0.1);'> | |
| <table style='width:100%;border-collapse:collapse;font-size:15px;'> | |
| <thead><tr>{ths}</tr></thead> | |
| <tbody>{rows_html}</tbody> | |
| </table></div>""" | |
| def table_row(cells, even=True): | |
| bg = COLORS['row_even'] if even else COLORS['row_odd'] | |
| tds = ''.join(f"<td style='{TD_STYLE}background:{bg};'>{c}</td>" for c in cells) | |
| return f"<tr>{tds}</tr>" | |
| # ───────────────────────────────────────────── | |
| # جدول ترکیب نوع خبر خبرنگاران (بیش از N خبر) | |
| # ───────────────────────────────────────────── | |
| def build_journalist_type_table(df_svc, min_count=10): | |
| jf = df_svc[~df_svc['_journalist'].isin(['', '-', 'nan', 'None'])].copy() | |
| if jf.empty: | |
| return None | |
| totals = jf.groupby('_journalist').size() | |
| eligible = totals[totals > min_count].sort_values(ascending=False) | |
| if eligible.empty: | |
| return None | |
| type_order = jf[jf['_journalist'].isin(eligible.index)]['نوع خبر'].value_counts().index.tolist() | |
| rows_html = '' | |
| for i, (name, total) in enumerate(eligible.items()): | |
| sub = jf[jf['_journalist'] == name] | |
| cells = [name, fmt(total)] | |
| for t in type_order: | |
| c = (sub['نوع خبر'] == t).sum() | |
| cells.append(pct(c, total) if c else '—') | |
| rows_html += table_row(cells, even=(i % 2 == 0)) | |
| return make_table(rows_html, ['خبرنگار', 'کل خبر'] + type_order) | |
| # ───────────────────────────────────────────── | |
| # نمودار میلهای ناشران | |
| # ───────────────────────────────────────────── | |
| def make_publisher_chart(df_svc, title=''): | |
| nr = df_svc[df_svc['_non_received']] | |
| if nr.empty: | |
| return None | |
| counts = nr['ناشر'].value_counts().head(12) | |
| labels = [str(l) for l in counts.index][::-1] | |
| vals = list(counts.values)[::-1] | |
| fig = go.Figure(go.Bar( | |
| y=labels, x=vals, orientation='h', | |
| marker=dict( | |
| color=vals, | |
| colorscale=[[0, '#90caf9'], [0.5, '#1565c0'], [1, '#0d47a1']], | |
| showscale=False, | |
| line=dict(width=0) | |
| ), | |
| text=vals, textposition='outside', | |
| textfont=dict(size=14, color='#1a1a1a'), | |
| hovertemplate='<b>%{y}</b>: %{x} خبر<extra></extra>' | |
| )) | |
| fig.update_layout( | |
| title=dict( | |
| text=f'ناشران خبرهای با منبع غیردریافتی — {title}', | |
| font=dict(size=15, family='Tahoma', color=COLORS['primary']), | |
| x=0.5, xanchor='center' | |
| ), | |
| font=dict(family='Tahoma', size=14, color='#1a1a1a'), | |
| height=max(300, len(labels) * 42 + 100), | |
| plot_bgcolor='rgba(232,234,246,0.3)', | |
| paper_bgcolor='white', | |
| xaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#1a1a1a')), | |
| yaxis=dict(tickfont=dict(color='#1a1a1a', size=13)), | |
| margin=dict(l=10, r=80, t=60, b=40) | |
| ) | |
| return fig | |
| # ───────────────────────────────────────────── | |
| # بخش آمار کلی | |
| # ───────────────────────────────────────────── | |
| def build_overview_html(df_main, period): | |
| total = len(df_main) | |
| with_src = df_main['_has_source'].sum() | |
| non_recv = df_main['_non_received'].sum() | |
| recv_j = df_main['_recv_with_journalist'].sum() | |
| pct_src = pct(with_src, total) | |
| pct_nr_src = pct(non_recv, with_src) | |
| pct_recv_j = pct(recv_j, total) | |
| # خبرنگاری با بیشترین خبر دریافتی به نام خود | |
| rj_counts = df_main[df_main['_recv_with_journalist']]['_journalist'].value_counts() | |
| top_rj = rj_counts.index[0] if not rj_counts.empty else '—' | |
| top_rj_cnt = rj_counts.iloc[0] if not rj_counts.empty else 0 | |
| # سرویس با بیشترین و کمترین خبر | |
| svc_counts = df_main.groupby('_service_prefix').size() | |
| max_svc = svc_counts.idxmax() if not svc_counts.empty else '—' | |
| min_svc = svc_counts.idxmin() if not svc_counts.empty else '—' | |
| max_cnt = svc_counts.max() if not svc_counts.empty else 0 | |
| min_cnt = svc_counts.min() if not svc_counts.empty else 0 | |
| # سرویس با بیشترین خبر غیردریافتی | |
| nr_counts = df_main[df_main['_non_received']].groupby('_service_prefix').size() | |
| top_nr_svc = nr_counts.idxmax() if not nr_counts.empty else '—' | |
| top_nr_cnt = nr_counts.max() if not nr_counts.empty else 0 | |
| # پرتکرارترین ناشر (خبرهای غیردریافتی) | |
| pub_counts = df_main[df_main['_non_received']]['ناشر'].value_counts() | |
| top_pub = pub_counts.index[0] if not pub_counts.empty else '—' | |
| top_pub_cnt = pub_counts.iloc[0] if not pub_counts.empty else 0 | |
| excluded_names = ' ، '.join(EXCLUDE_LABELS.values()) | |
| html = f""" | |
| <div style='direction:rtl;font-family:Tahoma,Arial;padding:28px 24px; | |
| background:white;color:{COLORS["text"]};line-height:1.9;'> | |
| <!-- عنوان --> | |
| <div style='text-align:center;background:linear-gradient(135deg,{COLORS["primary"]},{COLORS["accent"]}); | |
| border-radius:14px;padding:28px 20px;margin-bottom:28px; | |
| box-shadow:0 4px 16px rgba(21,101,192,0.25);'> | |
| <h1 style='color:white;font-size:24px;margin:0 0 8px 0;font-weight:bold;'> | |
| دستیار نظارت بر اخبار | |
| </h1> | |
| <p style='color:rgba(255,255,255,0.85);font-size:16px;margin:0;'> | |
| {period} | خبرگزاری دانشجویان ایران (ایسنا) | |
| </p> | |
| </div> | |
| <!-- توضیح موارد حذفشده --> | |
| <div style='background:#fff3e0;border-radius:10px;padding:14px 18px; | |
| margin-bottom:24px;border-right:5px solid {COLORS["amber"]}; | |
| font-size:15px;color:#1a1a1a;'> | |
| <b style='color:#7f4000;'>⚠ موارد خارج از بررسی:</b> | |
| سرویسهای <b style='color:#1a1a1a;'>{excluded_names}</b> از تمام آمارها حذف شدهاند. | |
| </div> | |
| {section_title('آمار کلی', '📊')} | |
| <div style='display:flex;flex-wrap:wrap;gap:14px;margin-bottom:24px;'> | |
| {stat_card(fmt(total), 'کل خبرهای منتشرشده', COLORS['bg_blue'], COLORS['primary'], COLORS['accent'])} | |
| {stat_card(fmt(with_src), 'خبرهای دارای منبع', COLORS['bg_green'], COLORS['green'], COLORS['green'], pct_src + ' از کل')} | |
| {stat_card(fmt(non_recv), 'دارای منبع / غیردریافتی', COLORS['bg_amber'], COLORS['amber'], COLORS['amber'], pct_nr_src + ' از دارای منبع')} | |
| {stat_card(fmt(recv_j), 'دریافتی ثبتشده به نام خبرنگار', COLORS['bg_teal'], COLORS['teal'], COLORS['teal'], pct_recv_j + ' از کل')} | |
| </div> | |
| <!-- نکات کلیدی --> | |
| {section_title('نکات کلیدی', '🔍')} | |
| <div style='border-radius:10px;overflow:hidden;margin-bottom:28px;'> | |
| <div style='background:#1a237e;padding:14px 20px;display:flex;justify-content:space-between;align-items:center;'> | |
| <span style='color:white;font-size:15px;font-weight:bold;'>📌 پُرخبرترین سرویس</span> | |
| <span style='color:#fff176;font-size:17px;font-weight:bold;'>{max_svc} | {fmt(max_cnt)} خبر</span> | |
| </div> | |
| <div style='background:#1a237e;padding:14px 20px;display:flex;justify-content:space-between;align-items:center;'> | |
| <span style='color:white;font-size:15px;font-weight:bold;'>📌 بیشترین خبر غیردریافتی</span> | |
| <span style='color:#ce93d8;font-size:17px;font-weight:bold;'>{top_nr_svc} | {fmt(top_nr_cnt)} مورد</span> | |
| </div> | |
| <div style='background:#283593;padding:14px 20px;display:flex;justify-content:space-between;align-items:center;'> | |
| <span style='color:white;font-size:15px;font-weight:bold;'>📌 ناشری که بیشترین میزان خبرهای با منبع با نوع غیردریافتی ارسال کرده</span> | |
| <span style='color:#ffcc80;font-size:17px;font-weight:bold;'>{top_pub} | {fmt(top_pub_cnt)} خبر</span> | |
| </div> | |
| <div style='background:#004d40;padding:14px 20px;display:flex;justify-content:space-between;align-items:center;'> | |
| <span style='color:white;font-size:15px;font-weight:bold;'>📌 خبرنگاری با بیشترین خبر دریافتی به نام خود</span> | |
| <span style='color:#80cbc4;font-size:17px;font-weight:bold;'>{top_rj} | {fmt(top_rj_cnt)} خبر</span> | |
| </div> | |
| </div> | |
| </div>""" | |
| return html | |
| # ───────────────────────────────────────────── | |
| # بخش هر سرویس — آمار + جدول HTML | |
| # ───────────────────────────────────────────── | |
| def build_service_html(svc_name, df_svc, period=''): | |
| total = len(df_svc) | |
| with_src = df_svc['_has_source'].sum() | |
| non_recv = df_svc['_non_received'].sum() | |
| recv_j = df_svc['_recv_with_journalist'].sum() | |
| pct_src = pct(with_src, total) | |
| pct_nr = pct(non_recv, with_src) | |
| pct_rj = pct(recv_j, total) | |
| nr_df = df_svc[df_svc['_non_received']][['تیتر', 'نوع خبر', 'منبع', 'ناشر', 'خبرنگار']].copy() | |
| if nr_df.empty: | |
| table_html = f"<p style='color:#1a1a1a;font-size:15px;padding:10px 0;'>خبری با منبع غیردریافتی وجود ندارد.</p>" | |
| else: | |
| rows_html = '' | |
| for i, (_, row) in enumerate(nr_df.iterrows()): | |
| bg = COLORS['row_even'] if i % 2 == 0 else COLORS['row_odd'] | |
| type_val = str(row.get('نوع خبر', '—')) | |
| cells = [ | |
| f"<td style='{TD_STYLE}background:{bg};'>{str(row.get('تیتر','—'))}</td>", | |
| f"<td style='{TD_STYLE}background:{bg};'><span style='background:#e3f2fd;color:#1a1a1a;padding:3px 8px;border-radius:5px;font-size:14px;font-weight:bold;'>{type_val}</span></td>", | |
| f"<td style='{TD_STYLE}background:{bg};'>{str(row.get('منبع','—'))}</td>", | |
| f"<td style='{TD_STYLE}background:{bg};'><b style='color:{COLORS['accent']};'>{str(row.get('ناشر','—'))}</b></td>", | |
| f"<td style='{TD_STYLE}background:{bg};'>{str(row.get('خبرنگار','—'))}</td>", | |
| ] | |
| rows_html += f"<tr>{''.join(cells)}</tr>" | |
| table_html = make_table(rows_html, ['تیتر', 'نوع خبر', 'منبع', 'ناشر', 'خبرنگار']) | |
| rj_df = df_svc[df_svc['_recv_with_journalist']][['تیتر', 'خبرنگار', 'ناشر']].copy() | |
| if rj_df.empty: | |
| rj_table_html = f"<p style='color:#1a1a1a;font-size:15px;padding:10px 0;'>خبر دریافتی ثبتشده به نام خبرنگار وجود ندارد.</p>" | |
| else: | |
| rows_html2 = '' | |
| for i, (_, row) in enumerate(rj_df.iterrows()): | |
| bg = COLORS['row_even'] if i % 2 == 0 else COLORS['row_odd'] | |
| cells = [ | |
| f"<td style='{TD_STYLE}background:{bg};'>{str(row.get('تیتر','—'))}</td>", | |
| f"<td style='{TD_STYLE}background:{bg};'><b style='color:{COLORS['teal']};'>{str(row.get('خبرنگار','—'))}</b></td>", | |
| f"<td style='{TD_STYLE}background:{bg};'>{str(row.get('ناشر','—'))}</td>", | |
| ] | |
| rows_html2 += f"<tr>{''.join(cells)}</tr>" | |
| rj_table_html = make_table(rows_html2, ['تیتر', 'خبرنگار', 'ناشر']) | |
| jt_table = build_journalist_type_table(df_svc) | |
| jt_html = jt_table if jt_table else "<p style='color:#1a1a1a;font-size:15px;padding:10px 0;'>خبرنگاری با بیش از ۱۰ خبر در این سرویس وجود ندارد.</p>" | |
| html = f""" | |
| <div style='direction:rtl;font-family:Tahoma,Arial;padding:22px 20px; | |
| background:white;color:{COLORS["text"]};border-radius:12px; | |
| box-shadow:0 2px 10px rgba(0,0,0,0.07);margin-bottom:8px;line-height:1.8;'> | |
| <div style='background:linear-gradient(90deg,{COLORS["accent"]},{COLORS["primary"]}); | |
| border-radius:10px;padding:14px 20px;margin-bottom:20px; | |
| display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;'> | |
| <h2 style='color:white;margin:0;font-size:20px;'>📂 {svc_name}</h2> | |
| <span style='color:rgba(255,255,255,0.85);font-size:14px;'> | |
| دستیار نظارت بر اخبار | {period} | |
| </span> | |
| </div> | |
| <div style='display:flex;flex-wrap:wrap;gap:12px;margin-bottom:16px;'> | |
| {stat_card(fmt(total), 'کل خبرهای منتشرشده', COLORS['bg_blue'], COLORS['primary'], COLORS['accent'])} | |
| {stat_card(fmt(with_src), 'دارای منبع', COLORS['bg_green'], COLORS['green'], COLORS['green'], pct_src + ' از کل')} | |
| {stat_card(fmt(non_recv), 'دارای منبع / غیردریافتی', COLORS['bg_amber'], COLORS['amber'], COLORS['amber'], pct_nr + ' از دارای منبع')} | |
| {stat_card(fmt(recv_j), 'دریافتی به نام خبرنگار', COLORS['bg_teal'], COLORS['teal'], COLORS['teal'], pct_rj + ' از کل')} | |
| </div> | |
| {section_title(f'خبرهای با منبع غیردریافتی ({fmt(non_recv)} مورد)', '📋')} | |
| {table_html} | |
| {section_title(f'خبرهای دریافتی ثبتشده به نام خبرنگار ({fmt(recv_j)} مورد)', '🖊️')} | |
| {rj_table_html} | |
| {section_title('ترکیب نوع خبر خبرنگاران (بیش از ۱۰ خبر)', '📈')} | |
| {jt_html} | |
| </div>""" | |
| return html | |
| # ───────────────────────────────────────────── | |
| # تابع اصلی | |
| # ───────────────────────────────────────────── | |
| def process(file_bytes): | |
| if file_bytes is None: | |
| return "<p style='direction:rtl;font-family:Tahoma;color:#b71c1c;padding:20px;'>لطفاً فایل اکسل را انتخاب کنید.</p>", [] | |
| try: | |
| df_raw, df_main = load_and_filter(file_bytes) | |
| period = parse_period(df_main) | |
| overview_html = build_overview_html(df_main, period) | |
| prefixes_ordered = list(dict.fromkeys( | |
| df_main['_service_prefix'].dropna().tolist() | |
| )) | |
| # هر سرویس: html آماری+جدول + نمودار میلهای | |
| service_blocks = [] | |
| for prefix in prefixes_ordered: | |
| if not prefix: | |
| continue | |
| df_svc = df_main[df_main['_service_prefix'] == prefix] | |
| svc_html = build_service_html(prefix, df_svc, period) | |
| bar_fig = make_publisher_chart(df_svc, prefix) | |
| service_blocks.append((svc_html, bar_fig)) | |
| sections_header = f""" | |
| <div style='direction:rtl;font-family:Tahoma,Arial;padding:0 24px 4px 24px;background:white;'> | |
| <h2 style='color:{COLORS["primary"]};font-size:21px;border-bottom:3px solid {COLORS["accent"]}; | |
| padding-bottom:10px;margin-bottom:20px;'> | |
| 📁 آمار تفکیکی سرویسها | |
| </h2> | |
| </div>""" | |
| return overview_html, sections_header, service_blocks | |
| except Exception as e: | |
| import traceback | |
| err = f"""<div style='direction:rtl;font-family:Tahoma;padding:20px;color:#b71c1c;'> | |
| <h3>خطا در پردازش فایل</h3> | |
| <pre style='font-size:12px;color:#424242;background:#f5f5f5;padding:12px;border-radius:6px;'> | |
| {traceback.format_exc()}</pre></div>""" | |
| return err, '', [] | |
| # ───────────────────────────────────────────── | |
| # رابط کاربری Gradio | |
| # ───────────────────────────────────────────── | |
| MAX_SERVICES = 20 | |
| def run(file_bytes): | |
| overview_html, header_html, service_blocks = process(file_bytes) | |
| # خروجی: overview + header + برای هر سرویس: html + bar_fig | |
| outputs = [overview_html, header_html] | |
| for i in range(MAX_SERVICES): | |
| if i < len(service_blocks): | |
| svc_html, bar_fig = service_blocks[i] | |
| outputs.append(svc_html) | |
| outputs.append(bar_fig if bar_fig is not None else go.Figure()) | |
| else: | |
| outputs.append("") | |
| outputs.append(go.Figure()) | |
| return outputs | |
| custom_css = """ | |
| .gradio-container { | |
| direction: rtl; | |
| background: linear-gradient(135deg, #e8eaf6 0%, #e0f2f1 100%); | |
| min-height: 100vh; | |
| font-family: Tahoma, Arial, sans-serif; | |
| } | |
| footer { display: none !important; } | |
| """ | |
| with gr.Blocks(theme=gr.themes.Soft(), css=custom_css, title="داشبورد آمار خبرهای ایسنا") as demo: | |
| gr.HTML(f""" | |
| <div style='text-align:center;direction:rtl;font-family:Tahoma;padding:22px 20px; | |
| background:rgba(255,255,255,0.95);border-radius:14px;margin-bottom:14px; | |
| box-shadow:0 2px 12px rgba(21,101,192,0.12);'> | |
| <h1 style='color:{COLORS["primary"]};margin:0 0 8px 0;font-size:26px;font-weight:bold;'> | |
| داشبورد آمار خبرهای دریافتی دارای منبع | |
| </h1> | |
| <p style='color:#1a1a1a;font-size:15px;margin:0;'> | |
| فایل اکسل ماهانه سرویسها را آپلود کنید | |
| </p> | |
| <hr style='border:2px solid {COLORS["accent"]};width:30%;margin:14px auto 0;'> | |
| </div> | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| file_input = gr.File( | |
| label="📂 آپلود فایل اکسل", | |
| file_types=[".xlsx", ".xls"], | |
| type="binary" | |
| ) | |
| btn = gr.Button("🔍 شروع تحلیل", variant="primary", size="lg") | |
| out_overview = gr.HTML() | |
| out_header = gr.HTML() | |
| # هر سرویس: html + نمودار میلهای | |
| svc_htmls = [] | |
| svc_bars = [] | |
| for _ in range(MAX_SERVICES): | |
| svc_htmls.append(gr.HTML()) | |
| svc_bars.append(gr.Plot()) | |
| all_outputs = [out_overview, out_header] | |
| for i in range(MAX_SERVICES): | |
| all_outputs += [svc_htmls[i], svc_bars[i]] | |
| btn.click(fn=run, inputs=file_input, outputs=all_outputs) | |
| if __name__ == "__main__": | |
| demo.launch() | |
| def is_excluded(s): | |
| p = service_prefix(s) | |
| if any(p == ex for ex in EXCLUDE_PREFIXES): | |
| return True | |
| # حذف انگلیسی: اگر اکثر کاراکترها ASCII باشند | |
| if p and all(ord(c) < 128 or c == ' ' for c in p if c.strip()): | |
| return True | |
| # حذف عربی خالص: حروف مختص عربی (نه فارسی) | |
| arabic_only = set('ثذضظغؤئءةى') | |
| if p and any(c in arabic_only for c in p): | |
| return True | |
| return False | |
| def fa_to_en(s): | |
| """تبدیل ارقام فارسی/عربی به انگلیسی""" | |
| mapping = str.maketrans('۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩', '01234567890123456789') | |
| return s.translate(mapping) | |
| def parse_month_year(df): | |
| """استخراج ماه و سال از ستون تاریخ انتشار""" | |
| col = 'تاریخ انتشار' | |
| if col not in df.columns: | |
| return '', '' | |
| dates = df[col].dropna().astype(str) | |
| if dates.empty: | |
| return '', '' | |
| sample = fa_to_en(dates.iloc[0]) | |
| parts = sample.replace('،', '/').split('/') | |
| if len(parts) >= 2: | |
| year = parts[0].strip() | |
| month_num = parts[1].strip().zfill(2) | |
| month_name = MONTH_NAMES.get(month_num, month_num) | |
| return parts[0].strip(), month_name | |
| return '', '' | |
| def load_and_filter(file_bytes): | |
| import io | |
| df = pd.read_excel(io.BytesIO(file_bytes), sheet_name=0) | |
| df['_excluded'] = df['سرویس'].apply(is_excluded) | |
| df_main = df[~df['_excluded']].copy() | |
| df_main['_has_source'] = df_main['منبع'].notna() & (df_main['منبع'].astype(str).str.strip() != '') | |
| df_main['_non_received'] = df_main['_has_source'] & (df_main['نوع خبر'].astype(str).str.strip() != 'دریافتی') | |
| df_main['_service_prefix'] = df_main['سرویس'].apply(service_prefix) | |
| return df, df_main | |
| # ───────────────────────────────────────────── | |
| # HTML helpers | |
| # ───────────────────────────────────────────── | |
| TH_STYLE = f"padding:12px 16px;border:1px solid {COLORS['accent']};text-align:right;color:white;font-weight:bold;font-size:16px;background:{COLORS['accent']};" | |
| TD_STYLE = f"padding:11px 15px;border:1px solid {COLORS['border']};text-align:right;color:{COLORS['text']};font-size:15px;" | |
| def stat_card(value, label, bg, color, border_color, sub=''): | |
| sub_html = f"<div style='font-size:12px;color:{COLORS['subtext']};margin-top:4px;'>{sub}</div>" if sub else '' | |
| return f""" | |
| <div style='flex:1;min-width:150px;background:{bg};border-radius:12px; | |
| padding:18px 14px;text-align:center;border-top:5px solid {border_color}; | |
| box-shadow:0 2px 8px rgba(0,0,0,0.08);'> | |
| <div style='font-size:30px;font-weight:bold;color:{color};'>{value}</div> | |
| <div style='font-size:14px;color:{COLORS["subtext"]};margin-top:6px;font-weight:600;'>{label}</div> | |
| {sub_html} | |
| </div>""" | |
| def section_title(text, icon=''): | |
| return f""" | |
| <h3 style='color:{COLORS["primary"]};margin:32px 0 14px 0;font-size:19px; | |
| border-right:5px solid {COLORS["accent"]};padding-right:12px; | |
| display:flex;align-items:center;gap:6px;'> | |
| {icon} {text} | |
| </h3>""" | |
| def make_table(rows_html, headers): | |
| ths = ''.join(f"<th style='{TH_STYLE}'>{h}</th>" for h in headers) | |
| return f""" | |
| <div style='overflow-x:auto;margin:10px 0 28px 0;border-radius:8px; | |
| box-shadow:0 1px 6px rgba(0,0,0,0.1);'> | |
| <table style='width:100%;border-collapse:collapse;font-size:15px;'> | |
| <thead><tr>{ths}</tr></thead> | |
| <tbody>{rows_html}</tbody> | |
| </table></div>""" | |
| def table_row(cells, even=True): | |
| bg = COLORS['row_even'] if even else COLORS['row_odd'] | |
| tds = ''.join(f"<td style='{TD_STYLE}background:{bg};'>{c}</td>" for c in cells) | |
| return f"<tr>{tds}</tr>" | |
| # ───────────────────────────────────────────── | |
| # نمودار میلهای ناشران | |
| # ───────────────────────────────────────────── | |
| def make_publisher_chart(df_svc, title=''): | |
| nr = df_svc[df_svc['_non_received']] | |
| if nr.empty: | |
| return None | |
| counts = nr['ناشر'].value_counts().head(12) | |
| labels = [str(l) for l in counts.index][::-1] | |
| vals = list(counts.values)[::-1] | |
| fig = go.Figure(go.Bar( | |
| y=labels, x=vals, orientation='h', | |
| marker=dict( | |
| color=vals, | |
| colorscale=[[0, '#90caf9'], [0.5, '#1565c0'], [1, '#0d47a1']], | |
| showscale=False, | |
| line=dict(width=0) | |
| ), | |
| text=vals, textposition='outside', | |
| textfont=dict(size=14, color='#1a1a1a'), | |
| hovertemplate='<b>%{y}</b>: %{x} خبر<extra></extra>' | |
| )) | |
| fig.update_layout( | |
| title=dict( | |
| text=f'ناشران خبرهای با منبع غیردریافتی — {title}', | |
| font=dict(size=15, family='Tahoma', color=COLORS['primary']), | |
| x=0.5, xanchor='center' | |
| ), | |
| font=dict(family='Tahoma', size=14, color='#1a1a1a'), | |
| height=max(300, len(labels) * 42 + 100), | |
| plot_bgcolor='rgba(232,234,246,0.3)', | |
| paper_bgcolor='white', | |
| xaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#1a1a1a')), | |
| yaxis=dict(tickfont=dict(color='#1a1a1a', size=13)), | |
| margin=dict(l=10, r=80, t=60, b=40) | |
| ) | |
| return fig | |
| # ───────────────────────────────────────────── | |
| # بخش آمار کلی | |
| # ───────────────────────────────────────────── | |
| def build_overview_html(df_main, year, month): | |
| total = len(df_main) | |
| with_src = df_main['_has_source'].sum() | |
| non_recv = df_main['_non_received'].sum() | |
| pct_src = pct(with_src, total) | |
| pct_nr_src = pct(non_recv, with_src) | |
| # سرویس با بیشترین و کمترین خبر | |
| svc_counts = df_main.groupby('_service_prefix').size() | |
| max_svc = svc_counts.idxmax() if not svc_counts.empty else '—' | |
| min_svc = svc_counts.idxmin() if not svc_counts.empty else '—' | |
| max_cnt = svc_counts.max() if not svc_counts.empty else 0 | |
| min_cnt = svc_counts.min() if not svc_counts.empty else 0 | |
| # سرویس با بیشترین خبر غیردریافتی | |
| nr_counts = df_main[df_main['_non_received']].groupby('_service_prefix').size() | |
| top_nr_svc = nr_counts.idxmax() if not nr_counts.empty else '—' | |
| top_nr_cnt = nr_counts.max() if not nr_counts.empty else 0 | |
| # پرتکرارترین ناشر (خبرهای غیردریافتی) | |
| pub_counts = df_main[df_main['_non_received']]['ناشر'].value_counts() | |
| top_pub = pub_counts.index[0] if not pub_counts.empty else '—' | |
| top_pub_cnt = pub_counts.iloc[0] if not pub_counts.empty else 0 | |
| excluded_names = ' ، '.join(EXCLUDE_LABELS.values()) | |
| html = f""" | |
| <div style='direction:rtl;font-family:Tahoma,Arial;padding:28px 24px; | |
| background:white;color:{COLORS["text"]};line-height:1.9;'> | |
| <!-- عنوان --> | |
| <div style='text-align:center;background:linear-gradient(135deg,{COLORS["primary"]},{COLORS["accent"]}); | |
| border-radius:14px;padding:28px 20px;margin-bottom:28px; | |
| box-shadow:0 4px 16px rgba(21,101,192,0.25);'> | |
| <h1 style='color:white;font-size:24px;margin:0 0 8px 0;font-weight:bold;'> | |
| نگاهی به آمار خبرهای دریافتی دارای منبع | |
| </h1> | |
| <p style='color:rgba(255,255,255,0.85);font-size:16px;margin:0;'> | |
| {month} {year} | خبرگزاری دانشجویان ایران (ایسنا) | |
| </p> | |
| </div> | |
| <!-- توضیح موارد حذفشده --> | |
| <div style='background:#fff3e0;border-radius:10px;padding:14px 18px; | |
| margin-bottom:24px;border-right:5px solid {COLORS["amber"]}; | |
| font-size:15px;color:#1a1a1a;'> | |
| <b style='color:#7f4000;'>⚠ موارد خارج از بررسی:</b> | |
| سرویسهای <b style='color:#1a1a1a;'>{excluded_names}</b> از تمام آمارها حذف شدهاند. | |
| </div> | |
| {section_title('آمار کلی', '📊')} | |
| <div style='display:flex;flex-wrap:wrap;gap:14px;margin-bottom:24px;'> | |
| {stat_card(fmt(total), 'کل خبرهای منتشرشده', COLORS['bg_blue'], COLORS['primary'], COLORS['accent'])} | |
| {stat_card(fmt(with_src), 'خبرهای دارای منبع', COLORS['bg_green'], COLORS['green'], COLORS['green'], pct_src + ' از کل')} | |
| {stat_card(fmt(non_recv), 'دارای منبع / غیردریافتی', COLORS['bg_amber'], COLORS['amber'], COLORS['amber'], pct_nr_src + ' از دارای منبع')} | |
| </div> | |
| <!-- نکات کلیدی --> | |
| {section_title('نکات کلیدی', '🔍')} | |
| <div style='border-radius:10px;overflow:hidden;margin-bottom:28px;'> | |
| <div style='background:#1a237e;padding:14px 20px;display:flex;justify-content:space-between;align-items:center;'> | |
| <span style='color:white;font-size:15px;font-weight:bold;'>📌 پُرخبرترین سرویس</span> | |
| <span style='color:#fff176;font-size:17px;font-weight:bold;'>{max_svc} | {fmt(max_cnt)} خبر</span> | |
| </div> | |
| <div style='background:#1a237e;padding:14px 20px;display:flex;justify-content:space-between;align-items:center;'> | |
| <span style='color:white;font-size:15px;font-weight:bold;'>📌 بیشترین خبر غیردریافتی</span> | |
| <span style='color:#ce93d8;font-size:17px;font-weight:bold;'>{top_nr_svc} | {fmt(top_nr_cnt)} مورد</span> | |
| </div> | |
| <div style='background:#283593;padding:14px 20px;display:flex;justify-content:space-between;align-items:center;'> | |
| <span style='color:white;font-size:15px;font-weight:bold;'>📌 ناشری که بیشترین میزان خبرهای با منبع با نوع غیردریافتی ارسال کرده</span> | |
| <span style='color:#ffcc80;font-size:17px;font-weight:bold;'>{top_pub} | {fmt(top_pub_cnt)} خبر</span> | |
| </div> | |
| </div> | |
| </div>""" | |
| return html | |
| # ───────────────────────────────────────────── | |
| # بخش هر سرویس — آمار + جدول HTML | |
| # ───────────────────────────────────────────── | |
| def build_service_html(svc_name, df_svc, year='', month=''): | |
| total = len(df_svc) | |
| with_src = df_svc['_has_source'].sum() | |
| non_recv = df_svc['_non_received'].sum() | |
| pct_src = pct(with_src, total) | |
| pct_nr = pct(non_recv, with_src) | |
| nr_df = df_svc[df_svc['_non_received']][['تیتر', 'نوع خبر', 'منبع', 'ناشر']].copy() | |
| if nr_df.empty: | |
| table_html = f"<p style='color:#1a1a1a;font-size:15px;padding:10px 0;'>خبری با منبع غیردریافتی وجود ندارد.</p>" | |
| else: | |
| rows_html = '' | |
| for i, (_, row) in enumerate(nr_df.iterrows()): | |
| bg = COLORS['row_even'] if i % 2 == 0 else COLORS['row_odd'] | |
| type_val = str(row.get('نوع خبر', '—')) | |
| cells = [ | |
| f"<td style='{TD_STYLE}background:{bg};'>{str(row.get('تیتر','—'))}</td>", | |
| f"<td style='{TD_STYLE}background:{bg};'><span style='background:#e3f2fd;color:#1a1a1a;padding:3px 8px;border-radius:5px;font-size:14px;font-weight:bold;'>{type_val}</span></td>", | |
| f"<td style='{TD_STYLE}background:{bg};'>{str(row.get('منبع','—'))}</td>", | |
| f"<td style='{TD_STYLE}background:{bg};'><b style='color:{COLORS['accent']};'>{str(row.get('ناشر','—'))}</b></td>", | |
| ] | |
| rows_html += f"<tr>{''.join(cells)}</tr>" | |
| table_html = make_table(rows_html, ['تیتر', 'نوع خبر', 'منبع', 'ناشر']) | |
| html = f""" | |
| <div style='direction:rtl;font-family:Tahoma,Arial;padding:22px 20px; | |
| background:white;color:{COLORS["text"]};border-radius:12px; | |
| box-shadow:0 2px 10px rgba(0,0,0,0.07);margin-bottom:8px;line-height:1.8;'> | |
| <div style='background:linear-gradient(90deg,{COLORS["accent"]},{COLORS["primary"]}); | |
| border-radius:10px;padding:14px 20px;margin-bottom:20px; | |
| display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;'> | |
| <h2 style='color:white;margin:0;font-size:20px;'>📂 {svc_name}</h2> | |
| <span style='color:rgba(255,255,255,0.85);font-size:14px;'> | |
| نگاهی به آمار خبرهای دریافتی دارای منبع | {month} {year} | |
| </span> | |
| </div> | |
| <div style='display:flex;flex-wrap:wrap;gap:12px;margin-bottom:16px;'> | |
| {stat_card(fmt(total), 'کل خبرهای منتشرشده', COLORS['bg_blue'], COLORS['primary'], COLORS['accent'])} | |
| {stat_card(fmt(with_src), 'دارای منبع', COLORS['bg_green'], COLORS['green'], COLORS['green'], pct_src + ' از کل')} | |
| {stat_card(fmt(non_recv), 'دارای منبع / غیردریافتی', COLORS['bg_amber'], COLORS['amber'], COLORS['amber'], pct_nr + ' از دارای منبع')} | |
| </div> | |
| {section_title(f'خبرهای با منبع غیردریافتی ({fmt(non_recv)} مورد)', '📋')} | |
| {table_html} | |
| </div>""" | |
| return html | |
| # ───────────────────────────────────────────── | |
| # تابع اصلی | |
| # ───────────────────────────────────────────── | |
| def process(file_bytes): | |
| if file_bytes is None: | |
| return "<p style='direction:rtl;font-family:Tahoma;color:#b71c1c;padding:20px;'>لطفاً فایل اکسل را انتخاب کنید.</p>", [] | |
| try: | |
| df_raw, df_main = load_and_filter(file_bytes) | |
| year, month = parse_month_year(df_main) | |
| overview_html = build_overview_html(df_main, year, month) | |
| prefixes_ordered = list(dict.fromkeys( | |
| df_main['_service_prefix'].dropna().tolist() | |
| )) | |
| # هر سرویس: html آماری+جدول + نمودار میلهای | |
| service_blocks = [] | |
| for prefix in prefixes_ordered: | |
| if not prefix: | |
| continue | |
| df_svc = df_main[df_main['_service_prefix'] == prefix] | |
| svc_html = build_service_html(prefix, df_svc, year, month) | |
| bar_fig = make_publisher_chart(df_svc, prefix) | |
| service_blocks.append((svc_html, bar_fig)) | |
| sections_header = f""" | |
| <div style='direction:rtl;font-family:Tahoma,Arial;padding:0 24px 4px 24px;background:white;'> | |
| <h2 style='color:{COLORS["primary"]};font-size:21px;border-bottom:3px solid {COLORS["accent"]}; | |
| padding-bottom:10px;margin-bottom:20px;'> | |
| 📁 آمار تفکیکی سرویسها | |
| </h2> | |
| </div>""" | |
| return overview_html, sections_header, service_blocks | |
| except Exception as e: | |
| import traceback | |
| err = f"""<div style='direction:rtl;font-family:Tahoma;padding:20px;color:#b71c1c;'> | |
| <h3>خطا در پردازش فایل</h3> | |
| <pre style='font-size:12px;color:#424242;background:#f5f5f5;padding:12px;border-radius:6px;'> | |
| {traceback.format_exc()}</pre></div>""" | |
| return err, '', [] | |
| # ───────────────────────────────────────────── | |
| # رابط کاربری Gradio | |
| # ───────────────────────────────────────────── | |
| MAX_SERVICES = 20 | |
| def run(file_bytes): | |
| overview_html, header_html, service_blocks = process(file_bytes) | |
| # خروجی: overview + header + برای هر سرویس: html + bar_fig | |
| outputs = [overview_html, header_html] | |
| for i in range(MAX_SERVICES): | |
| if i < len(service_blocks): | |
| svc_html, bar_fig = service_blocks[i] | |
| outputs.append(svc_html) | |
| outputs.append(bar_fig if bar_fig is not None else go.Figure()) | |
| else: | |
| outputs.append("") | |
| outputs.append(go.Figure()) | |
| return outputs | |
| custom_css = """ | |
| .gradio-container { | |
| direction: rtl; | |
| background: linear-gradient(135deg, #e8eaf6 0%, #e0f2f1 100%); | |
| min-height: 100vh; | |
| font-family: Tahoma, Arial, sans-serif; | |
| } | |
| footer { display: none !important; } | |
| """ | |
| with gr.Blocks(theme=gr.themes.Soft(), css=custom_css, title="داشبورد آمار خبرهای ایسنا") as demo: | |
| gr.HTML(f""" | |
| <div style='text-align:center;direction:rtl;font-family:Tahoma;padding:22px 20px; | |
| background:rgba(255,255,255,0.95);border-radius:14px;margin-bottom:14px; | |
| box-shadow:0 2px 12px rgba(21,101,192,0.12);'> | |
| <h1 style='color:{COLORS["primary"]};margin:0 0 8px 0;font-size:26px;font-weight:bold;'> | |
| داشبورد آمار خبرهای دریافتی دارای منبع | |
| </h1> | |
| <p style='color:#1a1a1a;font-size:15px;margin:0;'> | |
| فایل اکسل ماهانه سرویسها را آپلود کنید | |
| </p> | |
| <hr style='border:2px solid {COLORS["accent"]};width:30%;margin:14px auto 0;'> | |
| </div> | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| file_input = gr.File( | |
| label="📂 آپلود فایل اکسل", | |
| file_types=[".xlsx", ".xls"], | |
| type="binary" | |
| ) | |
| btn = gr.Button("🔍 شروع تحلیل", variant="primary", size="lg") | |
| out_overview = gr.HTML() | |
| out_header = gr.HTML() | |
| # هر سرویس: html + نمودار میلهای | |
| svc_htmls = [] | |
| svc_bars = [] | |
| for _ in range(MAX_SERVICES): | |
| svc_htmls.append(gr.HTML()) | |
| svc_bars.append(gr.Plot()) | |
| all_outputs = [out_overview, out_header] | |
| for i in range(MAX_SERVICES): | |
| all_outputs += [svc_htmls[i], svc_bars[i]] | |
| btn.click(fn=run, inputs=file_input, outputs=all_outputs) | |
| if __name__ == "__main__": | |
| demo.launch | |