KIMOSSINO commited on
Commit
b54a3b2
·
verified ·
1 Parent(s): 2f2cd58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -132
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
- def extract_titles_and_hashtags(file):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- # تحليل HTML باستخدام BeautifulSoup
20
- soup = BeautifulSoup(content, 'html.parser')
21
 
22
- # استخراج البيانات
23
- data = []
24
- hashtags_counter = Counter()
25
 
26
- # العثور على الحاويات التي تحتوي على البيانات
27
- # محاولة العثور على الحاويات بطرق مختلفة
28
- desc_containers = soup.find_all('div', class_=lambda x: x and 'DivDesContainer' in x)
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
- if isinstance(df_titles, str): # في حالة وجود رسالة خطأ
70
- return df_titles, None
71
 
72
- if df_titles is None or df_hashtags is None:
73
- return "لم يتم استخراج أي بيانات.", None
74
 
75
- # عرض النتائج
76
- titles_html = df_titles.to_html(index=False) if not df_titles.empty else "لا توجد عناوين مستخرجة."
77
- hashtags_html = df_hashtags.to_html(index=False) if not df_hashtags.empty else "لا توجد هاشتاغات مستخرجة."
 
 
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"خطأ غير متوقع: {str(e)}", None
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"Title: {row['Title']}\nHashtags: {row['Hashtags']}\n")
102
  doc.add_heading("الهاشتاغات وتكرارها", level=1)
103
  for _, row in df_hashtags.iterrows():
104
- doc.add_paragraph(f"{row['Hashtag']}: {row['Count']}")
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"Title: {row['Title']}\nHashtags: {row['Hashtags']}\n\n"
114
  content += "الهاشتاغات وتكرارها:\n"
115
  for _, row in df_hashtags.iterrows():
116
- content += f"{row['Hashtag']}: {row['Count']}\n"
117
  buffer.write(content.encode('utf-8'))
118
- buffer.seek(0)
119
- return buffer, "titles_and_hashtags.txt"
120
 
121
- # واجهة Gradio
122
- def process_file(file):
123
- if not file:
124
- return "الرجاء رفع ملف", None, None
125
-
126
- try:
127
- df_titles, df_hashtags = extract_titles_and_hashtags(file)
128
 
129
- if isinstance(df_titles, str):
130
- return df_titles, None, None
 
131
 
132
- # إنشاء جداول HTML مع تنسيق أفضل
133
- titles_html = df_titles.to_html(
134
- index=False,
135
- classes='table table-striped table-bordered',
136
- escape=False
137
- )
138
- hashtags_html = df_hashtags.to_html(
139
- index=False,
140
- classes='table table-striped table-bordered',
141
- escape=False
142
- )
143
 
144
- return "تم استخراج البيانات بنجاح", titles_html, hashtags_html
 
 
 
 
145
 
146
- except Exception as e:
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
- interface.launch()
 
 
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()