Spaces:
Sleeping
Sleeping
Update app.py
Browse files24 unmodified lines2526272829303132333435363738394041424344454647484950515230 unmodified lines8384858687888990919293949530 unmodified lines1261271281291301311321331341354 unmodified lines140141142143144145146147148149150151152119 unmodified lines2722732742752762772782792802812822832842852862872882892902912922932942952962972982993003016 unmodified lines30830931031131231331431531631731831932032124 unmodified lines# Промпты для Saiga2GPT_PROMPTS = {'find_quotes': """Задача: найти эмоционально значимые цитаты в тексте.Инструкция:1. Найди цитаты, которые содержат яркие эмоции или важные мысли2. Каждая цитата должна быть самодостаточной3. Выдели только сами цитаты, по одной на строку4. Не добавляй пояснений и нумерацииТекст:{text}Цитаты:""",'analyze_context': """Задача: найти связанные по смыслу и эмоциям части текста.Инструкция:1. Определи части текста, связанные общей темой или эмоцией2. Выдели только сами фрагменты текста3. Раздели фрагменты переносом строкиТекст:{text}Фрагменты:"""}EMOTION_TRANSLATION = {30 unmodified linesANALYSIS_PARAMS = {'min_block_words': 3,'emotion_threshold': 0.3,'top_n_quotes': 3,'neutral_threshold': 0.9,'max_length': 2048,'temperature': 0.7,'top_p': 0.95,'top_k': 50}class GPTQuoteExtractor:30 unmodified linesdef extract_quotes(self, text):try:prompt = GPT_PROMPTS['find_quotes'].format(text=text)inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True,max_length=ANALYSIS_PARAMS['max_length'])inputs = {k: v.to(self.device) for k, v in inputs.items()}with torch.no_grad():outputs = self.model.generate(inputs['input_ids'],4 unmodified linestop_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:119 unmodified linesdef 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()return self._format_results(quote_analyses)def preprocess_text(self, text):lines = []for line in text.split('\n'):line = line.strip()6 unmodified linesre.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 _format_results(self, quote_analyses):results = {24 unmodified lines252627282930313233343536373839404142434430 unmodified lines75767778798081828384858687888930 unmodified lines1201211221231241251261271281291301311324 unmodified lines137138139140141142143144145146147148149150151152153154155156157158119 unmodified lines2782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213226 unmodified lines32933033133233333433533633733833934034134234334424 unmodified lines# Промпты для Saiga2GPT_PROMPTS = {'find_quotes': """Задача: найти эмоциональные цитаты в тексте.Инструкция:1. Внимательно прочитай текст2. Найди фрагменты, где есть сильные эмоции: радость, грусть, гнев, страх, любовь, тоска3. Выбери цитаты длиной от 10 до 100 слов4. Каждая цитата должна содержать законченную мысль5. Верни только сами цитаты, каждую с новой строки6. Не добавляй комментарии или нумерациюТекст:{text}Цитаты:""",}EMOTION_TRANSLATION = {30 unmodified linesANALYSIS_PARAMS = {'min_block_words': 3,'emotion_threshold': 0.25, # Снизим порог'top_n_quotes': 5, # Увеличим количество цитат'neutral_threshold': 0.8, # Снизим порог нейтральности'max_length': 2048,'temperature': 0.8, # Увеличим креативность'top_p': 0.9,'top_k': 40,'min_quote_length': 10, # Минимальная длина цитаты в словах'max_quote_length': 100 # Максимальная длина цитаты в словах}class GPTQuoteExtractor:30 unmodified linesdef extract_quotes(self, text):try:prompt = GPT_PROMPTS['find_quotes'].format(text=text)print(f"Generated prompt length: {len(prompt)}")inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True,max_length=ANALYSIS_PARAMS['max_length'])inputs = {k: v.to(self.device) for k, v in inputs.items()}print("Starting generation...")with torch.no_grad():outputs = self.model.generate(inputs['input_ids'],4 unmodified linestop_k=ANALYSIS_PARAMS['top_k'],top_p=ANALYSIS_PARAMS['top_p'],temperature=ANALYSIS_PARAMS['temperature'],pad_token_id=self.tokenizer.eos_token_id,repetition_penalty=1.2 # Добавим штраф за повторения)print("Generation completed")generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)quotes_text = generated_text.split("Цитаты:")[-1].strip()# Фильтруем и проверяем цитатыquotes = []for q in quotes_text.split('\n'):q = q.strip()if q and len(q.split()) >= ANALYSIS_PARAMS['min_quote_length']:quotes.append(q)print(f"Extracted {len(quotes)} valid quotes")return quotesexcept Exception as e:119 unmodified linesdef analyze_text(self, text):cleaned_text = self.preprocess_text(text)print(f"Preprocessed text length: {len(cleaned_text)} characters")# Получаем цитаты с помощью GPTprint("Starting quote extraction...")quotes = self.gpt_extractor.extract_quotes(cleaned_text)if not quotes:print("No quotes were extracted by the model")return self._empty_result()print(f"Found {len(quotes)} quotes:")for i, quote in enumerate(quotes, 1):print(f"Quote {i}: {quote[:100]}...")# Анализируем каждую цитатуquote_analyses = []for i, quote in enumerate(quotes, 1):print(f"\nAnalyzing quote {i}...")analysis = self.analyzer.analyze_text_block(quote)if analysis and analysis['emotions']:print(f"Emotions found: {analysis['emotions']}")quote_analyses.append(analysis)else:print("No emotions detected in this quote")print(f"\nSuccessfully analyzed {len(quote_analyses)} quotes")if not quote_analyses:print("No emotional quotes found")return self._empty_result()return self._format_results(quote_analyses)def preprocess_text(self, text):if not text or len(text.strip()) < 10:print("Input text is too short or empty")return ""print(f"Original text length: {len(text)} characters")lines = []for line in text.split('\n'):line = line.strip()6 unmodified linesre.match(r'^\[.*\]$', line)]):continuecleaned_line = re.sub(r'[^а-яА-ЯёЁ0-9\s.!?,\-]', '', line)cleaned_line = re.sub(r'\s+', ' ', cleaned_line).strip()if cleaned_line and len(cleaned_line.split()) >= ANALYSIS_PARAMS['min_block_words']:lines.append(cleaned_line)result = '\n'.join(lines)print(f"Preprocessed text length: {len(result)} characters")return resultdef _format_results(self, quote_analyses):results = {
app.py+65-42