Update app.py
Browse files
app.py
CHANGED
|
@@ -4,175 +4,114 @@ from collections import Counter
|
|
| 4 |
from io import BytesIO
|
| 5 |
from docx import Document
|
| 6 |
import gradio as gr
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
try:
|
| 10 |
-
# قراءة محتوى الملف مع التعامل مع مختلف أنواع الإدخال
|
| 11 |
if hasattr(file, 'read'):
|
| 12 |
content = file.read().decode('utf-8') if isinstance(file.read(), bytes) else file.read()
|
| 13 |
else:
|
| 14 |
with open(file.name, 'r', encoding='utf-8') as f:
|
| 15 |
content = f.read()
|
| 16 |
-
except Exception as e:
|
| 17 |
-
return f"خطأ أثناء قراءة الملف: {str(e)}", None
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
hashtags_counter = Counter()
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
if not desc_containers:
|
| 31 |
-
desc_containers = soup.find_all('div', attrs={'aria-label': True})
|
| 32 |
-
|
| 33 |
-
if not desc_containers:
|
| 34 |
-
return "لم يتم العثور على أي بيانات مطابقة.", None
|
| 35 |
-
|
| 36 |
-
for container in desc_containers[:500]: # تحديد الحد الأقصى للعناصر
|
| 37 |
-
# استخراج العنوان من الخاصية aria-label
|
| 38 |
-
title = container.get('aria-label', 'بدون عنوان')
|
| 39 |
-
|
| 40 |
-
# استخراج الهاشتاغات بشكل أكثر مرونة
|
| 41 |
-
hashtags = []
|
| 42 |
-
for tag in container.find_all(['a', 'span']):
|
| 43 |
-
tag_text = tag.get_text(strip=True)
|
| 44 |
-
if tag_text.startswith('#'):
|
| 45 |
-
hashtags.append(tag_text)
|
| 46 |
-
|
| 47 |
-
# تحديث عداد الهاشتاغات
|
| 48 |
-
hashtags_counter.update(hashtags)
|
| 49 |
-
|
| 50 |
-
# إضافة البيانات إلى القائمة
|
| 51 |
-
data.append({
|
| 52 |
-
"العنوان": title,
|
| 53 |
-
"الهاشتاغات": ", ".join(hashtags)
|
| 54 |
-
})
|
| 55 |
-
|
| 56 |
-
# تحويل البيانات إلى DataFrame
|
| 57 |
-
df_titles = pd.DataFrame(data)
|
| 58 |
-
df_hashtags = pd.DataFrame(hashtags_counter.most_common(), columns=["الهاشتاغ", "عدد التكرار"])
|
| 59 |
-
|
| 60 |
-
return df_titles, df_hashtags
|
| 61 |
-
# تعديل على دالة Gradio للتعامل مع الأخطاء
|
| 62 |
-
def gradio_interface(file, format_choice):
|
| 63 |
-
if not file:
|
| 64 |
-
return "الرجاء رفع ملف.", None
|
| 65 |
-
|
| 66 |
-
try:
|
| 67 |
-
df_titles, df_hashtags = extract_titles_and_hashtags(file)
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
|
| 72 |
-
|
| 73 |
-
return "لم يتم استخراج أي بيانات.", None
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
|
| 80 |
-
buffer, file_name = create_downloadable_files(df_titles, df_hashtags, format_choice)
|
| 81 |
|
| 82 |
-
return titles_html + "<br><br>" + hashtags_html, (file_name, buffer)
|
| 83 |
-
|
| 84 |
except Exception as e:
|
| 85 |
-
return f"خطأ
|
| 86 |
-
|
| 87 |
def create_downloadable_files(df_titles, df_hashtags, format_choice):
|
|
|
|
|
|
|
| 88 |
if format_choice == "Excel":
|
| 89 |
-
buffer = BytesIO()
|
| 90 |
with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer:
|
| 91 |
df_titles.to_excel(writer, index=False, sheet_name='Titles')
|
| 92 |
df_hashtags.to_excel(writer, index=False, sheet_name='Hashtags')
|
| 93 |
-
buffer.seek(0)
|
| 94 |
-
return buffer, "titles_and_hashtags.xlsx"
|
| 95 |
-
|
| 96 |
elif format_choice == "Word":
|
| 97 |
-
buffer = BytesIO()
|
| 98 |
doc = Document()
|
| 99 |
doc.add_heading("العناوين والهاشتاغات", level=1)
|
| 100 |
for _, row in df_titles.iterrows():
|
| 101 |
-
doc.add_paragraph(f"
|
| 102 |
doc.add_heading("الهاشتاغات وتكرارها", level=1)
|
| 103 |
for _, row in df_hashtags.iterrows():
|
| 104 |
-
doc.add_paragraph(f"{row['
|
| 105 |
doc.save(buffer)
|
| 106 |
-
buffer.seek(0)
|
| 107 |
-
return buffer, "titles_and_hashtags.docx"
|
| 108 |
-
|
| 109 |
elif format_choice == "TXT":
|
| 110 |
-
buffer = BytesIO()
|
| 111 |
content = "العناوين والهاشتاغات:\n"
|
| 112 |
for _, row in df_titles.iterrows():
|
| 113 |
-
content += f"
|
| 114 |
content += "الهاشتاغات وتكرارها:\n"
|
| 115 |
for _, row in df_hashtags.iterrows():
|
| 116 |
-
content += f"{row['
|
| 117 |
buffer.write(content.encode('utf-8'))
|
| 118 |
-
|
| 119 |
-
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
return "الرجاء رفع ملف", None, None
|
| 125 |
-
|
| 126 |
-
try:
|
| 127 |
-
df_titles, df_hashtags = extract_titles_and_hashtags(file)
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
|
|
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
index=False,
|
| 140 |
-
classes='table table-striped table-bordered',
|
| 141 |
-
escape=False
|
| 142 |
-
)
|
| 143 |
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
-
|
| 147 |
-
return f"حدث خطأ: {str(e)}", None, None
|
| 148 |
-
|
| 149 |
-
# إنشاء واجهة Gradio
|
| 150 |
-
interface = gr.Interface(
|
| 151 |
-
fn=process_file,
|
| 152 |
-
inputs=gr.File(label="ارفع ملف HTML"),
|
| 153 |
-
outputs=[
|
| 154 |
-
gr.Textbox(label="الحالة"),
|
| 155 |
-
gr.HTML(label="العناوين"),
|
| 156 |
-
gr.HTML(label="الهاشتاغات")
|
| 157 |
-
],
|
| 158 |
-
title="مستخرج اله��شتاغات من TikTok",
|
| 159 |
-
description="قم بتحميل ملف HTML للحصول على العناوين والهاشتاغات",
|
| 160 |
-
css="""
|
| 161 |
-
.table {
|
| 162 |
-
width: 100%;
|
| 163 |
-
margin-bottom: 1rem;
|
| 164 |
-
color: #212529;
|
| 165 |
-
}
|
| 166 |
-
.table th, .table td {
|
| 167 |
-
padding: 0.75rem;
|
| 168 |
-
vertical-align: top;
|
| 169 |
-
border: 1px solid #dee2e6;
|
| 170 |
-
}
|
| 171 |
-
.table thead {
|
| 172 |
-
background-color: #f8f9fa;
|
| 173 |
-
}
|
| 174 |
-
"""
|
| 175 |
-
)
|
| 176 |
|
| 177 |
# تشغيل التطبيق
|
| 178 |
-
|
|
|
|
|
|
| 4 |
from io import BytesIO
|
| 5 |
from docx import Document
|
| 6 |
import gradio as gr
|
| 7 |
+
import re
|
| 8 |
+
|
| 9 |
+
# تصنيف الهاشتاغات
|
| 10 |
+
HASHTAG_CATEGORIES = {
|
| 11 |
+
'رياضة': ['كرة_قدم', 'رياضة', 'دوري', 'كرة_سلة', 'تنس', 'سباحة', 'كرة_يد', 'أولمبياد', 'مباراة'],
|
| 12 |
+
'موسيقى': ['موسيقى', 'غناء', 'مطرب', 'أغنية', 'فن', 'مزيكا', 'غنائي', 'كليب', 'ألبوم'],
|
| 13 |
+
'تكنولوجيا': ['تكنولوجيا', 'تقنية', 'برمجة', 'ذكاء_اصطناعي', 'تطبيقات', 'هاتف', 'كمبيوتر', 'انترنت'],
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
def classify_hashtag(hashtag):
|
| 17 |
+
"""تصنيف الهاشتاغ حسب المجال"""
|
| 18 |
+
hashtag = hashtag.lower()
|
| 19 |
+
for category, keywords in HASHTAG_CATEGORIES.items():
|
| 20 |
+
if any(keyword in hashtag for keyword in keywords):
|
| 21 |
+
return category
|
| 22 |
+
return 'أخرى'
|
| 23 |
+
|
| 24 |
+
def extract_keywords(title):
|
| 25 |
+
"""استخراج الكلمات الرئيسية من العنوان"""
|
| 26 |
+
cleaned_title = re.sub(r'[^\u0600-\u06FF\s]', '', title)
|
| 27 |
+
words = cleaned_title.split()
|
| 28 |
+
return ', '.join([word for word in words if len(word) > 2][:5])
|
| 29 |
+
|
| 30 |
+
def extract_data(file, min_frequency=1):
|
| 31 |
try:
|
|
|
|
| 32 |
if hasattr(file, 'read'):
|
| 33 |
content = file.read().decode('utf-8') if isinstance(file.read(), bytes) else file.read()
|
| 34 |
else:
|
| 35 |
with open(file.name, 'r', encoding='utf-8') as f:
|
| 36 |
content = f.read()
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
soup = BeautifulSoup(content, 'html.parser')
|
| 39 |
+
desc_containers = soup.find_all('div', class_=lambda x: x and 'DivDesContainer' in x)
|
| 40 |
|
| 41 |
+
data = []
|
| 42 |
+
hashtags_counter = Counter()
|
|
|
|
| 43 |
|
| 44 |
+
for container in desc_containers[:500]:
|
| 45 |
+
title = container.get('aria-label', 'بدون عنوان')
|
| 46 |
+
keywords = extract_keywords(title)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
hashtags = [tag.get_text(strip=True) for tag in container.find_all(['a', 'span']) if tag.get_text(strip=True).startswith('#')]
|
| 49 |
+
hashtags_counter.update(hashtags)
|
| 50 |
|
| 51 |
+
data.append({"العنوان": title, "الكلمات الرئيسية": keywords, "الهاشتاغات": ", ".join(hashtags)})
|
|
|
|
| 52 |
|
| 53 |
+
df_titles = pd.DataFrame(data)
|
| 54 |
+
df_hashtags = pd.DataFrame(
|
| 55 |
+
[(tag, count, classify_hashtag(tag)) for tag, count in hashtags_counter.items() if count >= min_frequency],
|
| 56 |
+
columns=["الهاشتاغ", "عدد التكرار", "المجال"]
|
| 57 |
+
).sort_values(by="عدد التكرار", ascending=False)
|
| 58 |
|
| 59 |
+
return df_titles, df_hashtags
|
|
|
|
| 60 |
|
|
|
|
|
|
|
| 61 |
except Exception as e:
|
| 62 |
+
return f"حدث خطأ: {str(e)}", None
|
| 63 |
+
|
| 64 |
def create_downloadable_files(df_titles, df_hashtags, format_choice):
|
| 65 |
+
buffer = BytesIO()
|
| 66 |
+
|
| 67 |
if format_choice == "Excel":
|
|
|
|
| 68 |
with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer:
|
| 69 |
df_titles.to_excel(writer, index=False, sheet_name='Titles')
|
| 70 |
df_hashtags.to_excel(writer, index=False, sheet_name='Hashtags')
|
|
|
|
|
|
|
|
|
|
| 71 |
elif format_choice == "Word":
|
|
|
|
| 72 |
doc = Document()
|
| 73 |
doc.add_heading("العناوين والهاشتاغات", level=1)
|
| 74 |
for _, row in df_titles.iterrows():
|
| 75 |
+
doc.add_paragraph(f"العنوان: {row['العنوان']}\nالكلمات الرئيسية: {row['الكلمات الرئيسية']}\nالهاشتاغات: {row['الهاشتاغات']}\n")
|
| 76 |
doc.add_heading("الهاشتاغات وتكرارها", level=1)
|
| 77 |
for _, row in df_hashtags.iterrows():
|
| 78 |
+
doc.add_paragraph(f"{row['الهاشتاغ']}: {row['عدد التكرار']} ({row['المجال']})")
|
| 79 |
doc.save(buffer)
|
|
|
|
|
|
|
|
|
|
| 80 |
elif format_choice == "TXT":
|
|
|
|
| 81 |
content = "العناوين والهاشتاغات:\n"
|
| 82 |
for _, row in df_titles.iterrows():
|
| 83 |
+
content += f"العنوان: {row['العنوان']}\nالكلمات الرئيسية: {row['الكلمات الرئيسية']}\nالهاشتاغات: {row['الهاشتاغات']}\n\n"
|
| 84 |
content += "الهاشتاغات وتكرارها:\n"
|
| 85 |
for _, row in df_hashtags.iterrows():
|
| 86 |
+
content += f"{row['الهاشتاغ']}: {row['عدد التكرار']} ({row['المجال']})\n"
|
| 87 |
buffer.write(content.encode('utf-8'))
|
| 88 |
+
buffer.seek(0)
|
| 89 |
+
return buffer, f"data.{format_choice.lower()}"
|
| 90 |
|
| 91 |
+
def gradio_interface():
|
| 92 |
+
with gr.Blocks() as demo:
|
| 93 |
+
gr.Markdown("## محلل TikTok المتقدم")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
+
with gr.Row():
|
| 96 |
+
file_input = gr.File(label="رفع ملف HTML")
|
| 97 |
+
format_choice = gr.Radio(["Excel", "Word", "TXT"], label="تنسيق الملف", value="Excel")
|
| 98 |
|
| 99 |
+
analyze_btn = gr.Button("تحليل البيانات")
|
| 100 |
+
|
| 101 |
+
with gr.Tabs():
|
| 102 |
+
with gr.TabItem("العناوين"):
|
| 103 |
+
titles_output = gr.HTML(label="العناوين")
|
| 104 |
+
with gr.TabItem("الهاشتاغات"):
|
| 105 |
+
hashtags_output = gr.HTML(label="الهاشتاغات")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
analyze_btn.click(
|
| 108 |
+
fn=lambda file, fmt: extract_data(file) + (fmt,),
|
| 109 |
+
inputs=[file_input, format_choice],
|
| 110 |
+
outputs=[titles_output, hashtags_output]
|
| 111 |
+
)
|
| 112 |
|
| 113 |
+
return demo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
# تشغيل التطبيق
|
| 116 |
+
app = gradio_interface()
|
| 117 |
+
app.launch()
|