Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819201 unmodified line222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380import gradio as grfrom transformers import AutoTokenizer, AutoModelForCausalLM, BertModel, AutoModel, AutoModelForSequenceClassificationimport torchimport osimport jsonimport reimport numpy as npfrom collections import defaultdictfrom sklearn.cluster import DBSCANfrom sklearn.metrics.pairwise import cosine_similarityfrom sentence_transformers import SentenceTransformer# Загрузка модели для контекстных эмбеддинговsentence_model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')# Загрузка RuGPT модели и токенизатора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)1 unmodified linedevice = "cuda" if torch.cuda.is_available() else "cpu"rugpt_model = rugpt_model.to(device)# Конфигурация моделей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"}}EMOTION_TRANSLATION = {'disappointment': 'разочарование','sadness': 'грусть','neutral': 'нейтральность','joy': 'радость','surprise': 'удивление','fear': 'страх','anger': 'злость'}EMOTIONAL_MARKERS = {'злость': ['убей', 'жрет', 'кровь', 'злость', 'ярость', 'ненависть','гнев', 'мертвые', 'труп', 'смерть', 'убийство', 'война','бой', 'битва', 'враг', 'драка'],'грусть': ['грусть', 'печаль', 'тоска', 'слезы', 'боль', 'прощай','одиночество', 'страдание', 'утрата', 'потеря', 'пустота','тьма', 'холод', 'прощание'],'страх': ['страх', 'ужас', 'кошмар', 'темнота', 'смерть', 'могила','призрак', 'жуть', 'паника', 'тревога', 'жуткий', 'страшный'],'радость': ['радость', 'счастье', 'любовь', 'свет', 'улыбка', 'смех','веселье', 'праздник', 'восторг', 'наслаждение']}ANALYSIS_PARAMS = {'min_block_lines': 2, # Минимальное количество строк в блоке'max_block_lines': 4, # Максимальное количество строк в блоке'similarity_threshold': 0.7, # Порог схожести для группировки строк'emotion_threshold': 0.3, # Порог для фильтрации эмоций'neutral_threshold': 0.9, # Порог для отбрасывания нейтральных эмоций'clustering_eps': 0.5, # Параметр для кластеризации'clustering_min_samples': 2, # Минимальное количество образцов для кластеризации'top_n_quotes': 3 # Количество топовых цитат для каждой эмоции}EMOTION_LABELS = ['грусть','радость','злость','страх','разочарование','удивление','нейтральность']def emotion_analysis_to_vector(emotion_analysis, emotion_labels):vector = np.zeros(len(emotion_labels))label_to_idx = {label: idx for idx, label in enumerate(emotion_labels)}for emotion in emotion_analysis:if emotion['label'] in label_to_idx:vector[label_to_idx[emotion['label']]] = emotion['score']return vectordef cosine_sim(vec1, vec2):return cosine_similarity([vec1], [vec2])[0][0]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():try:print(f"Loading {model_type} model...")self.tokenizers[model_type] = AutoTokenizer.from_pretrained(config['name'])if config['task'] == "feature-extraction":if model_type == 'context':self.models[model_type] = BertModel.from_pretrained(config['name']).to(self.device)else:self.models[model_type] = AutoModel.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 emotions if 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 emotions# Анализ текста с помощью RuGPTrugpt_analysis = analyze_text_with_rugpt(text_block)return {'text': text_block,'emotions': final_emotions,'sentiment': self._analyze_sentiment(text_block),'context_embedding': self._get_context_embedding(text_block),'rugpt_analysis': rugpt_analysis # Добавляем результат анализа RuGPT}except Exception as e:print(f"Ошибка при анализе блока: {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):return sentence_model.encode(text)def analyze_text_with_rugpt(text):try:inputs = rugpt_tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(device)with torch.no_grad():outputs = rugpt_model.generate(**inputs, max_length=100, num_return_sequences=1)return rugpt_tokenizer.decode(outputs[0], skip_special_tokens=True)except Exception as e:print(f"Ошибка при вызове RuGPT: {str(e)}")return Noneclass TextBlockAnalyzer:def __init__(self):self.analyzer = TextAnalyzer()self.emotion_clusters = defaultdict(list)self.EMOTION_LABELS = EMOTION_LABELSdef _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)blocks = self.split_into_blocks(cleaned_text)if not blocks:return self._empty_result()print(f"Found {len(blocks)} blocks")block_analyses = []for block in blocks:analysis = self.analyzer.analyze_text_block(block)if analysis and analysis['emotions']:block_analyses.append(analysis)print(f"Analyzed {len(block_analyses)} blocks")if not block_analyses:return self._empty_result()self._cluster_blocks(block_analyses)return self._format_results(block_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 split_into_blocks(self, text):lines = text.split('\n')blocks = []current_block = []for line in lines:if not line.strip():continuecurrent_block.append(line)if len(current_block) >= ANALYSIS_PARAMS['max_block_lines']:blocks.append('\n'.join(current_block))current_block = []if current_block:blocks.append('\n'.join(current_block))return blocksdef _cluster_blocks(self, block_analyses):try:embeddings = np.array([analysis['context_embedding'] 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"Ошибка при кластеризации: {str(e)}")def _format_results(self, block_analyses):results = {'emotional_blocks': defaultdict(list),'general_mood': self._determine_general_mood(block_analyses),'emotional_progression': self._analyze_emotional_progression(block_analyses),'clusters': self._format_clusters()}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'])if primary_emotion['score'] >= ANALYSIS_PARAMS['emotion_threshold']:results['emotional_blocks'][primary_emotion['label']].append({'text': block['text'],'score': primary_emotion['score'],'sentiment': block['sentiment'],'all_emotions': emotions[:3],'rugpt_analysis': block.get('rugpt_analysis', None) # Добавляем анализ RuGPT})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 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):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_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"Ошибка при обработке файла {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"Ошибка при обработке файла: {str(e)}")return Nonedef 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 Nonedemo = gr.Interface(fn=analyze_files,inputs=gr.File(label="Загрузите .txt файлы", file_count="multiple", type="filepath"),1234567891011121 unmodified line1415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import 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)1 unmodified linedevice = "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=200, # Увеличиваем длину генерации для более детального анализа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'"(.*?)" - (.*?)\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"),
app.py+74-346