Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234511 unmodified lines1718192021222324252627282930 unmodified lines60616263646566676869707172737482 unmodified lines15715815916016116216316423 unmodified lines18818919019119219319419542 unmodified lines23823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826967 unmodified lines337338339340341342343344345346347348349350351352353import gradio as grfrom transformers import AutoTokenizer, AutoModel, BertModel, AutoModelForSequenceClassificationimport torchimport osimport json11 unmodified lines},# Для анализа тональности и общего настроения'sentiment': {'name': "blanchefort/rubert-base-cased-sentiment",'task': "sentiment"},# Для понимания контекста и тем'context': {'name': "DeepPavlov/rubert-base-cased", # Используем исходную модель'task': "feature-extraction" # Задача для извлечения признаков}}30 unmodified lines}ANALYSIS_PARAMS = {'min_block_lines': 1,'max_block_lines': 3, # Максимальное количество строк в блоке'min_block_words': 3,'metaphor_threshold': 0.5,'emotion_threshold': 0.3,'clustering_eps': 0.5,'clustering_min_samples': 2,'top_n_quotes': 3,'neutral_threshold': 0.9}class TextAnalyzer:82 unmodified linesoutputs = model(**inputs)scores = torch.nn.functional.softmax(outputs.logits, dim=1)[0]# Предполагаем, что положительная тональность – индекс 2, отрицательная – 0return float(scores[2]) - float(scores[0]) # Регулируйте в зависимости от моделиdef _get_context_embedding(self, text):model = self.models['context']23 unmodified lines# Предварительная обработка текстаcleaned_text = self.preprocess_text(text)# Разбиваем на смысловые блокиblocks = self.split_into_meaningful_blocks(cleaned_text)if not blocks:return self._empty_result()42 unmodified linesreturn '\n'.join(lines)def split_into_meaningful_blocks(self, text):blocks = []current_block = []lines = text.split('\n')for i, line in enumerate(lines):if not line.strip():continuecurrent_block.append(line)# Проверяем условия для завершения блока:# 1. Если достигли максимального количества строк# 2. Если следующая строка пустая# 3. Если достигли конца текстаnext_line_empty = (i < len(lines) - 1 and not lines[i + 1].strip())max_lines_reached = len(current_block) >= ANALYSIS_PARAMS['max_block_lines']end_of_text = i == len(lines) - 1if max_lines_reached or next_line_empty or end_of_text:# Формируем блок, сохраняя переносы строкblock_text = '\n'.join(current_block)if len(block_text.split()) >= ANALYSIS_PARAMS['min_block_words']:blocks.append(block_text)current_block = []return blocksdef _cluster_blocks(self, block_analyses):67 unmodified linesdef _analyze_emotional_progression(self, block_analyses):progression = []for block in block_analyses:emotions = [e for e in block['emotions']if e['label'] not in ['neutral', 'no_emotion']or e['score'] < ANALYSIS_PARAMS['neutral_threshold']]if emotions:primary_emotion = max(emotions, key=lambda x: x['score'])progression.append({'text': block['text'],'emotion': primary_emotion['label'],'intensity': float(primary_emotion['score'])})return progressiondef _format_clusters(self):1234511 unmodified lines1718192021222324252627282930 unmodified lines60616263646566676869707172737482 unmodified lines15715815916016116216323 unmodified lines18718818919019119219319442 unmodified lines23723823924024124224324424524624724867 unmodified lines316317318319320321322323324325326327328329330331332333334335336337import gradio as grfrom transformers import AutoTokenizer, AutoModel, BertModel, AutoModelForSequenceClassification, GPT2LMHeadModel, GPT2Tokenizerimport torchimport osimport json11 unmodified lines},# Для анализа тональности и общего настроения'sentiment': {'name': "seara/rubert-base-cased-russian-sentiment",'task': "sentiment"},# Для понимания контекста и тем'context': {'name': "DeepPavlov/rubert-base-cased", # Используем исходную модель'task': "feature-extraction" # Меняем задачу на feature-extraction}}30 unmodified lines}ANALYSIS_PARAMS = {'min_block_lines': 2,'min_block_words': 3,'metaphor_threshold': 0.5,'emotion_threshold': 0.3,'clustering_eps': 0.5,'clustering_min_samples': 2,'top_n_quotes': 3,'neutral_threshold': 0.9,'sliding_window_size': 3 # Размер скользящего окна для анализа контекста}class TextAnalyzer:82 unmodified linesoutputs = model(**inputs)scores = torch.nn.functional.softmax(outputs.logits, dim=1)[0]return float(scores[1]) - float(scores[0])def _get_context_embedding(self, text):model = self.models['context']23 unmodified lines# Предварительная обработка текстаcleaned_text = self.preprocess_text(text)# Разбиваем на смысловые блоки с использованием скользящего окнаblocks = self.split_into_sliding_blocks(cleaned_text, ANALYSIS_PARAMS['sliding_window_size'])if not blocks:return self._empty_result()42 unmodified linesreturn '\n'.join(lines)def split_into_sliding_blocks(self, text, window_size=3):lines = text.split('\n')blocks = []for i in range(len(lines) - window_size + 1):block = '\n'.join(lines[i:i + window_size])blocks.append(block)return blocksdef _cluster_blocks(self, block_analyses):67 unmodified linesdef _analyze_emotional_progression(self, block_analyses):progression = []for i in range(len(block_analyses) - 1):current_block = block_analyses[i]next_block = block_analyses[i + 1]current_emotions = current_block['emotions']next_emotions = next_block['emotions']if current_emotions and next_emotions:current_primary = max(current_emotions, key=lambda x: x['score'])next_primary = max(next_emotions, key=lambda x: x['score'])progression.append({'transition': f"{current_primary['label']} -> {next_primary['label']}",'intensity': (current_primary['score'] + next_primary['score']) / 2})return progressiondef _format_clusters(self):
app.py+28-44