Spaces:
Sleeping
Sleeping
Update app.py
Browse files12 unmodified lines1314151617181920212223154 unmodified lines17817918018118218318486 unmodified lines27127227327427527627751 unmodified lines3293303313323333343352 unmodified lines33833934034134234334434534634734834935028 unmodified lines37938038138238338438538638738838939039112 unmodified lines# Загрузка модели для контекстных эмбеддинговsentence_model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')# Загрузка RuGPT3Large модели и токенизатора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)# Конфигурация моделейMODELS = {'emotion': {154 unmodified linesdef analyze_text_with_rugpt(text):try:inputs = rugpt_tokenizer(text, return_tensors="pt", truncation=True, max_length=512)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)86 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']]51 unmodified linesdef 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:28 unmodified linesdemo = gr.Interface(fn=analyze_files,inputs=gr.File(label="Загрузите .txt файлы", file_count="multiple", type="filepath"),outputs=[gr.File(label="Результаты анализа"),gr.Textbox(label="Анализ LLaMA") # Добавляем текстовое поле для анализа LLaMA],title="Анализ эмоций в тексте",description="Загрузите текстовые файлы для анализа эмоций и настроения.")if __name__ == "__main__":demo.launch()12 unmodified lines131415161718192021222324252627154 unmodified lines18218318418518618718886 unmodified lines27527627727827928028151 unmodified lines3333343353363373382 unmodified lines34134234334434534634734834928 unmodified lines37837938038138238338438538612 unmodified lines# Загрузка модели для контекстных эмбеддинговsentence_model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')# Загрузка RuGPT модели и токенизатораrugpt_model_name = "ai-forever/rugpt3large_based_on_gpt2" # Модель RuGPTrugpt_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)# Конфигурация моделейMODELS = {'emotion': {154 unmodified linesdef 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)86 unmodified lines'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']]51 unmodified linesdef 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:28 unmodified linesdemo = gr.Interface(fn=analyze_files,inputs=gr.File(label="Загрузите .txt файлы", file_count="multiple", type="filepath"),outputs=gr.File(label="Результаты анализа"),title="Анализ эмоций в тексте",description="Загрузите текстовые файлы для анализа эмоций и настроения.")if __name__ == "__main
app.py+11-16