Spaces:
Sleeping
Sleeping
Update app.py
Browse files123453 unmodified lines9101112131415161718192021109 unmodified lines13113213313413513613713813914014114214314414529 unmodified lines17517617717817918079 unmodified lines26026126226326426526649 unmodified lines3163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553562 unmodified lines35936036136236336436536636730 unmodified lines398399400401402403404import gradio as grfrom transformers import AutoTokenizer, AutoModel, BertModel, AutoModelForSequenceClassificationimport torchimport osimport json3 unmodified linesfrom sklearn.cluster import DBSCANfrom sklearn.metrics.pairwise import cosine_similarityfrom sentence_transformers import SentenceTransformerimport openai# Загрузка модели для контекстных эмбеддинговsentence_model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')# Конфигурация OpenAIopenai.api_key = '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' # Замените на ваш API ключ OpenAI# Конфигурация моделейMODELS = {109 unmodified linesfiltered_emotions.extend(additional_emotions)final_emotions = filtered_emotions if filtered_emotions else emotions# Анализ текста с помощью OpenAIopenai_analysis = analyze_text_with_openai(text_block)return {'text': text_block,'emotions': final_emotions,'sentiment': self._analyze_sentiment(text_block),'context_embedding': self._get_context_embedding(text_block),'openai_analysis': openai_analysis # Добавляем результат анализа OpenAI}except Exception as e:print(f"Ошибка при анализе блока: {str(e)}")29 unmodified linesdef _get_context_embedding(self, text):return sentence_model.encode(text)class TextBlockAnalyzer:def __init__(self):self.analyzer = TextAnalyzer()79 unmodified lines'score': primary_emotion['score'],'sentiment': block['sentiment'],'all_emotions': emotions[:3],'openai_analysis': block.get('openai_analysis', None) # Добавляем анализ OpenAI})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']]49 unmodified lines})return clusters_infodef analyze_with_openai(text):try:response = openai.Completion.create(engine="text-davinci-003", # или "gpt-4", если у вас есть доступprompt=text,max_tokens=100,temperature=0.7,top_p=1.0,frequency_penalty=0.0,presence_penalty=0.0)return response.choices[0].text.strip()except Exception as e:print(f"Ошибка при вызове OpenAI API: {str(e)}")return Nonedef analyze_text_with_openai(text):prompt = f"Проанализируй текст и выдели основные эмоции и настроения:\n{text}\n\nЭмоции:"try:response = openai.Completion.create(engine="text-davinci-003",prompt=prompt,max_tokens=150,temperature=0.5,top_p=1.0,frequency_penalty=0.0,presence_penalty=0.0)return response.choices[0].text.strip()except Exception as e:print(f"Ошибка при вызове OpenAI API: {str(e)}")return Nonedef analyze_files(file_paths):result_files = []for file_path in file_paths:try:with open(file_path, 'r', encoding='utf-8') as f:2 unmodified linesresult_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:30 unmodified linesinputs=gr.File(label="Загрузите .txt файлы", file_count="multiple", type="filepath"),outputs=[gr.File(label="Результаты анализа"),gr.Textbox(label="Анализ OpenAI") # Добавляем текстовое поле для анализа OpenAI],title="Анализ эмоций в тексте",description="Загрузите текстовые файлы для анализа эмоций и настроения."123453 unmodified lines910111213141516171819202122109 unmodified lines13213313413513613713813914014114214314414514629 unmodified lines17617717817918018118218318418518618718818919019179 unmodified lines27127227327427527627749 unmodified lines3273283293303313323333343352 unmodified lines33833934034134234334434534634734834935030 unmodified lines381382383384385386387import gradio as grfrom transformers import AutoTokenizer, AutoModelForCausalLM, BertModel, AutoModel, AutoModelForSequenceClassificationimport torchimport osimport json3 unmodified linesfrom sklearn.cluster import DBSCANfrom sklearn.metrics.pairwise import cosine_similarityfrom sentence_transformers import SentenceTransformer# Загрузка модели для контекстных эмбеддинговsentence_model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')# Загрузка LLaMA модели и токенизатораllama_model_name = "meta-llama/Llama-2-7b-chat-hf" # Пример модели LLaMAllama_tokenizer = AutoTokenizer.from_pretrained(llama_model_name)llama_model = AutoModelForCausalLM.from_pretrained(llama_model_name)# Конфигурация моделейMODELS = {109 unmodified linesfiltered_emotions.extend(additional_emotions)final_emotions = filtered_emotions if filtered_emotions else emotions# Анализ текста с помощью LLaMAllama_analysis = analyze_text_with_llama(text_block)return {'text': text_block,'emotions': final_emotions,'sentiment': self._analyze_sentiment(text_block),'context_embedding': self._get_context_embedding(text_block),'llama_analysis': llama_analysis # Добавляем результат анализа LLaMA}except Exception as e:print(f"Ошибка при анализе блока: {str(e)}")29 unmodified linesdef _get_context_embedding(self, text):return sentence_model.encode(text)def analyze_text_with_llama(text):try:inputs = llama_tokenizer(text, return_tensors="pt", truncation=True, max_length=512)with torch.no_grad():outputs = llama_model.generate(**inputs, max_length=100, num_return_sequences=1)return llama_tokenizer.decode(outputs[0], skip_special_tokens=True)except Exception as e:print(f"Ошибка при вызове LLaMA: {str(e)}")return Noneclass TextBlockAnalyzer:def __init__(self):self.analyzer = TextAnalyzer()79 unmodified lines'score': primary_emotion['score'],'sentiment': block['sentiment'],'all_emotions': emotions[:3],'llama_analysis': block.get('llama_analysis', None) # Добавляем анализ LLaMA})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']]49 unmodified lines})return clusters_infodef analyze_files(file_paths):result_files = []openai_results = []for file_path in file_paths:try:with open(file_path, 'r', encoding='utf-8') as f:2 unmodified linesresult_path = analyze_text_file(text, file_name)if result_path:result_files.append(result_path)# Добавляем результат анализа LLaMAllama_analysis = analyze_text_with_llama(text)openai_results.append(llama_analysis)except Exception as e:print(f"Ошибка при обработке файла {file_name}: {str(e)}")# Возвращаем два значения: файл и текстовый результатreturn result_files, "\n".join(openai_results)def analyze_text_file(text, original_file_name):try:30 unmodified linesinputs=gr.File(label="Загрузите .txt файлы", file_count="multiple", type="filepath"),outputs=[gr.File(label="Результаты анализа"),gr.Textbox(label="Анализ LLaMA") # Добавляем текстовое поле для анализа LLaMA],title="Анализ эмоций в тексте",description="Загрузите текстовые файлы для анализа эмоций и настроения."
app.py+26-43