File size: 15,800 Bytes
9297977
 
 
 
 
 
92287cb
0c8faca
e20a82b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92287cb
 
 
9297977
4feef77
 
 
 
 
 
 
 
 
 
 
 
 
9297977
 
f0111d1
412ee33
 
 
 
 
f0111d1
 
 
 
4feef77
9297977
412ee33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4feef77
 
 
 
 
 
 
 
9297977
f0111d1
9297977
 
f0111d1
 
 
 
e20a82b
 
4feef77
e20a82b
 
412ee33
 
 
e20a82b
 
4feef77
 
 
e20a82b
 
 
 
 
9297977
 
 
 
 
92287cb
9297977
 
 
a5a84d4
 
 
92287cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9297977
f0111d1
ce3b970
 
 
f0111d1
 
ce3b970
e20a82b
 
 
 
 
ce3b970
 
 
 
e20a82b
 
 
 
ce3b970
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e20a82b
ce3b970
 
f0111d1
 
 
ce3b970
 
 
 
 
 
 
 
 
 
 
 
 
9297977
4feef77
 
92287cb
412ee33
9297977
 
92287cb
 
 
118a5c5
92287cb
9297977
 
2a0d401
4feef77
2a0d401
 
 
4feef77
2a0d401
4feef77
2a0d401
 
 
4feef77
92287cb
 
 
ce3b970
118a5c5
 
92287cb
9297977
 
92287cb
 
 
 
 
9297977
 
2a0d401
9297977
2a0d401
9297977
 
4feef77
 
 
 
85ab85d
 
92287cb
118a5c5
ce3b970
92287cb
4feef77
 
 
85ab85d
ce3b970
 
 
 
 
4feef77
 
 
118a5c5
4feef77
 
 
 
ce3b970
4feef77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce3b970
4feef77
 
ce3b970
 
4feef77
 
 
 
ce3b970
9297977
92287cb
ce3b970
 
 
 
9297977
4feef77
9297977
118a5c5
9297977
92287cb
9297977
 
 
 
 
 
92287cb
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import gradio as gr
import spaces
import pandas as pd
import torch
from transformers import pipeline, AutoModelForSeq2SeqLM, AutoTokenizer
import plotly.graph_objects as go
import logging
import io
from rapidfuzz import fuzz

def fuzzy_deduplicate(df, column, threshold=55):
    """Deduplicate rows based on fuzzy matching of text content"""
    seen_texts = []
    indices_to_keep = []
    
    for i, text in enumerate(df[column]):
        if pd.isna(text):
            indices_to_keep.append(i)
            continue
            
        text = str(text)
        if not seen_texts or all(fuzz.ratio(text, seen) < threshold for seen in seen_texts):
            seen_texts.append(text)
            indices_to_keep.append(i)
            
    return df.iloc[indices_to_keep]

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ProcessControl:
    def __init__(self):
        self.stop_requested = False
        
    def request_stop(self):
        self.stop_requested = True
        
    def should_stop(self):
        return self.stop_requested
        
    def reset(self):
        self.stop_requested = False

class EventDetector:
    def __init__(self):
        self.model_name = "google/mt5-small"
        # Initialize tokenizer with legacy=True to suppress warning
        self.tokenizer = AutoTokenizer.from_pretrained(
            self.model_name,
            legacy=True
        )
        self.model = None
        self.finbert = None
        self.roberta = None
        self.finbert_tone = None
        self.control = ProcessControl()

    @spaces.GPU
    def initialize_models(self):
        """Initialize all models with GPU support"""
        try:
            device = "cuda" if torch.cuda.is_available() else "cpu"
            logger.info(f"Initializing models on device: {device}")
            
            # Initialize MT5 model
            self.model = AutoModelForSeq2SeqLM.from_pretrained(self.model_name).to(device)
            
            # Initialize sentiment analysis pipelines
            self.finbert = pipeline(
                "sentiment-analysis",
                model="ProsusAI/finbert",
                device=device,
                truncation=True,
                max_length=512
            )
            
            self.roberta = pipeline(
                "sentiment-analysis",
                model="cardiffnlp/twitter-roberta-base-sentiment",
                device=device,
                truncation=True,
                max_length=512
            )
            
            self.finbert_tone = pipeline(
                "sentiment-analysis",
                model="yiyanghkust/finbert-tone",
                device=device,
                truncation=True,
                max_length=512
            )
            
            logger.info("All models initialized successfully")
            return True
            
        except Exception as e:
            logger.error(f"Model initialization error: {str(e)}")
            return False

    @spaces.GPU
    def detect_events(self, text, entity):
        if not text or not entity:
            return "Нет", "Invalid input"
            
        try:
            # Check if models are initialized
            if self.model is None:
                if not self.initialize_models():
                    return "Нет", "Model initialization failed"
            
            # Truncate input text
            text = text[:500]
            
            prompt = f"""<s>Analyze the following news about {entity}:
            Text: {text}
            Task: Identify the main event type and provide a brief summary.</s>"""
            
            inputs = self.tokenizer(
                prompt,
                return_tensors="pt",
                padding=True,
                truncation=True,
                max_length=512
            ).to(self.model.device)
            
            outputs = self.model.generate(
                **inputs,
                max_length=300,
                num_return_sequences=1,
                pad_token_id=self.tokenizer.pad_token_id,
                eos_token_id=self.tokenizer.eos_token_id
            )
            response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
            
            event_type = "Нет"
            if any(term in text.lower() for term in ['отчет', 'выручка', 'прибыль', 'ebitda']):
                event_type = "Отчетность"
            elif any(term in text.lower() for term in ['облигаци', 'купон', 'дефолт']):
                event_type = "РЦБ"
            elif any(term in text.lower() for term in ['суд', 'иск', 'арбитраж']):
                event_type = "Суд"
                
            return event_type, response
            
        except Exception as e:
            logger.error(f"Event detection error: {str(e)}")
            return "Нет", f"Error: {str(e)}"

    def get_sentiment_label(self, result):
        """Helper method for sentiment classification"""
        label = result['label'].lower()
        if label in ["positive", "label_2", "pos"]:
            return "Positive"
        elif label in ["negative", "label_0", "neg"]:
            return "Negative"
        return "Neutral"

    @spaces.GPU
    def analyze_sentiment(self, text):
        try:
            if self.finbert is None:
                if not self.initialize_models():
                    return "Neutral"
            
            truncated_text = text[:500]
            results = []
            
            try:
                inputs = [truncated_text]
                finbert_result = self.finbert(inputs)[0]
                roberta_result = self.roberta(inputs)[0]
                finbert_tone_result = self.finbert_tone(inputs)[0]
                
                results = [
                    self.get_sentiment_label(finbert_result),
                    self.get_sentiment_label(roberta_result),
                    self.get_sentiment_label(finbert_tone_result)
                ]
                
            except Exception as e:
                logger.error(f"Model inference error: {e}")
                return "Neutral"
            
            sentiment_counts = pd.Series(results).value_counts()
            return sentiment_counts.index[0] if sentiment_counts.iloc[0] >= 2 else "Neutral"
            
        except Exception as e:
            logger.error(f"Sentiment analysis error: {e}")
            return "Neutral"

def create_visualizations(df):
    if df is None or df.empty:
        return None, None
        
    try:
        sentiments = df['Sentiment'].value_counts()
        fig_sentiment = go.Figure(data=[go.Pie(
            labels=sentiments.index,
            values=sentiments.values,
            marker_colors=['#FF6B6B', '#4ECDC4', '#95A5A6']
        )])
        fig_sentiment.update_layout(title="Распределение тональности")
        
        events = df['Event_Type'].value_counts()
        fig_events = go.Figure(data=[go.Bar(
            x=events.index,
            y=events.values,
            marker_color='#2196F3'
        )])
        fig_events.update_layout(title="Распределение событий")
        
        return fig_sentiment, fig_events
        
    except Exception as e:
        logger.error(f"Visualization error: {e}")
        return None, None

@spaces.GPU
def process_file(file_obj):
    try:
        logger.info("Starting to read Excel file...")
        df = pd.read_excel(file_obj, sheet_name='Публикации')
        logger.info(f"Successfully read Excel file. Shape: {df.shape}")
        
        # Perform deduplication
        original_count = len(df)
        df = fuzzy_deduplicate(df, 'Выдержки из текста', threshold=55)
        logger.info(f"Removed {original_count - len(df)} duplicate entries")
        
        detector = EventDetector()
        processed_rows = []
        total = len(df)
        
        # Initialize models once for all rows
        if not detector.initialize_models():
            raise Exception("Failed to initialize models")
        
        for idx, row in df.iterrows():
            try:
                text = str(row.get('Выдержки из текста', ''))
                if not text.strip():
                    continue
                    
                entity = str(row.get('Объект', ''))
                if not entity.strip():
                    continue
                
                event_type, event_summary = detector.detect_events(text, entity)
                sentiment = detector.analyze_sentiment(text)
                
                processed_rows.append({
                    'Объект': entity,
                    'Заголовок': str(row.get('Заголовок', '')),
                    'Sentiment': sentiment,
                    'Event_Type': event_type,
                    'Event_Summary': event_summary,
                    'Текст': text[:1000]  # Truncate text for display
                })
                
                if idx % 5 == 0:
                    logger.info(f"Processed {idx + 1}/{total} rows")
                    
            except Exception as e:
                logger.error(f"Error processing row {idx}: {str(e)}")
                continue
        
        result_df = pd.DataFrame(processed_rows)
        logger.info(f"Processing complete. Final DataFrame shape: {result_df.shape}")
        
        return result_df
        
    except Exception as e:
        logger.error(f"File processing error: {str(e)}")
        raise

def create_interface():
    control = ProcessControl()
    
    with gr.Blocks(theme=gr.themes.Soft()) as app:
        gr.Markdown("# AI-анализ мониторинга новостей v.1.14")
        
        with gr.Row():
            file_input = gr.File(
                label="Загрузите Excel файл",
                file_types=[".xlsx"],
                type="binary"
            )
        
        with gr.Row():
            with gr.Column(scale=1):
                analyze_btn = gr.Button(
                    "▶️ Начать анализ",
                    variant="primary",
                    size="lg"
                )
            with gr.Column(scale=1):
                stop_btn = gr.Button(
                    "⏹️ Остановить",
                    variant="stop",
                    size="lg"
                )
            
        with gr.Row():
            progress = gr.Textbox(
                label="Статус обработки",
                interactive=False,
                value="Ожидание файла..."
            )
        
        with gr.Row():
            stats = gr.DataFrame(
                label="Результаты анализа",
                interactive=False,
                wrap=True
            )
            
        with gr.Row():
            with gr.Column(scale=1):
                sentiment_plot = gr.Plot(label="Распределение тональности")
            with gr.Column(scale=1):
                events_plot = gr.Plot(label="Распределение событий")
                
        def stop_processing():
            control.request_stop()
            return "Остановка обработки..."
                
        def analyze(file_bytes):
            if file_bytes is None:
                gr.Warning("Пожалуйста, загрузите файл")
                return None, None, None, "Ожидание файла..."
                
            try:
                # Reset stop flag
                control.reset()
                
                file_obj = io.BytesIO(file_bytes)
                logger.info("File loaded into BytesIO successfully")
                
                progress_status = "Начинаем обработку файла..."
                yield None, None, None, progress_status
                
                # Process file
                df = pd.read_excel(file_obj, sheet_name='Публикации')
                logger.info(f"Successfully read Excel file. Shape: {df.shape}")
                
                # Deduplication
                original_count = len(df)
                df = fuzzy_deduplicate(df, 'Выдержки из текста', threshold=55)
                logger.info(f"Removed {original_count - len(df)} duplicate entries")
                
                detector = EventDetector()
                detector.control = control  # Pass control object
                processed_rows = []
                total = len(df)
                
                # Initialize models
                if not detector.initialize_models():
                    raise Exception("Failed to initialize models")
                
                for idx, row in df.iterrows():
                    if control.should_stop():
                        yield (
                            pd.DataFrame(processed_rows) if processed_rows else None,
                            None, None,
                            f"Обработка остановлена. Обработано {idx} из {total} строк"
                        )
                        return
                    
                    try:
                        text = str(row.get('Выдержки из текста', ''))
                        if not text.strip():
                            continue
                            
                        entity = str(row.get('Объект', ''))
                        if not entity.strip():
                            continue
                        
                        event_type, event_summary = detector.detect_events(text, entity)
                        sentiment = detector.analyze_sentiment(text)
                        
                        processed_rows.append({
                            'Объект': entity,
                            'Заголовок': str(row.get('Заголовок', '')),
                            'Sentiment': sentiment,
                            'Event_Type': event_type,
                            'Event_Summary': event_summary,
                            'Текст': text[:1000]
                        })
                        
                        if idx % 5 == 0:
                            progress_status = f"Обработано {idx + 1}/{total} строк"
                            yield None, None, None, progress_status
                            
                    except Exception as e:
                        logger.error(f"Error processing row {idx}: {str(e)}")
                        continue
                
                result_df = pd.DataFrame(processed_rows)
                fig_sentiment, fig_events = create_visualizations(result_df)
                
                return (
                    result_df,
                    fig_sentiment,
                    fig_events,
                    f"Обработка завершена успешно! Обработано {len(result_df)} строк"
                )
                
            except Exception as e:
                error_msg = f"Ошибка анализа: {str(e)}"
                logger.error(error_msg)
                gr.Error(error_msg)
                return None, None, None, error_msg
            
        stop_btn.click(fn=stop_processing, outputs=[progress])
        analyze_btn.click(
            fn=analyze,
            inputs=[file_input],
            outputs=[stats, sentiment_plot, events_plot, progress]
        )
        
    return app

if __name__ == "__main__":
    app = create_interface()
    app.launch(share=True)