Spaces:
Sleeping
Sleeping
Update app.py
Browse files123454 unmodified lines101112131415161718192021222324252653 unmodified lines8081828384858668 unmodified lines155156157158159160161162163164165166167168169170153 unmodified lines32432532632732832982 unmodified lines412413414415import gradio as grfrom transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassificationimport torchimport osimport json4 unmodified lines# Конфигурация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" # Меняем только задачу}}53 unmodified linesprint(f"Loading {model_type} model...")self.tokenizers[model_type] = AutoTokenizer.from_pretrained(config['name'])if config['task'] == "feature-extraction":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")68 unmodified linesmodel = 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)if hasattr(outputs, 'last_hidden_state'):embeddings = outputs.last_hidden_state.mean(dim=1)else:embeddings = outputs.logitsreturn embeddings.cpu().numpy()class TextBlockAnalyzer:def __init__(self):self.analyzer = TextAnalyzer()153 unmodified linesreturn resultsdef _format_clusters(self):clusters_info = []for label, blocks in self.emotion_clusters.items():82 unmodified lines)if __name__ == "__main__":demo.launch()123454 unmodified lines101112131415161718192021222324252627282953 unmodified lines838485868788899091929368 unmodified lines162163164165166167168169170171172173174153 unmodified lines32832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336482 unmodified lines447448449450import gradio as grfrom transformers import AutoTokenizer, AutoModel, BertModel, AutoModelForSequenceClassificationimport torchimport osimport json4 unmodified lines# Конфигурация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" # Меняем задачу на feature-extraction}}53 unmodified linesprint(f"Loading {model_type} model...")self.tokenizers[model_type] = AutoTokenizer.from_pretrained(config['name'])if config['task'] == "feature-extraction":if model_type == 'context':# Используем BertModel для контекстной модели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")68 unmodified linesmodel = 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()153 unmodified linesreturn 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():82 unmodified lines)if __name__ == "__main__":demo.launch()
app.py+47-12