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"
{sub}
" if sub else '' return f"""
{value}
{label}
{sub_html}
""" def section_title(text, icon=''): return f"""

{icon} {text}

""" def make_table(rows_html, headers): ths = ''.join(f"{h}" for h in headers) return f"""
{ths}{rows_html}
""" def table_row(cells, even=True): bg = COLORS['row_even'] if even else COLORS['row_odd'] tds = ''.join(f"{c}" for c in cells) return f"{tds}" # ───────────────────────────────────────────── # جدول ترکیب نوع خبر خبرنگاران (بیش از 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='%{y}: %{x} خبر' )) 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"""

دستیار نظارت بر اخبار

{period}  |  خبرگزاری دانشجویان ایران (ایسنا)

⚠ موارد خارج از بررسی: سرویس‌های {excluded_names} از تمام آمارها حذف شده‌اند.
{section_title('آمار کلی', '📊')}
{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 + ' از کل')}
{section_title('نکات کلیدی', '🔍')}
📌 پُرخبرترین سرویس {max_svc}  |  {fmt(max_cnt)} خبر
📌 بیشترین خبر غیردریافتی {top_nr_svc}  |  {fmt(top_nr_cnt)} مورد
📌 ناشری که بیشترین میزان خبرهای با منبع با نوع غیردریافتی ارسال کرده {top_pub}  |  {fmt(top_pub_cnt)} خبر
📌 خبرنگاری با بیشترین خبر دریافتی به نام خود {top_rj}  |  {fmt(top_rj_cnt)} خبر
""" 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"

خبری با منبع غیردریافتی وجود ندارد.

" 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"{str(row.get('تیتر','—'))}", f"{type_val}", f"{str(row.get('منبع','—'))}", f"{str(row.get('ناشر','—'))}", f"{str(row.get('خبرنگار','—'))}", ] rows_html += f"{''.join(cells)}" table_html = make_table(rows_html, ['تیتر', 'نوع خبر', 'منبع', 'ناشر', 'خبرنگار']) rj_df = df_svc[df_svc['_recv_with_journalist']][['تیتر', 'خبرنگار', 'ناشر']].copy() if rj_df.empty: rj_table_html = f"

خبر دریافتی ثبت‌شده به نام خبرنگار وجود ندارد.

" 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"{str(row.get('تیتر','—'))}", f"{str(row.get('خبرنگار','—'))}", f"{str(row.get('ناشر','—'))}", ] rows_html2 += f"{''.join(cells)}" rj_table_html = make_table(rows_html2, ['تیتر', 'خبرنگار', 'ناشر']) jt_table = build_journalist_type_table(df_svc) jt_html = jt_table if jt_table else "

خبرنگاری با بیش از ۱۰ خبر در این سرویس وجود ندارد.

" html = f"""

📂 {svc_name}

دستیار نظارت بر اخبار  |  {period}
{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 + ' از کل')}
{section_title(f'خبرهای با منبع غیردریافتی ({fmt(non_recv)} مورد)', '📋')} {table_html} {section_title(f'خبرهای دریافتی ثبت‌شده به نام خبرنگار ({fmt(recv_j)} مورد)', '🖊️')} {rj_table_html} {section_title('ترکیب نوع خبر خبرنگاران (بیش از ۱۰ خبر)', '📈')} {jt_html}
""" return html # ───────────────────────────────────────────── # تابع اصلی # ───────────────────────────────────────────── def process(file_bytes): if file_bytes is None: return "

لطفاً فایل اکسل را انتخاب کنید.

", [] 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"""

📁 آمار تفکیکی سرویس‌ها

""" return overview_html, sections_header, service_blocks except Exception as e: import traceback err = f"""

خطا در پردازش فایل

{traceback.format_exc()}
""" 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"""

داشبورد آمار خبرهای دریافتی دارای منبع

فایل اکسل ماهانه سرویس‌ها را آپلود کنید


""") 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"
{sub}
" if sub else '' return f"""
{value}
{label}
{sub_html}
""" def section_title(text, icon=''): return f"""

{icon} {text}

""" def make_table(rows_html, headers): ths = ''.join(f"{h}" for h in headers) return f"""
{ths}{rows_html}
""" def table_row(cells, even=True): bg = COLORS['row_even'] if even else COLORS['row_odd'] tds = ''.join(f"{c}" for c in cells) return f"{tds}" # ───────────────────────────────────────────── # نمودار میله‌ای ناشران # ───────────────────────────────────────────── 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='%{y}: %{x} خبر' )) 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"""

نگاهی به آمار خبرهای دریافتی دارای منبع

{month} {year}  |  خبرگزاری دانشجویان ایران (ایسنا)

⚠ موارد خارج از بررسی: سرویس‌های {excluded_names} از تمام آمارها حذف شده‌اند.
{section_title('آمار کلی', '📊')}
{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 + ' از دارای منبع')}
{section_title('نکات کلیدی', '🔍')}
📌 پُرخبرترین سرویس {max_svc}  |  {fmt(max_cnt)} خبر
📌 بیشترین خبر غیردریافتی {top_nr_svc}  |  {fmt(top_nr_cnt)} مورد
📌 ناشری که بیشترین میزان خبرهای با منبع با نوع غیردریافتی ارسال کرده {top_pub}  |  {fmt(top_pub_cnt)} خبر
""" 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"

خبری با منبع غیردریافتی وجود ندارد.

" 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"{str(row.get('تیتر','—'))}", f"{type_val}", f"{str(row.get('منبع','—'))}", f"{str(row.get('ناشر','—'))}", ] rows_html += f"{''.join(cells)}" table_html = make_table(rows_html, ['تیتر', 'نوع خبر', 'منبع', 'ناشر']) html = f"""

📂 {svc_name}

نگاهی به آمار خبرهای دریافتی دارای منبع  |  {month} {year}
{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 + ' از دارای منبع')}
{section_title(f'خبرهای با منبع غیردریافتی ({fmt(non_recv)} مورد)', '📋')} {table_html}
""" return html # ───────────────────────────────────────────── # تابع اصلی # ───────────────────────────────────────────── def process(file_bytes): if file_bytes is None: return "

لطفاً فایل اکسل را انتخاب کنید.

", [] 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"""

📁 آمار تفکیکی سرویس‌ها

""" return overview_html, sections_header, service_blocks except Exception as e: import traceback err = f"""

خطا در پردازش فایل

{traceback.format_exc()}
""" 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"""

داشبورد آمار خبرهای دریافتی دارای منبع

فایل اکسل ماهانه سرویس‌ها را آپلود کنید


""") 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