import streamlit as st
import pandas as pd
import time
import matplotlib.pyplot as plt
from openpyxl.utils.dataframe import dataframe_to_rows
import io
from rapidfuzz import fuzz
import os
from openpyxl import load_workbook
from langchain.prompts import PromptTemplate
from langchain_core.runnables import RunnablePassthrough
from io import StringIO, BytesIO
import sys
import contextlib
from langchain_openai import ChatOpenAI # Updated import
import pdfkit
from jinja2 import Template
import time
from tenacity import retry, stop_after_attempt, wait_exponential
from typing import Optional
from deep_translator import GoogleTranslator
from googletrans import Translator as LegacyTranslator
import torch
from transformers import (
pipeline,
AutoModelForSeq2SeqLM,
AutoTokenizer
)
class FallbackLLMSystem:
def __init__(self):
"""Initialize fallback models for event detection and reasoning"""
try:
# Initialize MT5 model (multilingual T5)
self.model_name = "google/mt5-small"
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
self.model = AutoModelForSeq2SeqLM.from_pretrained(self.model_name)
# Set device
self.device = "cuda" if torch.cuda.is_available() else "cpu"
self.model = self.model.to(self.device)
st.success(f"Successfully initialized MT5 model on {self.device}")
except Exception as e:
st.error(f"Error initializing MT5: {str(e)}")
raise
def detect_events(self, text, entity):
"""Detect events using MT5"""
# Initialize default return values
event_type = "Нет"
summary = ""
try:
prompt = f"""Analyze news about company {entity}:
{text}
Classify event type as one of:
- Отчетность (financial reports)
- РЦБ (securities market events)
- Суд (legal actions)
- Нет (no significant events)
Format response as:
Тип: [type]
Краткое описание: [summary]"""
inputs = self.tokenizer(
prompt,
return_tensors="pt",
padding=True,
truncation=True,
max_length=512
).to(self.device)
outputs = self.model.generate(
**inputs,
max_length=200,
num_return_sequences=1,
do_sample=False,
pad_token_id=self.tokenizer.pad_token_id
)
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
# Parse response
if "Тип:" in response and "Краткое описание:" in response:
parts = response.split("Краткое описание:")
type_part = parts[0]
if "Тип:" in type_part:
event_type = type_part.split("Тип:")[1].strip()
# Validate event type
valid_types = ["Отчетность", "РЦБ", "Суд", "Нет"]
if event_type not in valid_types:
event_type = "Нет"
if len(parts) > 1:
summary = parts[1].strip()
return event_type, summary
except Exception as e:
st.warning(f"Event detection error: {str(e)}")
return "Нет", "Ошибка анализа"
def ensure_groq_llm():
"""Initialize Groq LLM for impact estimation"""
try:
if 'groq_key' not in st.secrets:
st.error("Groq API key not found in secrets. Please add it with the key 'groq_key'.")
return None
return ChatOpenAI(
base_url="https://api.groq.com/openai/v1",
model="llama-3.1-70b-versatile",
openai_api_key=st.secrets['groq_key'],
temperature=0.0
)
except Exception as e:
st.error(f"Error initializing Groq LLM: {str(e)}")
return None
def estimate_impact(llm, news_text, entity):
"""
Estimate impact using Groq LLM regardless of the main model choice.
Falls back to the provided LLM if Groq initialization fails.
"""
# Initialize default return values
impact = "Неопределенный эффект"
reasoning = "Не удалось получить обоснование"
try:
# Always try to use Groq first
groq_llm = ensure_groq_llm()
working_llm = groq_llm if groq_llm is not None else llm
template = """
You are a financial analyst. Analyze this news piece about {entity} and assess its potential impact.
News: {news}
Classify the impact into one of these categories:
1. "Значительный риск убытков" (Significant loss risk)
2. "Умеренный риск убытков" (Moderate loss risk)
3. "Незначительный риск убытков" (Minor loss risk)
4. "Вероятность прибыли" (Potential profit)
5. "Неопределенный эффект" (Uncertain effect)
Provide a brief, fact-based reasoning for your assessment.
Format your response exactly as:
Impact: [category]
Reasoning: [explanation in 2-3 sentences]
"""
prompt = PromptTemplate(template=template, input_variables=["entity", "news"])
chain = prompt | working_llm
response = chain.invoke({"entity": entity, "news": news_text})
# Extract content from response
response_text = response.content if hasattr(response, 'content') else str(response)
if "Impact:" in response_text and "Reasoning:" in response_text:
impact_part, reasoning_part = response_text.split("Reasoning:")
impact_temp = impact_part.split("Impact:")[1].strip()
# Validate impact category
valid_impacts = [
"Значительный риск убытков",
"Умеренный риск убытков",
"Незначительный риск убытков",
"Вероятность прибыли",
"Неопределенный эффект"
]
if impact_temp in valid_impacts:
impact = impact_temp
reasoning = reasoning_part.strip()
except Exception as e:
st.warning(f"Error in impact estimation: {str(e)}")
return impact, reasoning
class TranslationSystem:
def __init__(self, batch_size=5):
"""
Initialize translation system using Helsinki NLP model.
"""
try:
self.translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ru-en") # Note: ru-en for Russian to English
self.batch_size = batch_size
except Exception as e:
st.error(f"Error initializing Helsinki NLP translator: {str(e)}")
raise
def translate_text(self, text):
"""
Translate single text using Helsinki NLP model with chunking for long texts.
"""
if pd.isna(text) or not isinstance(text, str) or not text.strip():
return text
text = str(text).strip()
if not text:
return text
try:
# Helsinki NLP model typically has a max length limit
max_chunk_size = 512 # Standard transformer length
if len(text.split()) <= max_chunk_size:
# Direct translation for short texts
result = self.translator(text, max_length=512)
return result[0]['translation_text']
# Split long text into chunks by sentences
chunks = self._split_into_chunks(text, max_chunk_size)
translated_chunks = []
for chunk in chunks:
result = self.translator(chunk, max_length=512)
translated_chunks.append(result[0]['translation_text'])
time.sleep(0.1) # Small delay between chunks
return ' '.join(translated_chunks)
except Exception as e:
st.warning(f"Translation error: {str(e)}. Using original text.")
return text
def _split_into_chunks(self, text, max_length):
"""
Split text into chunks by sentences, respecting max length.
"""
# Simple sentence splitting by common punctuation
sentences = [s.strip() for s in text.replace('!', '.').replace('?', '.').split('.') if s.strip()]
chunks = []
current_chunk = []
current_length = 0
for sentence in sentences:
sentence_length = len(sentence.split())
if current_length + sentence_length > max_length:
if current_chunk:
chunks.append(' '.join(current_chunk))
current_chunk = [sentence]
current_length = sentence_length
else:
current_chunk.append(sentence)
current_length += sentence_length
if current_chunk:
chunks.append(' '.join(current_chunk))
return chunks
def process_file(uploaded_file, model_choice, translation_method=None):
df = None
try:
df = pd.read_excel(uploaded_file, sheet_name='Публикации')
llm = init_langchain_llm(model_choice)
# Add fallback initialization here
fallback_llm = FallbackLLMSystem() if model_choice != "Local-MT5" else llm
translator = TranslationSystem(batch_size=5)
# Pre-initialize Groq for impact estimation
groq_llm = ensure_groq_llm()
if groq_llm is None:
st.warning("Failed to initialize Groq LLM for impact estimation. Using fallback model.")
# Initialize all required columns first
df['Translated'] = ''
df['Sentiment'] = ''
df['Impact'] = ''
df['Reasoning'] = ''
df['Event_Type'] = ''
df['Event_Summary'] = ''
# Validate required columns
required_columns = ['Объект', 'Заголовок', 'Выдержки из текста']
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
st.error(f"Error: The following required columns are missing: {', '.join(missing_columns)}")
return None
# Deduplication
original_news_count = len(df)
df = df.groupby('Объект', group_keys=False).apply(
lambda x: fuzzy_deduplicate(x, 'Выдержки из текста', 65)
).reset_index(drop=True)
remaining_news_count = len(df)
duplicates_removed = original_news_count - remaining_news_count
st.write(f"Из {original_news_count} новостных сообщений удалены {duplicates_removed} дублирующих. Осталось {remaining_news_count}.")
# Initialize progress tracking
progress_bar = st.progress(0)
status_text = st.empty()
# Process in batches
batch_size = 5
for i in range(0, len(df), batch_size):
batch_df = df.iloc[i:i+batch_size]
for idx, row in batch_df.iterrows():
try:
# Translation with Helsinki NLP
translated_text = translator.translate_text(row['Выдержки из текста'])
df.at[idx, 'Translated'] = translated_text
# Sentiment analysis
sentiment = analyze_sentiment(translated_text)
df.at[idx, 'Sentiment'] = sentiment
try:
# Try with primary LLM
event_type, event_summary = detect_events(
llm,
row['Выдержки из текста'],
row['Объект']
)
except Exception as e:
if 'rate limit' in str(e).lower():
st.warning("Rate limit reached. Using fallback model for event detection.")
event_type, event_summary = fallback_llm.detect_events(
row['Выдержки из текста'],
row['Объект']
)
df.at[idx, 'Event_Type'] = event_type
df.at[idx, 'Event_Summary'] = event_summary
# Similar for impact estimation
if sentiment == "Negative":
try:
impact, reasoning = estimate_impact(
groq_llm if groq_llm is not None else llm,
translated_text,
row['Объект']
)
df.at[idx, 'Impact'] = impact
df.at[idx, 'Reasoning'] = reasoning
except Exception as e:
if 'rate limit' in str(e).lower():
st.warning("Groq rate limit reached. Waiting before retry...")
time.sleep(240) # Wait 4 minutes
continue
df.at[idx, 'Impact'] = impact
df.at[idx, 'Reasoning'] = reasoning
# Update progress
progress = (idx + 1) / len(df)
progress_bar.progress(progress)
status_text.text(f"Проанализировано {idx + 1} из {len(df)} новостей")
except Exception as e:
if 'rate limit' in str(e).lower():
wait_time = 240 # 4 minutes wait for rate limit
st.warning(f"Rate limit reached. Waiting {wait_time} seconds...")
time.sleep(wait_time)
continue
st.warning(f"Ошибка при обработке новости {idx + 1}: {str(e)}")
continue
# Small delay between items
time.sleep(0.5)
# Delay between batches
time.sleep(2)
return df
except Exception as e:
st.error(f"❌ Ошибка при обработке файла: {str(e)}")
return None
def translate_reasoning_to_russian(llm, text):
template = """
Translate this English explanation to Russian, maintaining a formal business style:
"{text}"
Your response should contain only the Russian translation.
"""
prompt = PromptTemplate(template=template, input_variables=["text"])
chain = prompt | llm | RunnablePassthrough()
response = chain.invoke({"text": text})
# Handle different response types
if hasattr(response, 'content'):
return response.content.strip()
elif isinstance(response, str):
return response.strip()
else:
return str(response).strip()
def create_download_section(excel_data, pdf_data):
st.markdown("""