import gradio as gr import pandas as pd import numpy as np import warnings import plotly.graph_objects as go import re from collections import Counter from itertools import combinations warnings.filterwarnings('ignore') # ==================== STOP WORDS ==================== PERSIAN_STOP_WORDS = set([ 'و', 'در', 'به', 'از', 'که', 'این', 'را', 'با', 'است', 'برای', 'آن', 'یک', 'خود', 'تا', 'کرد', 'بر', 'هم', 'نیز', 'اما', 'یا', 'اگر', 'همه', 'بود', 'شد', 'می', 'هر', 'ما', 'او', 'ها', 'های', 'شده', 'کند', 'باید', 'دارد', 'داد', 'بی', 'نه', 'هیچ', 'چه', 'وی', 'آنها', 'ان', 'پس', 'چون', 'پیش', 'دو', 'سه', 'چهار', 'شود', 'کرده', 'بوده', 'داشت', 'شدن', 'کنند', 'دهد', 'گفت', 'نمی', 'خواهد', 'کنیم', 'دارند', 'شده‌اند', 'بودند', 'کردند', 'ولی', 'چنین', 'نشده', 'کنم', 'هستند', 'درباره', 'بیش', 'کم', 'بین', 'زیر', 'بالای', 'طی', 'حتی', 'مورد', 'جز', 'علیه', 'روی', 'هنوز', 'فقط', 'هم‌چنین', 'همچنین', 'البته', 'اکنون', 'دیگر', 'ایسنا', 'isna', 'isna_farsi', 'خبرگزاری', 'گزارش', 'اعلام', 'خبر', 'منتشر', 'اینکه', 'گفته', 'طبق', 'براساس', 'https', 'http', 'rt', 'co', 'amp', 't', 'the', 'of', 'in', 'a', 'to', 'is', 'and', 'for', 'on', 'that', 'are', 'was', 'it', 'with', 'he', 'she', 'they', 'we', 'i', 'you', 'at', 'this', 'by', 'an', 'be', 'from', 'or', 'but', 'not', 'has', ]) PERSIAN_LANGUAGE_WORDS = set([ 'و', 'در', 'به', 'از', 'که', 'این', 'را', 'با', 'است', 'برای', 'آن', 'یک', 'خود', 'تا', 'کرد', 'بر', 'هم', 'نیز', 'اما', 'یا', 'اگر', 'همه', 'بود', 'شد', 'می', 'هر', 'ما', 'او', 'ها', 'های', 'شود', 'کرده', 'دارد', 'گفت', 'نمی', 'خواهد', 'کنیم', 'دارند', 'ایران', 'خبر', 'گزارش', 'امروز', 'درباره', 'مردم', 'کشور' ]) ARABIC_LANGUAGE_WORDS = set([ 'و', 'في', 'من', 'على', 'إلى', 'الى', 'عن', 'أن', 'ان', 'إن', 'هذا', 'هذه', 'ذلك', 'تلك', 'الذي', 'التي', 'الذين', 'كان', 'كانت', 'يكون', 'لا', 'ما', 'مع', 'كما', 'بعد', 'قبل', 'بين', 'اليوم', 'قال', 'الله', 'الناس', 'الدولة', 'البلاد', 'خبر' ]) ENGLISH_LANGUAGE_WORDS = set([ 'the', 'of', 'in', 'a', 'to', 'is', 'and', 'for', 'on', 'that', 'are', 'was', 'it', 'with', 'he', 'she', 'they', 'we', 'i', 'you', 'at', 'this', 'by', 'an', 'be', 'from', 'or', 'but', 'not', 'has', 'have', 'as', 'will', 'can', 'about', 'news', 'today', 'people' ]) # الگوهای بازنشر خبر ایسنا ISNA_NEWS_PATTERNS = [ r'/ایسنا', r'به گزارش ایسنا', r'به نقل از ایسنا', r'منبع:\s*ایسنا', r'به گزارش خبرگزاری ایسنا', r'ایسنا نوشت', r'ایسنا:', ] ISNA_PATTERN_COMBINED = '|'.join(ISNA_NEWS_PATTERNS) # ==================== توابع کمکی ==================== def format_number(n): try: return f"{int(n):,}" except: return '۰' def parse_date_range(df): if 'روز انتشار شمسی' not in df.columns: return '—', '—' dates = sorted(df['روز انتشار شمسی'].dropna().unique()) if not dates: return '—', '—' return dates[0], dates[-1] def clean_text(text): if pd.isna(text): return '' text = str(text) text = re.sub(r'https?://\S+', '', text) text = re.sub(r'@\S+', '', text) text = re.sub(r'#', '', text) text = re.sub(r'[^\w\s\u0600-\u06FF]', ' ', text) text = re.sub(r'\d+', '', text) text = re.sub(r'\s+', ' ', text) return text.strip() def detect_text_language(text): if pd.isna(text): return 'سایر' text = re.sub(r'https?://\S+|@\S+|#', ' ', str(text).lower()) text = re.sub(r'\d+', ' ', text) text = re.sub(r'\s+', ' ', text).strip() if not text: return 'سایر' latin_count = len(re.findall(r'[A-Za-z]', text)) arabic_script_count = len(re.findall(r'[\u0600-\u06FF]', text)) useful_chars = latin_count + arabic_script_count if useful_chars < 3: return 'سایر' tokens = re.findall(r'[A-Za-z]+|[\u0600-\u06FF]+', text) english_hits = sum(1 for t in tokens if t in ENGLISH_LANGUAGE_WORDS) persian_hits = sum(1 for t in tokens if t in PERSIAN_LANGUAGE_WORDS) arabic_hits = sum(1 for t in tokens if t in ARABIC_LANGUAGE_WORDS) persian_specific = len(re.findall(r'[پچژگکی]', text)) arabic_specific = len(re.findall(r'[أإؤئءةىيىك]', text)) english_score = latin_count + english_hits * 8 persian_score = arabic_script_count + persian_specific * 6 + persian_hits * 8 arabic_score = arabic_script_count + arabic_specific * 6 + arabic_hits * 8 if arabic_script_count == 0 and latin_count == 0: return 'سایر' if latin_count >= 4 and english_score > max(persian_score, arabic_score) * 1.2: return 'انگلیسی' if arabic_script_count >= 4: if arabic_score >= persian_score + 10 and arabic_hits >= 1: return 'عربی' if persian_score >= arabic_score + 4 or persian_specific > 0 or persian_hits >= 1: return 'فارسی' return 'سایر' if latin_count >= 4: return 'انگلیسی' return 'سایر' def is_valid_word(w): """کلمه معتبر: حداقل ۳ حرف و در لیست stop words نباشد""" return len(w) >= 3 and w.lower() not in PERSIAN_STOP_WORDS def get_ngrams_adjusted(df, top_n=20, min_count=2, max_ngram=8): """ استخراج عبارات پرتکرار ۲ تا max_ngram کلمه‌ای (بدون تک‌کلمه). - عبارات بلند‌تر از اجزای کوتاه‌تر کسر می‌شوند. - حداقل طول کلمه: ۳ حرف. - تک‌کلمه‌ای‌ها نمایش داده نمی‌شوند. """ all_texts = df['متن'].apply(clean_text).tolist() # شمارش همه n-gram های ۲ تا max_ngram ngram_counters = {n: Counter() for n in range(2, max_ngram + 1)} for text in all_texts: words = [w for w in text.split() if is_valid_word(w)] for n in range(2, max_ngram + 1): for i in range(len(words) - n + 1): ngram_counters[n][' '.join(words[i:i+n])] += 1 # فیلتر: حداقل min_count بار تکرار، از بزرگ به کوچک filtered = {n: Counter({k: v for k, v in c.items() if v >= min_count}) for n, c in ngram_counters.items()} # کسر تکرار عبارات بلندتر از کوتاه‌تر (از بزرگترین شروع) for n in range(max_ngram, 2, -1): for phrase, count in filtered[n].items(): if count == 0: continue ws = phrase.split() # از همه اندازه‌های کوچکتر کسر کن for m in range(2, n): for i in range(len(ws) - m + 1): sub = ' '.join(ws[i:i+m]) if sub in filtered[m]: filtered[m][sub] = max(0, filtered[m][sub] - count) # ترکیب همه (بدون تک‌کلمه) all_phrases = Counter() for n in range(2, max_ngram + 1): all_phrases.update({k: v for k, v in filtered[n].items() if v >= min_count}) # حذف overlap: اگر دو عبارت کلمات مشترک دارند و تعداد تکرارشان نزدیک است، # فقط بلندترین را نگه دار phrases_sorted = sorted(all_phrases.items(), key=lambda x: (-x[1], -len(x[0].split()))) kept = [] for phrase, count in phrases_sorted: phrase_words = set(phrase.split()) # بررسی overlap با عبارات قبلاً نگه‌داشته‌شده dominated = False for kp, kc in kept: kp_words = set(kp.split()) overlap = len(phrase_words & kp_words) union = len(phrase_words | kp_words) # اگر بیش از ۶۰٪ کلمات مشترک و تعداد تکرار مشابه → این عبارت حذف شود if overlap / union > 0.4 and abs(count - kc) <= 2: dominated = True break if not dominated: kept.append((phrase, count)) return kept[:top_n] def get_hourly_top_words(df, hour, top_n=3): """پرتکرارترین کلمات در یک ساعت مشخص""" texts = df[df['ساعت'] == hour]['متن'].apply(clean_text) words = [] for t in texts: words += [w for w in t.split() if is_valid_word(w)] return [w for w, _ in Counter(words).most_common(top_n)] def generate_heatmap_insights(df): """تولید توضیح داینامیک برای heatmap""" df = df.copy() df['ساعت'] = df['زمان انتشار'].apply( lambda x: int(str(x).split(':')[0]) if pd.notna(x) and ':' in str(x) else None ) df = df.dropna(subset=['ساعت']) df['ساعت'] = df['ساعت'].astype(int) hourly_counts = df['ساعت'].value_counts() if hourly_counts.empty: return '' # پیک ساعتی peak_hour = int(hourly_counts.idxmax()) peak_count = int(hourly_counts.max()) peak_words = get_hourly_top_words(df, peak_hour) # سه ساعت پرتوییت top3_hours = hourly_counts.nlargest(3) bullets = [] bullets.append( f"پیک توییت در ساعت {peak_hour}:00 با {peak_count} توییت بوده؛ " f"پرتکرارترین موضوعات: {' ، '.join(peak_words) if peak_words else '—'}" ) for h, cnt in top3_hours.items(): h = int(h) if h == peak_hour: continue words = get_hourly_top_words(df, h) if words: bullets.append( f"ساعت {h}:00 ({cnt} توییت): بیشتر درباره {' ، '.join(words)} صحبت شد" ) # ساعت با کمترین فعالیت low_hour = int(hourly_counts.idxmin()) low_count = int(hourly_counts.min()) if low_count == 0: bullets.append(f"در ساعت {low_hour}:00 هیچ توییتی ثبت نشده است") else: bullets.append(f"کمترین فعالیت در ساعت {low_hour}:00 با {low_count} توییت") return bullets def classify_tweets(df): df = df.copy() df['نوع_تعامل'] = 'سایر' df.loc[ df['متن'].str.contains(ISNA_PATTERN_COMBINED, case=False, na=False, regex=True), 'نوع_تعامل' ] = 'بازنشر_خبر' df.loc[ (df['نوع_تعامل'] == 'سایر') & df['در پاسخ به کاربر'].str.contains('isna_farsi', case=False, na=False), 'نوع_تعامل' ] = 'کامنت_ایسنا' df.loc[ (df['نوع_تعامل'] == 'سایر') & df['منشن ها'].str.contains('isna_farsi', case=False, na=False), 'نوع_تعامل' ] = 'منشن_مستقل' return df # ==================== نمودارها ==================== def create_hourly_chart(df): df = df.copy() df['ساعت'] = df['زمان انتشار'].apply( lambda x: int(str(x).split(':')[0]) if pd.notna(x) and ':' in str(x) else None ) hourly = df['ساعت'].value_counts().sort_index().reset_index() hourly.columns = ['ساعت', 'تعداد'] all_hours = pd.DataFrame({'ساعت': range(24)}) hourly = all_hours.merge(hourly, on='ساعت', how='left').fillna(0) fig = go.Figure() fig.add_trace(go.Bar( x=hourly['ساعت'], y=hourly['تعداد'], marker=dict(color=hourly['تعداد'], colorscale='Blues', showscale=False, line=dict(width=0.5, color='#1565c0')), hovertemplate='ساعت %{x}: %{y} توییت' )) fig.update_layout( title={'text': 'توزیع توییت‌ها بر اساس ساعت انتشار', 'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'}, 'x': 0.5, 'xanchor': 'center'}, xaxis_title='ساعت', yaxis_title='تعداد توییت', font=dict(family='Tahoma', size=13, color='#212121'), height=370, plot_bgcolor='rgba(240,245,255,0.6)', paper_bgcolor='white', xaxis=dict(tickmode='linear', dtick=1, gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121')), yaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121')), margin=dict(l=50, r=30, t=60, b=50) ) return fig def create_hourly_words_heatmap(df, top_n_words=10): df = df.copy() df['ساعت'] = df['زمان انتشار'].apply( lambda x: int(str(x).split(':')[0]) if pd.notna(x) and ':' in str(x) else None ) df = df.dropna(subset=['ساعت']) df['ساعت'] = df['ساعت'].astype(int) top_phrases = get_ngrams_adjusted(df, top_n=top_n_words) if not top_phrases: return go.Figure() top_words = [p[0] for p in top_phrases] hours = sorted(df['ساعت'].unique()) matrix = [] for word in top_words: row = [] for h in hours: texts = df[df['ساعت'] == h]['متن'].apply(clean_text) count = sum(1 for t in texts if word in t) row.append(count) matrix.append(row) fig = go.Figure(go.Heatmap( z=matrix, x=[f'{h}:00' for h in hours], y=top_words, colorscale='Blues', hovertemplate='ساعت %{x}
عبارت: %{y}
تعداد توییت: %{z}', colorbar=dict(title='تعداد', tickfont=dict(color='#212121')) )) fig.update_layout( title={'text': 'در هر ساعت بیشتر از چه صحبت شد؟', 'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'}, 'x': 0.5, 'xanchor': 'center'}, font=dict(family='Tahoma', size=12, color='#212121'), height=420, paper_bgcolor='white', plot_bgcolor='white', xaxis=dict(tickfont=dict(color='#212121'), title='ساعت'), yaxis=dict(tickfont=dict(color='#212121', size=11)), margin=dict(l=130, r=30, t=60, b=60) ) return fig def create_words_chart(df): top_phrases = get_ngrams_adjusted(df, top_n=20) if not top_phrases: return go.Figure() labels = [p[0] for p in top_phrases][::-1] counts = [p[1] for p in top_phrases][::-1] def phrase_color(l): n = len(l.split()) if n == 2: return '#00897b' elif n == 3: return '#6a1b9a' elif n == 4: return '#c62828' else: return '#e65100' # ۵ کلمه و بیشتر colors = [phrase_color(l) for l in labels] fig = go.Figure() fig.add_trace(go.Bar( y=labels, x=counts, orientation='h', marker=dict(color=colors, line=dict(width=0.5, color='white')), text=counts, textposition='outside', textfont=dict(color='#212121', size=14), hovertemplate='%{y}: %{x} بار', showlegend=False )) # legend جداگانه با scatter (بدون trace اضافه روی نمودار) for color, label in [('#00897b', 'دوکلمه‌ای'), ('#6a1b9a', 'سه‌کلمه‌ای'), ('#c62828', 'چهارکلمه‌ای'), ('#e65100', '۵+ کلمه')]: fig.add_trace(go.Scatter( x=[None], y=[None], mode='markers', marker=dict(size=12, color=color, symbol='square'), name=label, showlegend=True )) fig.update_layout( title={'text': 'پرتکرارترین عبارات در توییت‌ها', 'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'}, 'x': 0.5, 'xanchor': 'center'}, xaxis_title='تعداد تکرار', font=dict(family='Tahoma', size=16, color='#212121'), height=580, plot_bgcolor='rgba(240,245,255,0.6)', paper_bgcolor='white', xaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121')), yaxis=dict(gridcolor='rgba(150,150,150,0.2)', tickfont=dict(color='#212121', size=14)), legend=dict(orientation='h', yanchor='bottom', y=1.01, xanchor='center', x=0.5, font=dict(color='#212121')), margin=dict(l=200, r=80, t=80, b=50) ) return fig def create_content_type_chart(df): content_counts = df['نوع محتوا'].value_counts() labels_map = {'text': 'متن', 'photo': 'عکس', 'video': 'ویدئو'} labels = [labels_map.get(l, l) for l in content_counts.index] fig = go.Figure(go.Pie( labels=labels, values=content_counts.values, hole=0.45, marker=dict(colors=['#1565c0', '#2e7d32', '#e65100'], line=dict(color='white', width=2)), textinfo='label+percent', textfont=dict(size=14, family='Tahoma', color='#212121'), hovertemplate='%{label}: %{value} توییت (%{percent})' )) fig.update_layout( title={'text': 'توزیع نوع محتوای توییت‌ها', 'font': {'size': 16, 'family': 'Tahoma', 'color': '#1a237e'}, 'x': 0.5, 'xanchor': 'center'}, font=dict(family='Tahoma', size=13, color='#212121'), height=360, paper_bgcolor='white', margin=dict(l=20, r=20, t=60, b=20), legend=dict(font=dict(family='Tahoma', size=13, color='#212121')) ) return fig # ==================== تابع اصلی ==================== def process_twitter_data(file): try: import io try: df = pd.read_excel(io.BytesIO(file) if isinstance(file, bytes) else file) except Exception: df = pd.read_excel(io.BytesIO(file) if isinstance(file, bytes) else file, engine='openpyxl') required = ['متن', 'نام کاربری', 'تعداد بازنشر', 'تعداد لایک'] missing = [c for c in required if c not in df.columns] if missing: err = f"
❌ ستون‌های مفقود: {', '.join(missing)}
" return err, None, None, None, None # پاکسازی df['تعداد بازنشر'] = pd.to_numeric(df['تعداد بازنشر'], errors='coerce').fillna(0) df['تعداد لایک'] = pd.to_numeric(df['تعداد لایک'], errors='coerce').fillna(0) follower_col = 'تعداد دنبال کننده\u200cها' if follower_col in df.columns: df[follower_col] = pd.to_numeric(df[follower_col], errors='coerce').fillna(0) df['تعامل_کل'] = df['تعداد بازنشر'] + df['تعداد لایک'] # تفکیک نوع تعامل df = classify_tweets(df) count_news_share = (df['نوع_تعامل'] == 'بازنشر_خبر').sum() count_comment = (df['نوع_تعامل'] == 'کامنت_ایسنا').sum() count_mention = (df['نوع_تعامل'] == 'منشن_مستقل').sum() date_from, date_to = parse_date_range(df) total = len(df) total_retweet = int(df['تعداد بازنشر'].sum()) total_like = int(df['تعداد لایک'].sum()) unique_users = df['نام کاربری'].nunique() # نوع محتوا content_dist = '' if 'نوع محتوا' in df.columns: for ct, cnt in df['نوع محتوا'].value_counts().items(): label = {'text': 'متن', 'photo': 'عکس', 'video': 'ویدئو'}.get(ct, ct) pct = round(cnt / total * 100) content_dist += f"{label}: {cnt} ({pct}%)" # توزیع زبان متن توییت‌ها language_counts = df['متن'].apply(detect_text_language).value_counts() language_dist = '' for lang in ['فارسی', 'انگلیسی', 'عربی', 'سایر']: cnt = int(language_counts.get(lang, 0)) pct = round(cnt / total * 100, 1) if total else 0 language_dist += f"{lang}: {format_number(cnt)} ({pct}%)" # پرتعامل‌ترین توییت‌ها top_tweets = df.nlargest(10, 'تعامل_کل').copy() # فعال‌ترین کاربران agg_dict = {'متن': 'count', 'تعامل_کل': 'sum'} if follower_col in df.columns: agg_dict[follower_col] = 'max' user_agg = df.groupby('نام کاربری').agg(agg_dict).reset_index() user_agg.columns = ['نام کاربری', 'تعداد_توییت', 'تعامل_کل'] + ([follower_col] if follower_col in df.columns else []) sort_cols = ['تعداد_توییت', follower_col] if follower_col in df.columns else ['تعداد_توییت'] user_agg = user_agg.sort_values(sort_cols, ascending=False) # بازنشردهندگان خبر ایسنا df_news = df[df['نوع_تعامل'] == 'بازنشر_خبر'] news_sharers = pd.DataFrame() if follower_col in df.columns and len(df_news) > 0: ns = df_news.groupby('نام کاربری').agg( تعداد_توییت=('متن', 'count'), فالوور=(follower_col, 'max'), بازنشر_کل=('تعداد بازنشر', 'sum') ).reset_index().sort_values('فالوور', ascending=False).head(10) news_sharers = ns # توییت‌های ایسنا با بیشترین کامنت df_comments = df[df['نوع_تعامل'] == 'کامنت_ایسنا'].copy() isna_tweet_comments = pd.DataFrame() if 'در پاسخ به این پیام' in df_comments.columns and len(df_comments) > 0: cc = df_comments.groupby('در پاسخ به این پیام').size().reset_index() cc.columns = ['تیتر_توییت_ایسنا', 'تعداد_کامنت'] isna_tweet_comments = cc.sort_values('تعداد_کامنت', ascending=False).head(8) # توضیح داینامیک heatmap heatmap_bullets = [] if 'زمان انتشار' in df.columns: heatmap_bullets = generate_heatmap_insights(df) # ==================== ساخت HTML ==================== C = "#212121" # رنگ متن اصلی - تقریباً مشکی CS = "#37474f" # رنگ متن ثانوی TD = f"style='padding:10px 14px; border:1px solid #cfd8dc; text-align:right; color:{C}; font-size:15px;'" TH = f"style='padding:11px 14px; border:1px solid #1565c0; text-align:right; color:white; font-weight:bold; font-size:16px;'" html = f"""

گزارش تحلیل توییتر ایسنا

بازه زمانی: {date_from} تا {date_to}

تدوین: فاطمه نظرمحمدی  |  بازبینی: مهناز محمدی‌زادگان
اداره نظارت و ارزیابی، خبرگزاری دانشجویان ایران (ایسنا)


آمار کلی

{format_number(total)}
کل توییت‌ها
{format_number(total_retweet)}
مجموع بازنشر
{format_number(total_like)}
مجموع لایک
{format_number(unique_users)}
کاربران یکتا
توزیع زبان متن توییت‌ها: {language_dist}
{"
نوع محتوا: " + content_dist + "
" if content_dist else ""}

نوع تعامل با ایسنا

{format_number(count_news_share)}
بازنشر خبر ایسنا
محتوا با منبع ایسنا
{format_number(count_comment)}
کامنت به توییت ایسنا
ریپلای مستقیم
{format_number(count_mention)}
تگ مستقل ایسنا
منشن بدون ریپلای

پرتعامل‌ترین توییت‌ها

{"" if follower_col in df.columns else ""} {"" if 'روز انتشار شمسی' in df.columns else ""} """ for i, (_, row) in enumerate(top_tweets.iterrows()): bg = '#e3f2fd' if i % 2 == 0 else '#f9f9f9' username = row.get('نام کاربری', '—') text_raw = str(row.get('متن', '')) text_display = text_raw.replace('\n', ' ') rt = format_number(row.get('تعداد بازنشر', 0)) lk = format_number(row.get('تعداد لایک', 0)) f_cell = f"" if follower_col in df.columns else "" d_cell = f"" if 'روز انتشار شمسی' in df.columns else "" html += f""" {f_cell}{d_cell} """ html += "
کاربر متن توییت بازنشر لایکفالوورتاریخ
{format_number(row[follower_col])}{row['روز انتشار شمسی']}
@{username} {text_display} {rt} {lk}
" # ===== فعال‌ترین کاربران ===== html += f"""

فعال‌ترین کاربران

سورت بر اساس تعداد توییت و فالوور

{"" if follower_col in df.columns else ""} """ for i, (_, row) in enumerate(user_agg.head(10).iterrows()): bg = '#e8f5e9' if i % 2 == 0 else '#f9f9f9' f_cell = f"" if follower_col in df.columns else "" html += f""" {f_cell} """ html += "
کاربر تعداد توییتفالوورلایک+بازنشر
{format_number(row.get(follower_col, 0))}
@{row['نام کاربری']} {row['تعداد_توییت']}{format_number(row['تعامل_کل'])}
" # ===== بازنشردهندگان خبر ایسنا ===== if not news_sharers.empty: html += f"""

صفحات مهم بازنشردهنده خبر ایسنا

سورت بر اساس تعداد دنبال‌کننده (دامنه انتشار)

""" for i, (_, row) in enumerate(news_sharers.iterrows()): bg = '#fff8e1' if i % 2 == 0 else '#f9f9f9' html += f""" """ html += "
کاربر فالوور تعداد توییت با منبع ایسنا بازنشر کل
@{row['نام کاربری']} {format_number(row['فالوور'])} {row['تعداد_توییت']} {format_number(row['بازنشر_کل'])}
" # ===== توییت‌های ایسنا با بیشترین کامنت ===== if not isna_tweet_comments.empty: html += f"""

توییت‌های ایسنا با بیشترین واکنش (کامنت)

""" for i, (_, row) in enumerate(isna_tweet_comments.iterrows()): bg = '#fce4ec' if i % 2 == 0 else '#f9f9f9' html += f""" """ html += "
تیتر توییت ایسنا تعداد کامنت
{row['تیتر_توییت_ایسنا']} {row['تعداد_کامنت']}
" # ===== توضیح heatmap ===== if heatmap_bullets: bullets_html = ''.join( f"
  • {b}
  • " for b in heatmap_bullets ) html += f"""

    نکات کلیدی نمودار موضوع به تفکیک ساعت:

    """ html += "
    " # ==================== نمودارها ==================== chart_hourly = create_hourly_chart(df) if 'زمان انتشار' in df.columns else go.Figure() chart_heatmap = create_hourly_words_heatmap(df) if 'زمان انتشار' in df.columns else go.Figure() chart_content = create_content_type_chart(df) if 'نوع محتوا' in df.columns else go.Figure() chart_words = create_words_chart(df) if 'متن' in df.columns else go.Figure() return html, chart_hourly, chart_heatmap, chart_content, chart_words except Exception as e: import traceback err = f"""

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

    {str(e)}

    {traceback.format_exc()}
    """ return err, None, None, None, None # ==================== رابط کاربری ==================== custom_css = """ .gradio-container { direction: rtl; background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%); min-height: 100vh; } """ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo: gr.HTML("""

    دستیار هوشمند تحلیل توییتر ایسنا

    فایل اکسل توییتر را آپلود کنید تا گزارش کامل دریافت نمایید


    """) with gr.Row(): with gr.Column(): input_file = gr.File(label="آپلود فایل اکسل توییتر", file_types=[".xlsx", ".xls"], type="binary") submit_btn = gr.Button("شروع تحلیل", variant="primary", size="lg") with gr.Row(): with gr.Column(): output_html = gr.HTML(label="گزارش") with gr.Row(): with gr.Column(): chart_hourly = gr.Plot(label="توزیع ساعتی") with gr.Column(): chart_content = gr.Plot(label="نوع محتوا") with gr.Row(): with gr.Column(): chart_words = gr.Plot(label="پرتکرارترین عبارات") with gr.Row(): with gr.Column(): chart_heatmap = gr.Plot(label="موضوع به تفکیک ساعت") gr.Markdown("""

    فایل باید شامل ستون‌های «متن»، «نام کاربری»، «تعداد بازنشر» و «تعداد لایک» باشد

    سامانه هوشمند ایسنا | تحلیل توییتر | نسخه ۲.۱

    """) submit_btn.click( fn=process_twitter_data, inputs=input_file, outputs=[output_html, chart_hourly, chart_heatmap, chart_content, chart_words] ) if __name__ == "__main__": demo.launch()