Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121133 unmodified lines117118119120import gradio as grfrom transformers import AutoTokenizer, AutoModelForCausalLM, pipelineimport torchimport osimport jsonimport re# Загрузка RuGPT3Small модели и токенизатораrugpt_model_name = "ai-forever/rugpt3small_based_on_gpt2"rugpt_tokenizer = AutoTokenizer.from_pretrained(rugpt_model_name)rugpt_model = AutoModelForCausalLM.from_pretrained(rugpt_model_name)# Перемещение модели на GPU (если доступен)device = "cuda" if torch.cuda.is_available() else "cpu"rugpt_model = rugpt_model.to(device)# Загрузка модели для анализа тональностиsentiment_analyzer = pipeline("sentiment-analysis", model="seara/rubert-base-cased-russian-sentiment")def analyze_text_with_rugpt(text):"""Анализирует текст с помощью RuGPT, чтобы найти эмоциональные цитаты."""try:# Формируем улучшенный промт для RuGPTprompt = f"""Проанализируй текст и найди в нём наиболее эмоциональные цитаты.Для каждой цитаты укажи, какую эмоцию она выражает.Формат вывода: "Цитата" - ЭмоцияТекст: {text}"""# Генерация ответаinputs = rugpt_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).to(device)with torch.no_grad():outputs = rugpt_model.generate(**inputs,max_length=300, # Увеличиваем длину генерацииnum_return_sequences=1,temperature=0.7, # Контроль случайностиtop_k=50, # Ограничиваем выборкуtop_p=0.9 # Используем nucleus sampling)generated_text = rugpt_tokenizer.decode(outputs[0], skip_special_tokens=True)# Извлекаем цитаты и эмоции из сгенерированного текстаquotes_with_emotions = extract_quotes_and_emotions(generated_text)return quotes_with_emotionsexcept Exception as e:print(f"Ошибка при вызове RuGPT: {str(e)}")return []def extract_quotes_and_emotions(text):"""Извлекает цитаты и эмоции из текста, сгенерированного RuGPT."""# Используем улучшенное регулярное выражениеpattern = r'"(.*?)"\s*-\s*(.*?)(\n|$)'matches = re.findall(pattern, text)# Форматируем результатquotes_with_emotions = [{"quote": match[0], "emotion": match[1]} for match in matches]return quotes_with_emotionsdef analyze_sentiment(text):"""Анализирует тональность текста."""result = sentiment_analyzer(text)return result[0]['label'], result[0]['score']def analyze_files(file_paths):"""Анализирует текстовые файлы, находит эмоциональные цитаты и сохраняет результаты."""result_files = []for file_path in file_paths:try:with open(file_path, 'r', encoding='utf-8') as f:text = f.read()file_name = os.path.basename(file_path)# Анализ текста с помощью RuGPTquotes_with_emotions = analyze_text_with_rugpt(text)# Анализ тональности текстаsentiment_label, sentiment_score = analyze_sentiment(text)# Формируем результатoutput = {'file_name': file_name,'quotes_with_emotions': quotes_with_emotions,'sentiment': {'label': sentiment_label,'score': sentiment_score}}# Сохраняем результат в JSONoutput_file_name = f"{os.path.splitext(file_name)[0]}_analysis.json"output_file_path = os.path.join(os.getcwd(), output_file_name)with open(output_file_path, 'w', encoding='utf-8') as f:json.dump(output, f, ensure_ascii=False, indent=2)result_files.append(output_file_path)except Exception as e:print(f"Ошибка при обработке файла {file_name}: {str(e)}")return result_files# Интерфейс Gradiodemo = gr.Interface(fn=analyze_files,inputs=gr.File(label="Загрузите .txt файлы", file_count="multiple", type="filepath"),3 unmodified lines)if __name__ == "__main__":demo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924933 unmodified lines497498499500import gradio as grfrom transformers import AutoTokenizer, AutoModel, BertModel, AutoModelForSequenceClassification, GPT2LMHeadModel, GPT2Tokenizerimport torchimport osimport jsonimport reimport numpy as npfrom collections import defaultdictfrom sklearn.cluster import DBSCAN# Конфигурация моделейMODELS = {'emotion': {'name': "cointegrated/rubert-tiny2-cedr-emotion-detection",'task': "emotion"},'sentiment': {'name': "seara/rubert-base-cased-russian-sentiment",'task': "sentiment"},'context': {'name': "DeepPavlov/rubert-base-cased",'task': "feature-extraction"},'gpt': {'name': "saiga/rugpt3medium_based_on_gpt2",'task': "text-generation"}}# Промпты для GPTGPT_PROMPTS = {'find_quotes': """Найди в тексте эмоционально значимые цитаты.Каждая цитата должна быть самодостаточной и передавать законченную мысль.Верни только цитаты, по одной на строку, без пояснений и нумерации.Текст:{text}Цитаты:""",'analyze_context': """Проанализируй следующий текст и определи, какие части текстасвязаны между собой по смыслу и эмоциональному содержанию.Верни только связанные фрагменты текста, разделенные переносом строки.Текст:{text}Фрагменты:"""}EMOTION_TRANSLATION = {'disappointment': 'разочарование','sadness': 'грусть','neutral': 'нейтральность','joy': 'радость','surprise': 'удивление','fear': 'страх','anger': 'злость'}# Расширенный словарь эмоциональных маркеровEMOTIONAL_MARKERS = {'злость': ['убей', 'жрет', 'кровь', 'злость', 'ярость', 'ненависть','гнев', 'мертвые', 'труп', 'смерть', 'убийство', 'война','бой', 'битва', 'враг', 'драка'],'грусть': ['грусть', 'печаль', 'тоска', 'слезы', 'боль', 'прощай','одиночество', 'страдание', 'утрата', 'потеря', 'пустота','тьма', 'холод', 'прощание'],'страх': ['страх', 'ужас', 'кошмар', 'темнота', 'смерть', 'могила','призрак', 'жуть', 'паника', 'тревога', 'жуткий', 'страшный'],'радость': ['радость', 'счастье', 'любовь', 'свет', 'улыбка', 'смех','веселье', 'праздник', 'восторг', 'наслаждение']}ANALYSIS_PARAMS = {'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,'max_length': 1024,'temperature': 0.7,'top_p': 0.95,'top_k': 50}class GPTQuoteExtractor:def __init__(self):self.model = Noneself.tokenizer = Noneself.device = "cuda" if torch.cuda.is_available() else "cpu"self._load_model()def _load_model(self):try:model_name = MODELS['gpt']['name']print(f"Loading GPT model {model_name}...")self.tokenizer = GPT2Tokenizer.from_pretrained(model_name)self.model = GPT2LMHeadModel.from_pretrained(model_name).to(self.device)print("GPT model loaded successfully")except Exception as e:print(f"Error loading GPT model: {str(e)}")def extract_quotes(self, text):try:# Подготавливаем промптprompt = GPT_PROMPTS['find_quotes'].format(text=text)# Токенизируемinputs = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device)# Генерируем ответwith torch.no_grad():outputs = self.model.generate(inputs,max_length=ANALYSIS_PARAMS['max_length'],num_return_sequences=1,no_repeat_ngram_size=2,do_sample=True,top_k=ANALYSIS_PARAMS['top_k'],top_p=ANALYSIS_PARAMS['top_p'],temperature=ANALYSIS_PARAMS['temperature'],pad_token_id=self.tokenizer.eos_token_id)# Декодируем результатgenerated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)# Извлекаем только цитаты (после "Цитаты:")quotes_text = generated_text.split("Цитаты:")[-1].strip()# Разбиваем на отдельные цитатыquotes = [q.strip() for q in quotes_text.split('\n') if q.strip()]return quotesexcept Exception as e:print(f"Error extracting quotes: {str(e)}")return []def analyze_context(self, text):try:prompt = GPT_PROMPTS['analyze_context'].format(text=text)inputs = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device)with torch.no_grad():outputs = self.model.generate(inputs,max_length=ANALYSIS_PARAMS['max_length'],num_return_sequences=1,no_repeat_ngram_size=2,do_sample=True,top_k=ANALYSIS_PARAMS['top_k'],top_p=ANALYSIS_PARAMS['top_p'],temperature=ANALYSIS_PARAMS['temperature'],pad_token_id=self.tokenizer.eos_token_id)generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)fragments_text = generated_text.split("Фрагменты:")[-1].strip()fragments = [f.strip() for f in fragments_text.split('\n') if f.strip()]return fragmentsexcept Exception as e:print(f"Error analyzing context: {str(e)}")return []class TextAnalyzer:def __init__(self):self.models = {}self.tokenizers = {}self.device = "cuda" if torch.cuda.is_available() else "cpu"self._load_models()def _load_models(self):for model_type, config in MODELS.items():if model_type == 'gpt': # Пропускаем GPT модель, она загружается отдельноcontinuetry:print(f"Loading {model_type} model...")self.tokenizers[model_type] = AutoTokenizer.from_pretrained(config['name'])if config['task'] == "feature-extraction":self.models[model_type] = BertModel.from_pretrained(config['name']).to(self.device)else:self.models[model_type] = AutoModelForSequenceClassification.from_pretrained(config['name']).to(self.device)print(f"{model_type} model loaded successfully")except Exception as e:print(f"Error loading {model_type} model: {str(e)}")def analyze_text_block(self, text_block):if not text_block.strip():return Nonetry:emotions = self._analyze_emotions(text_block)filtered_emotions = [e for e in emotionsif e['label'] not in ['neutral', 'no_emotion']or e['score'] < ANALYSIS_PARAMS['neutral_threshold']]additional_emotions = analyze_emotions(text_block)if additional_emotions:filtered_emotions.extend(additional_emotions)final_emotions = filtered_emotions if filtered_emotions else emotionsreturn {'text': text_block,'emotions': final_emotions,'sentiment': self._analyze_sentiment(text_block),'context_embedding': self._get_context_embedding(text_block)}except Exception as e:print(f"Error analyzing block: {str(e)}")return Nonedef _analyze_emotions(self, text):model = self.models['emotion']tokenizer = self.tokenizers['emotion']inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(self.device)with torch.no_grad():outputs = model(**inputs)scores = torch.nn.functional.softmax(outputs.logits, dim=1)[0]emotions = []for idx, score in enumerate(scores):label = model.config.id2label[idx]emotion_label = EMOTION_TRANSLATION.get(label, label)if emotion_label not in ['neutral', 'no_emotion'] or float(score) < ANALYSIS_PARAMS['neutral_threshold']:emotions.append({'label': emotion_label,'score': float(score)})return sorted(emotions, key=lambda x: x['score'], reverse=True)def _analyze_sentiment(self, text):model = self.models['sentiment']tokenizer = self.tokenizers['sentiment']inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(self.device)with torch.no_grad():outputs = 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']tokenizer = self.tokenizers['context']inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(self.device)with torch.no_grad():outputs = model(**inputs)embeddings = outputs.last_hidden_state.mean(dim=1)return embeddings.cpu().numpy()class TextBlockAnalyzer:def __init__(self):self.analyzer = TextAnalyzer()self.gpt_extractor = GPTQuoteExtractor()self.emotion_clusters = defaultdict(list)def _empty_result(self):return {'emotional_blocks': {},'general_mood': {'average_sentiment': 0, 'dominant_emotion': 'neutral'},'emotional_progression': [],'clusters': []}def analyze_text(self, text):cleaned_text = self.preprocess_text(text)# Получаем цитаты с помощью GPTquotes = self.gpt_extractor.extract_quotes(cleaned_text)if not quotes:return self._empty_result()print(f"Found {len(quotes)} quotes")# Анализируем каждую цитатуquote_analyses = []for quote in quotes:analysis = self.analyzer.analyze_text_block(quote)if analysis and analysis['emotions']:quote_analyses.append(analysis)print(f"Analyzed {len(quote_analyses)} quotes")if not quote_analyses:return self._empty_result()self._cluster_blocks(quote_analyses)return self._format_results(quote_analyses)def preprocess_text(self, text):lines = []for line in text.split('\n'):line = line.strip()if any([not line,line.startswith('['),line.startswith('Название:'),line.startswith('URL:'),all(char in '=*-_' for char in line),re.match(r'^\[.*\]$', line)]):continuecleaned_line = re.sub(r'[^а-яА-ЯёЁ0-9\s.!?,\-]', '', line)cleaned_line = re.sub(r'\s+', ' ', cleaned_line).strip()if cleaned_line:lines.append(cleaned_line)return '\n'.join(lines)def _cluster_blocks(self, block_analyses):try:embeddings = np.array([analysis['context_embedding'][0] for analysis in block_analyses])clustering = DBSCAN(eps=ANALYSIS_PARAMS['clustering_eps'],min_samples=ANALYSIS_PARAMS['clustering_min_samples']).fit(embeddings)self.emotion_clusters.clear()for idx, label in enumerate(clustering.labels_):self.emotion_clusters[label].append(block_analyses[idx])except Exception as e:print(f"Clustering error: {str(e)}")def _format_results(self, quote_analyses):results = {'emotional_blocks': defaultdict(list),'general_mood': self._determine_general_mood(quote_analyses),'emotional_progression': self._analyze_emotional_progression(quote_analyses),'clusters': self._format_clusters()}for analysis in quote_analyses:emotions = [e for e in analysis['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'])if primary_emotion['score'] >= ANALYSIS_PARAMS['emotion_threshold']:results['emotional_blocks'][primary_emotion['label']].append({'text': analysis['text'],'score': primary_emotion['score'],'sentiment': analysis['sentiment'],'all_emotions': emotions[:3]})for emotion in results['emotional_blocks']:results['emotional_blocks'][emotion] = sorted(results['emotional_blocks'][emotion],key=lambda x: x['score'],reverse=True)[:ANALYSIS_PARAMS['top_n_quotes']]return resultsdef _determine_general_mood(self, block_analyses):sentiments = [block['sentiment'] for block in block_analyses]emotion_scores = defaultdict(float)for block in block_analyses:for emotion in block['emotions']:emotion_scores[emotion['label']] += emotion['score']dominant_emotion = max(emotion_scores.items(), key=lambda x: x[1])[0]return {'average_sentiment': float(np.mean(sentiments)),'sentiment_variance': float(np.var(sentiments)),'dominant_emotion': dominant_emotion}def _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):clusters_info = []for label, blocks in self.emotion_clusters.items():if label == -1:continuecluster_emotions = defaultdict(float)for block in blocks: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'])cluster_emotions[primary_emotion['label']] += primary_emotion['score']if cluster_emotions:dominant_emotion = max(cluster_emotions.items(), key=lambda x: x[1])clusters_info.append({'cluster_id': int(label),'dominant_emotion': dominant_emotion[0],'emotion_score': float(dominant_emotion[1] / len(blocks)),'blocks': [block['text'] for block in blocks]})return clusters_infodef analyze_emotions(text_block):found_emotions = []lower_text = text_block.lower()for emotion, markers in EMOTIONAL_MARKERS.items():for marker in markers:if marker in lower_text:found_emotions.append({'label': emotion,'score': 0.7})breakreturn found_emotions if found_emotions else Nonedef analyze_files(file_paths):result_files = []for file_path in file_paths:try:with open(file_path, 'r', encoding='utf-8') as f:text = f.read()file_name = os.path.basename(file_path)result_path = analyze_text_file(text, file_name)if result_path:result_files.append(result_path)except Exception as e:print(f"Error processing file {file_name}: {str(e)}")return result_filesdef analyze_text_file(text, original_file_name):try:analyzer = TextBlockAnalyzer()analysis_results = analyzer.analyze_text(text)output = {'file_name': original_file_name,'analysis': analysis_results}output_file_name = f"{os.path.splitext(original_file_name)[0]}_analysis.json"output_file_path = os.path.join(os.getcwd(), output_file_name)with open(output_file_path, 'w', encoding='utf-8') as f:json.dump(output, f, ensure_ascii=False, indent=2)return output_file_pathexcept Exception as e:print(f"Error processing file: {str(e)}")return None# Создание интерфейса Gradiodemo = gr.Interface(fn=analyze_files,inputs=gr.File(label="Загрузите .txt файлы", file_count="multiple", type="filepath"),3 unmodified lines)if __name__ == "__main__":demo.launch()
app.py+469-89