Update app.py
Browse files
app.py
CHANGED
@@ -1,58 +1,205 @@
|
|
1 |
import gradio as gr
|
2 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
# Функция для анализа поста
|
5 |
def analyze_post(content_type, link_to_post, post_likes, post_date, description, comment_count, all_comments):
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
# Создаем интерфейс Gradio
|
36 |
iface = gr.Interface(
|
37 |
fn=analyze_post,
|
38 |
inputs=[
|
39 |
-
gr.Radio(
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
gr.
|
45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
],
|
47 |
outputs=[
|
48 |
-
gr.Textbox(label="
|
49 |
-
gr.Textbox(label="Usernames (Output 1)"),
|
50 |
-
gr.Textbox(label="Comments (Output 2)"),
|
51 |
-
gr.Textbox(label="Likes Chronology (Output 3)"),
|
52 |
-
gr.Textbox(label="Total Likes on Comments (Output 4)")
|
53 |
],
|
54 |
-
title="Instagram Comment Analyzer",
|
55 |
-
description="
|
56 |
)
|
57 |
|
58 |
-
|
|
|
|
1 |
import gradio as gr
|
2 |
import re
|
3 |
+
from collections import Counter
|
4 |
+
from datetime import datetime
|
5 |
+
import emoji
|
6 |
+
|
7 |
+
def clean_text(text):
|
8 |
+
"""Очищает текст от лишних пробелов и переносов строк"""
|
9 |
+
return ' '.join(text.split())
|
10 |
+
|
11 |
+
def count_emojis(text):
|
12 |
+
"""Подсчитывает количество эмодзи в тексте"""
|
13 |
+
return len([c for c in text if c in emoji.EMOJI_DATA])
|
14 |
+
|
15 |
+
def extract_mentions(text):
|
16 |
+
"""Извлекает упоминания пользователей из текста"""
|
17 |
+
return re.findall(r'@[\w\.]+', text)
|
18 |
+
|
19 |
+
def analyze_sentiment(text):
|
20 |
+
"""Простой анализ тональности по эмодзи и ключевым словам"""
|
21 |
+
positive_indicators = ['🔥', '❤️', '👍', 'круто', 'супер', 'класс', 'огонь', 'пушка']
|
22 |
+
negative_indicators = ['👎', '😢', 'плохо', 'ужас']
|
23 |
+
|
24 |
+
text_lower = text.lower()
|
25 |
+
positive_count = sum(1 for ind in positive_indicators if ind in text_lower)
|
26 |
+
negative_count = sum(1 for ind in negative_indicators if ind in text_lower)
|
27 |
+
|
28 |
+
if positive_count > negative_count:
|
29 |
+
return 'positive'
|
30 |
+
elif negative_count > positive_count:
|
31 |
+
return 'negative'
|
32 |
+
return 'neutral'
|
33 |
+
|
34 |
+
def extract_comment_data(comment_text):
|
35 |
+
"""
|
36 |
+
Извлекает данные из отдельного комментария
|
37 |
+
Возвращает (username, comment_text, likes_count, week_number)
|
38 |
+
"""
|
39 |
+
# Извлекаем имя пользователя
|
40 |
+
username_match = re.search(r"Фото профиля ([^\n]+)", comment_text)
|
41 |
+
if not username_match:
|
42 |
+
return None, None, 0, 0
|
43 |
+
|
44 |
+
username = username_match.group(1).strip()
|
45 |
+
|
46 |
+
# Извлекаем текст комментария (теперь без имени пользователя)
|
47 |
+
comment_pattern = fr"{username}\n(.*?)(?:\d+ нед\.)"
|
48 |
+
comment_match = re.search(comment_pattern, comment_text, re.DOTALL)
|
49 |
+
if comment_match:
|
50 |
+
# Очищаем текст комментария от упоминаний пользователя в начале
|
51 |
+
comment = clean_text(comment_match.group(1))
|
52 |
+
comment = re.sub(fr'^{username}\s*', '', comment)
|
53 |
+
comment = re.sub(r'^@[\w\.]+ ', '', comment) # Удаляем упоминания в начале
|
54 |
+
else:
|
55 |
+
comment = ""
|
56 |
+
|
57 |
+
# Извлекаем количество недель
|
58 |
+
week_match = re.search(r'(\d+) нед\.', comment_text)
|
59 |
+
weeks = int(week_match.group(1)) if week_match else 0
|
60 |
+
|
61 |
+
# Ищем количество лайков
|
62 |
+
likes = 0
|
63 |
+
likes_patterns = [
|
64 |
+
r"(\d+) отметк[аи] \"Нравится\"",
|
65 |
+
r"Нравится: (\d+)",
|
66 |
+
]
|
67 |
+
|
68 |
+
for pattern in likes_patterns:
|
69 |
+
likes_match = re.search(pattern, comment_text)
|
70 |
+
if likes_match:
|
71 |
+
likes = int(likes_match.group(1))
|
72 |
+
break
|
73 |
+
|
74 |
+
return username, comment.strip(), likes, weeks
|
75 |
|
|
|
76 |
def analyze_post(content_type, link_to_post, post_likes, post_date, description, comment_count, all_comments):
|
77 |
+
try:
|
78 |
+
# Разделяем комментарии по "Фото профиля"
|
79 |
+
comments_blocks = re.split(r'(?=Фото профиля)', all_comments)
|
80 |
+
comments_blocks = [block for block in comments_blocks if block.strip()]
|
81 |
+
|
82 |
+
# Основные списки для данных
|
83 |
+
usernames = []
|
84 |
+
comments = []
|
85 |
+
likes = []
|
86 |
+
weeks = []
|
87 |
+
|
88 |
+
# Дополнительные метрики
|
89 |
+
total_emojis = 0
|
90 |
+
mentions = []
|
91 |
+
sentiments = []
|
92 |
+
comment_lengths = []
|
93 |
+
|
94 |
+
# Обработка каждого комментария
|
95 |
+
for block in comments_blocks:
|
96 |
+
username, comment, like_count, week_number = extract_comment_data(block)
|
97 |
+
if username and comment:
|
98 |
+
usernames.append(username)
|
99 |
+
comments.append(comment)
|
100 |
+
likes.append(str(like_count))
|
101 |
+
weeks.append(week_number)
|
102 |
+
|
103 |
+
# Сбор дополнительных метрик
|
104 |
+
total_emojis += count_emojis(comment)
|
105 |
+
mentions.extend(extract_mentions(comment))
|
106 |
+
sentiments.append(analyze_sentiment(comment))
|
107 |
+
comment_lengths.append(len(comment))
|
108 |
+
|
109 |
+
# Аналитика
|
110 |
+
total_comments = len(comments)
|
111 |
+
avg_comment_length = sum(comment_lengths) / total_comments if comment_lengths else 0
|
112 |
+
sentiment_distribution = Counter(sentiments)
|
113 |
+
most_active_users = Counter(usernames).most_common(5)
|
114 |
+
most_mentioned = Counter(mentions).most_common(5)
|
115 |
+
avg_likes = sum(map(int, likes)) / len(likes) if likes else 0
|
116 |
+
earliest_week = max(weeks) if weeks else 0
|
117 |
+
latest_week = min(weeks) if weeks else 0
|
118 |
+
|
119 |
+
# Формируем выходные данные
|
120 |
+
usernames_output = "\n".join(usernames)
|
121 |
+
comments_output = "\n".join(comments)
|
122 |
+
likes_chronology_output = "\n".join(likes)
|
123 |
+
total_likes_sum = sum(map(int, likes))
|
124 |
+
|
125 |
+
# Подробная аналитика
|
126 |
+
analytics_summary = (
|
127 |
+
f"Content Type: {content_type}\n"
|
128 |
+
f"Link to Post: {link_to_post}\n\n"
|
129 |
+
f"ОСНОВНАЯ СТАТИСТИКА:\n"
|
130 |
+
f"- Всего комментариев: {total_comments}\n"
|
131 |
+
f"- Всего лайков на комментариях: {total_likes_sum}\n"
|
132 |
+
f"- Среднее количество лайков: {avg_likes:.1f}\n"
|
133 |
+
f"- Период активности: {earliest_week}-{latest_week} недель\n\n"
|
134 |
+
f"АНАЛИЗ КОНТЕНТА:\n"
|
135 |
+
f"- Средняя длина комментария: {avg_comment_length:.1f} символов\n"
|
136 |
+
f"- Всего эмодзи использовано: {total_emojis}\n"
|
137 |
+
f"- Тональность комментариев:\n"
|
138 |
+
f" * Позитивных: {sentiment_distribution['positive']}\n"
|
139 |
+
f" * Нейтральных: {sentiment_distribution['neutral']}\n"
|
140 |
+
f" * Негативных: {sentiment_distribution['negative']}\n\n"
|
141 |
+
f"АКТИВНОСТЬ ПОЛЬЗОВАТЕЛЕЙ:\n"
|
142 |
+
f"Самые активные комментаторы:\n"
|
143 |
+
+ "\n".join([f"- {user}: {count} комментариев" for user, count in most_active_users]) + "\n\n"
|
144 |
+
f"Самые упоминаемые пользователи:\n"
|
145 |
+
+ "\n".join([f"- {user}: {count} упоминаний" for user, count in most_mentioned if user]) + "\n\n"
|
146 |
+
f"ВОВЛЕЧЕННОСТЬ:\n"
|
147 |
+
f"- Процент комментариев с лайками: {(sum(1 for l in likes if int(l) > 0) / total_comments * 100):.1f}%\n"
|
148 |
+
f"- Процент комментариев с эмодзи: {(sum(1 for c in comments if count_emojis(c) > 0) / total_comments * 100):.1f}%\n"
|
149 |
+
)
|
150 |
+
|
151 |
+
return analytics_summary, usernames_output, comments_output, likes_chronology_output, str(total_likes_sum)
|
152 |
+
|
153 |
+
except Exception as e:
|
154 |
+
error_message = f"Произошла ошибка при обработке: {str(e)}\n{str(type(e))}"
|
155 |
+
return error_message, error_message, error_message, error_message, "0"
|
156 |
|
157 |
# Создаем интерфейс Gradio
|
158 |
iface = gr.Interface(
|
159 |
fn=analyze_post,
|
160 |
inputs=[
|
161 |
+
gr.Radio(
|
162 |
+
choices=["Photo", "Video"],
|
163 |
+
label="Content Type",
|
164 |
+
value="Photo"
|
165 |
+
),
|
166 |
+
gr.Textbox(
|
167 |
+
label="Link to Post",
|
168 |
+
placeholder="Введите ссылку на пост"
|
169 |
+
),
|
170 |
+
gr.Number(
|
171 |
+
label="Likes",
|
172 |
+
value=0
|
173 |
+
),
|
174 |
+
gr.Textbox(
|
175 |
+
label="Post Date",
|
176 |
+
placeholder="Введите дату публикации"
|
177 |
+
),
|
178 |
+
gr.Textbox(
|
179 |
+
label="Description",
|
180 |
+
placeholder="Введите описание поста",
|
181 |
+
lines=3
|
182 |
+
),
|
183 |
+
gr.Number(
|
184 |
+
label="Total Comment Count",
|
185 |
+
value=0
|
186 |
+
),
|
187 |
+
gr.Textbox(
|
188 |
+
label="All Comments",
|
189 |
+
placeholder="Вставьте комментарии",
|
190 |
+
lines=10
|
191 |
+
)
|
192 |
],
|
193 |
outputs=[
|
194 |
+
gr.Textbox(label="Analytics Summary", lines=20),
|
195 |
+
gr.Textbox(label="Usernames (Output 1)", lines=5),
|
196 |
+
gr.Textbox(label="Comments (Output 2)", lines=5),
|
197 |
+
gr.Textbox(label="Likes Chronology (Output 3)", lines=5),
|
198 |
+
gr.Textbox(label="Total Likes on Comments (Output 4)")
|
199 |
],
|
200 |
+
title="Instagram Comment Analyzer Pro",
|
201 |
+
description="Расширенный анализатор комментариев Instagram с детальной аналитикой"
|
202 |
)
|
203 |
|
204 |
+
if __name__ == "__main__":
|
205 |
+
iface.launch()
|