File size: 17,797 Bytes
b4bbaee
 
cbff93c
 
 
e5c8ff6
 
282dd48
978ab36
8a11e5e
cbff93c
282dd48
e5c8ff6
 
cbff93c
282dd48
 
6bdcb96
 
cbff93c
282dd48
 
 
b4bbaee
282dd48
 
 
e5c8ff6
282dd48
 
 
978ab36
e5c8ff6
282dd48
 
 
 
6bdcb96
 
 
282dd48
 
6bdcb96
 
282dd48
 
6bdcb96
 
282dd48
 
 
6bdcb96
282dd48
6bdcb96
 
 
 
282dd48
6bdcb96
8a11e5e
282dd48
8a11e5e
282dd48
 
e5c8ff6
282dd48
6bdcb96
282dd48
6bdcb96
 
 
 
 
 
282dd48
6bdcb96
 
 
 
 
282dd48
 
 
 
6bdcb96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282dd48
 
6bdcb96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282dd48
 
 
 
 
6bdcb96
282dd48
6bdcb96
282dd48
 
 
e5c8ff6
6bdcb96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282dd48
6bdcb96
 
 
 
 
 
 
282dd48
6bdcb96
 
 
8a11e5e
6bdcb96
282dd48
 
 
 
 
 
 
 
 
 
978ab36
282dd48
8a11e5e
282dd48
8a11e5e
 
 
282dd48
6bdcb96
282dd48
 
 
 
e5c8ff6
6bdcb96
282dd48
8a11e5e
282dd48
 
 
 
 
 
 
 
6bdcb96
282dd48
 
 
 
 
 
978ab36
6bdcb96
282dd48
6bdcb96
282dd48
 
 
 
 
 
8a11e5e
282dd48
6bdcb96
8a11e5e
6bdcb96
 
8a11e5e
 
282dd48
 
 
 
 
8a11e5e
 
6bdcb96
8a11e5e
 
 
 
 
282dd48
6bdcb96
 
 
 
 
 
 
 
 
 
 
 
8a11e5e
6bdcb96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282dd48
6bdcb96
978ab36
8a11e5e
 
 
 
 
 
6bdcb96
8a11e5e
 
6bdcb96
 
 
8a11e5e
6bdcb96
8a11e5e
6bdcb96
8a11e5e
 
 
978ab36
282dd48
6bdcb96
8a11e5e
 
 
 
 
 
 
 
282dd48
6bdcb96
282dd48
8a11e5e
 
 
 
 
 
6bdcb96
 
 
 
 
 
 
 
 
 
 
 
8a11e5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282dd48
 
8a11e5e
cbff93c
282dd48
 
8a11e5e
282dd48
 
 
 
 
978ab36
 
 
 
 
 
 
282dd48
 
 
978ab36
 
 
 
282dd48
978ab36
 
282dd48
b4bbaee
cbff93c
 
1
2
3
4
5
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import gradio as gr
import re
from collections import Counter
from datetime import datetime
import emoji
import logging
from typing import Tuple, List, Optional
import statistics
import csv
from io import StringIO

# Настройка логирования
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def clean_text(text):
    """Очищает текст от лишних пробелов и переносов строк"""
    text = re.sub(r'\s+', ' ', text)
    return text.strip()

def count_emojis(text):
    """Подсчитывает количество эмодзи в тексте"""
    return len([c for c in text if c in emoji.EMOJI_DATA])

def extract_mentions(text):
    """Извлекает упоминания пользователей из текста"""
    return re.findall(r'@[\w\.]+', text)

def get_comment_words(text):
    """Получает список слов из комментария для анализа"""
    words = re.findall(r'\w+', text.lower())
    return [w for w in words if len(w) > 2]

def analyze_sentiment(text):
    """Расширенный анализ тональности по эмодзи и ключевым словам"""
    positive_indicators = ['🔥', '❤️', '👍', '😊', '💪', '👏', '🎉', '♥️', '😍', '🙏',
                         'круто', 'супер', 'класс', 'огонь', 'пушка', 'отлично', 'здорово',
                         'прекрасно', 'молодец', 'красота', 'спасибо', 'топ', 'лучший',
                         'amazing', 'wonderful', 'great', 'perfect', 'love', 'beautiful']
    
    negative_indicators = ['👎', '😢', '😞', '😠', '😡', '💔', '😕', '😑', 
                         'плохо', 'ужас', 'отстой', 'фу', 'жесть', 'ужасно',
                         'разочарован', 'печаль', 'грустно', 'bad', 'worst',
                         'terrible', 'awful', 'sad', 'disappointed']
    
    text_lower = text.lower()
    
    # Подсчет индикаторов настроения
    positive_count = sum(1 for ind in positive_indicators if ind in text_lower)
    negative_count = sum(1 for ind in negative_indicators if ind in text_lower)
    
    # Учет восклицательных знаков
    exclamation_count = text.count('!')
    if positive_count > negative_count:
        positive_count += exclamation_count * 0.5
    elif negative_count > positive_count:
        negative_count += exclamation_count * 0.5
    
    # Определение итогового настроения
    if positive_count > negative_count:
        return 'positive'
    elif negative_count > positive_count:
        return 'negative'
    return 'neutral'

def extract_comment_data(comment_text):
    """Извлекает данные из отдельного комментария с поддержкой различных форматов"""
    try:
        # Паттерны для извлечения данных
        username_patterns = [
            r"Фото профиля ([^\n]+)",
            r"^([^\s]+)\s+",
            r"@([^\s]+)\s+",
        ]
        
        time_patterns = [
            r"(\d+)\s*(?:ч|нед)\.",
            r"(\d+)\s*(?:h|w)",
            r"(\d+)\s*(?:час|hour|week)",
        ]
        
        likes_patterns = [
            r"(\d+) отметк[аи] \"Нравится\"",
            r"Нравится: (\d+)",
            r"(\d+) отметка \"Нравится\"",
            r"\"Нравится\": (\d+)",
            r"likes?: (\d+)",
        ]

        # Поиск имени пользователя
        username = None
        for pattern in username_patterns:
            username_match = re.search(pattern, comment_text)
            if username_match:
                username = username_match.group(1).strip()
                break
                
        if not username:
            return None, None, 0, 0

        # Извлечение комментария
        comment = comment_text
        
        # Удаление метаданных
        metadata_patterns = [
            r"Фото профиля [^\n]+\n",
            r"\d+\s*(?:ч|нед|h|w|час|hour|week)\.",
            r"Нравится:?\s*\d+",
            r"\d+ отметк[аи] \"Нравится\"",
            r"Ответить",
            r"Показать перевод",
            r"Скрыть все ответы",
            r"Смотреть все ответы \(\d+\)",
            username
        ]
        
        for pattern in metadata_patterns:
            comment = re.sub(pattern, '', comment)
        
        comment = clean_text(comment)

        # Определение времени публикации
        weeks = 0
        for pattern in time_patterns:
            time_match = re.search(pattern, comment_text)
            if time_match:
                time_value = int(time_match.group(1))
                if any(unit in comment_text.lower() for unit in ['нед', 'w', 'week']):
                    weeks = time_value
                else:
                    weeks = time_value / (24 * 7)  # конвертация часов в недели
                break

        # Подсчет лайков
        likes = 0
        for pattern in likes_patterns:
            likes_match = re.search(pattern, comment_text)
            if likes_match:
                likes = int(likes_match.group(1))
                break

        return username, comment.strip(), likes, weeks
        
    except Exception as e:
        logger.error(f"Error extracting comment data: {e}")
        return None, None, 0, 0

def analyze_post(content_type: str, link_to_post: str, post_likes: int, post_date: str, 
                description: str, comment_count: int, all_comments: str) -> Tuple[str, str, str, str, str]:
    """
    Анализирует пост Instagram и его комментарии
    
    Args:
        content_type: Тип контента (фото/видео)
        link_to_post: Ссылка на пост
        post_likes: Количество лайков поста
        post_date: Дата публикации
        description: Описание поста
        comment_count: Ожидаемое количество комментариев
        all_comments: Текст всех комментариев
        
    Returns:
        Tuple[str, str, str, str, str]: Кортеж с результатами анализа
    """
    try:
        # Разделение на блоки комментариев
        comment_patterns = [
            r"(?=Фото профиля)",
            r"(?=\n\s*[a-zA-Z0-9._]+\s+[^\n]+\n)",
            r"(?=^[a-zA-Z0-9._]+\s+[^\n]+\n)",
            r"(?=@[a-zA-Z0-9._]+\s+[^\n]+\n)"
        ]
        
        split_pattern = '|'.join(comment_patterns)
        comments_blocks = re.split(split_pattern, all_comments)
        comments_blocks = [block.strip() for block in comments_blocks if block and block.strip()]
        
        # Инициализация переменных для анализа
        usernames = []
        comments = []
        likes = []
        weeks = []
        total_emojis = 0
        mentions = []
        sentiments = []
        comment_lengths = []
        words_per_comment = []
        all_words = []
        user_engagement = {}
        
        # Обработка комментариев
        for block in comments_blocks:
            if 'Скрыто алгоритмами Instagram' in block:
                continue
                
            username, comment, like_count, week_number = extract_comment_data(block)
            if username and comment:
                usernames.append(username)
                comments.append(comment)
                likes.append(str(like_count))
                weeks.append(week_number)
                
                # Сбор статистики
                total_emojis += count_emojis(comment)
                mentions.extend(extract_mentions(comment))
                sentiment = analyze_sentiment(comment)
                sentiments.append(sentiment)
                comment_lengths.append(len(comment))
                
                words = get_comment_words(comment)
                words_per_comment.append(len(words))
                all_words.extend(words)
                
                # Обновление статистики пользователя
                if username not in user_engagement:
                    user_engagement[username] = {
                        'comments': 0,
                        'total_likes': 0,
                        'emoji_usage': 0,
                        'avg_length': 0,
                        'sentiments': [],
                        'weeks': []
                    }
                    
                user_stats = user_engagement[username]
                user_stats['comments'] += 1
                user_stats['total_likes'] += like_count
                user_stats['emoji_usage'] += count_emojis(comment)
                user_stats['avg_length'] += len(comment)
                user_stats['sentiments'].append(sentiment)
                user_stats['weeks'].append(week_number)
        
        # Расчет статистики
        total_comments = len(comments)
        if total_comments == 0:
            return "No comments found", "", "", "", "0"
            
        # Обновление статистики пользователей
        for username in user_engagement:
            stats = user_engagement[username]
            stats['avg_length'] /= stats['comments']
            stats['engagement_rate'] = stats['total_likes'] / stats['comments']
            stats['sentiment_ratio'] = sum(1 for s in stats['sentiments'] if s == 'positive') / len(stats['sentiments'])
            stats['activity_period'] = max(stats['weeks']) - min(stats['weeks']) if stats['weeks'] else 0
        
        # Базовая статистика
        avg_comment_length = sum(comment_lengths) / total_comments
        sentiment_distribution = Counter(sentiments)
        most_active_users = Counter(usernames).most_common(5)
        most_mentioned = Counter(mentions).most_common(5)
        avg_likes = sum(map(int, likes)) / len(likes) if likes else 0
        
        # Временной анализ
        if weeks:
            earliest_week = max(weeks)
            latest_week = min(weeks)
            week_range = earliest_week - latest_week
            
            # Разделение на периоды
            period_length = week_range / 3 if week_range > 0 else 1
            engagement_periods = {
                'early': [],
                'middle': [],
                'late': []
            }
            
            for i, week in enumerate(weeks):
                if week >= earliest_week - period_length:
                    engagement_periods['early'].append(i)
                elif week >= earliest_week - 2 * period_length:
                    engagement_periods['middle'].append(i)
                else:
                    engagement_periods['late'].append(i)
            
            period_stats = {
                period: {
                    'comments': len(indices),
                    'avg_likes': sum(int(likes[i]) for i in indices) / len(indices) if indices else 0,
                    'sentiment_ratio': sum(1 for i in indices if sentiments[i] == 'positive') / len(indices) if indices else 0
                }
                for period, indices in engagement_periods.items()
            }
        else:
            period_stats = {}
            earliest_week = 0
            latest_week = 0
        
        # Подготовка CSV
        csv_data = {
            'metadata': {
                'content_type': content_type,
                'link': link_to_post,
                'post_likes': post_likes,
                'post_date': post_date,
                'total_comments': total_comments,
                'expected_comments': comment_count
            },
            'basic_stats': {
                'avg_comment_length': round(avg_comment_length, 2),
                'median_comment_length': statistics.median(comment_lengths),
                'avg_words': round(sum(words_per_comment) / total_comments, 2),
                'total_emojis': total_emojis,
                'avg_likes': round(avg_likes, 2)
            },
            'sentiment_stats': dict(Counter(sentiments)),
            'period_analysis': period_stats,
            'top_users': dict(most_active_users),
            'top_mentioned': dict(most_mentioned)
        }
        
        # Создание CSV строки
        output = StringIO()
        writer = csv.writer(output)
        for section, data in csv_data.items():
            writer.writerow([section])
            for key, value in data.items():
                writer.writerow([key, value])
            writer.writerow([])
        csv_output = output.getvalue()
        
        # Формирование отчета
        analytics_summary = (
            f"CSV DATA:\n{csv_output}\n\n"
            f"ДЕТАЛЬНЫЙ АНАЛИЗ:\n"
            f"Контент: {content_type}\n"
            f"Ссылка: {link_to_post}\n\n"
            f"СТАТИСТИКА:\n"
            f"- Всего комментариев: {total_comments} (ожидалось: {comment_count})\n"
            f"- Всего лайков на комментариях: {sum(map(int, likes))}\n"
            f"- Среднее лайков на комментарий: {avg_likes:.1f}\n"
            f"- Период активности: {earliest_week}-{latest_week} недель\n\n"
            f"АНАЛИЗ КОНТЕНТА:\n"
            f"- Средняя длина комментария: {avg_comment_length:.1f} символов\n"
            f"- Медиана длины: {statistics.median(comment_lengths)} символов\n"
            f"- Среднее количество слов: {sum(words_per_comment) / total_comments:.1f}\n"
            f"- Всего эмодзи: {total_emojis}\n"
            f"- Тональность:\n"
            f"  * Позитивных: {sentiment_distribution['positive']}\n"
            f"  * Нейтральных: {sentiment_distribution['neutral']}\n"
            f"  * Негативных: {sentiment_distribution['negative']}\n\n"
            f"АНАЛИЗ КОНТЕНТА:\n"
            f"- Средняя длина: {avg_comment_length:.1f} символов\n"
            f"- Медиана длины: {median_comment_length} символов\n"
            f"- Среднее слов: {avg_words_per_comment:.1f}\n"
            f"- Эмодзи: {total_emojis}\n"
            f"- Тональность:\n"
            f"  * Позитив: {sentiment_distribution['positive']}\n"
            f"  * Нейтрально: {sentiment_distribution['neutral']}\n"
            f"  * Негатив: {sentiment_distribution['negative']}\n\n"
            f"ПОПУЛЯРНЫЕ СЛОВА:\n"
            + "\n".join([f"- {word}: {count}" for word, count in common_words]) + "\n\n"
            f"АКТИВНЫЕ ПОЛЬЗОВАТЕЛИ:\n"
            + "\n".join([f"- {user}: {count}" for user, count in most_active_users]) + "\n\n"
            f"УПОМИНАНИЯ:\n"
            + "\n".join([f"- {user}: {count}" for user, count in most_mentioned if user]) + "\n\n"
            f"АНАЛИЗ ПО ПЕРИОДАМ:\n"
            + "\n".join([f"- {period}: {stats['comments']} комментариев, {stats['avg_likes']:.1f} лайков/коммент, "
                        f"{stats['sentiment_ratio']*100:.1f}% позитивных"
                        for period, stats in period_stats.items()]) + "\n\n"
            f"ЭКСПЕРИМЕНТАЛЬНАЯ АНАЛИТИКА:\n"
            f"- Самый активный период: {max(period_stats.items(), key=lambda x: x[1]['comments'])[0]}\n"
            f"- Наиболее позитивный период: {max(period_stats.items(), key=lambda x: x[1]['sentiment_ratio'])[0]}\n"
            f"- Период с макс. вовлеченностью: {max(period_stats.items(), key=lambda x: x[1]['avg_likes'])[0]}"
        )
        
        return analytics_summary, "\n".join(usernames), "\n".join(comments), "\n".join(likes), str(sum(map(int, likes)))
    
    except Exception as e:
        logger.error(f"Error in analyze_post: {e}", exc_info=True)
        return f"Error: {str(e)}", "", "", "", "0"

# Создаем интерфейс Gradio
iface = gr.Interface(
    fn=analyze_post,
    inputs=[
        gr.Radio(choices=["Photo", "Video"], label="Content Type", value="Photo"),
        gr.Textbox(label="Link to Post"),
        gr.Number(label="Likes", value=0),
        gr.Textbox(label="Post Date"),
        gr.Textbox(label="Description", lines=3),
        gr.Number(label="Total Comment Count", value=0),
        gr.Textbox(label="All Comments", lines=10)
    ],
    outputs=[
        gr.Textbox(label="Analytics Summary", lines=20),
        gr.Textbox(label="Usernames"),
        gr.Textbox(label="Comments"),
        gr.Textbox(label="Likes Chronology"),
        gr.Textbox(label="Total Likes on Comments")
    ],
    title="Enhanced Instagram Comment Analyzer",
    description="Анализатор комментариев Instagram с расширенной аналитикой и CSV-форматированием"
)

if __name__ == "__main__":
    iface.launch()