import os import io import torch from fastapi import FastAPI, UploadFile, File, Form, HTTPException from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse from pydantic import BaseModel from transformers import AutoTokenizer, AutoModelForSequenceClassification from dotenv import load_dotenv from pypdf import PdfReader from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_groq import ChatGroq from langchain_huggingface import HuggingFaceEmbeddings from langchain_community.vectorstores import Chroma from langchain_core.prompts import PromptTemplate # 1. Path Resolution (This MUST happen first) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 2. Security & Keys dotenv_path = os.path.join(BASE_DIR, ".env") load_dotenv(dotenv_path) GROQ_API_KEY = os.getenv("GROQ_API_KEY") if not GROQ_API_KEY: print("⚠️ FATAL ERROR: GROQ_API_KEY is missing or .env file is not being read.") app = FastAPI(title="AnchorQuant API") app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"]) # ========================================== # 3. AI Model Initialization # ========================================== device = torch.device("cpu") print("Loading Native FinBERT, LLM, and Embeddings...") # PyTorch Classification Loader (Custom Weights) model_path = os.path.join(BASE_DIR, "models", "finbert_sentiment.pt") tokenizer = AutoTokenizer.from_pretrained("ProsusAI/finbert") finbert_model = AutoModelForSequenceClassification.from_pretrained("ProsusAI/finbert") # Safely inject custom trained weights try: loaded_data = torch.load(model_path, map_location=device) if isinstance(loaded_data, dict): finbert_model.load_state_dict(loaded_data) else: finbert_model = loaded_data print("✅ Custom FinBERT weights loaded successfully.") except Exception as e: print(f"⚠️ ERROR LOADING CUSTOM WEIGHTS: {e}") print("Falling back to base ProsusAI model.") finbert_model.to(device) finbert_model.eval() # LLM & RAG llm = ChatGroq( temperature=0.1, model_name="llama-3.3-70b-versatile", api_key=GROQ_API_KEY ) embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2") vector_store = Chroma(embedding_function=embeddings) class StatementRequest(BaseModel): text: str class ChatRequest(BaseModel): query: str context: str = "" # Used for Flow B statement context # ========================================== # FLOW B: Quick Statement (FinBERT Only) # ========================================== @app.post("/predict/statement") def analyze_statement(request: StatementRequest): inputs = tokenizer(request.text, padding=True, truncation=True, max_length=128, return_tensors='pt').to(device) with torch.no_grad(): outputs = finbert_model(**inputs) prediction = torch.argmax(outputs.logits, dim=-1).item() mapping = {0: "Bullish", 1: "Bearish", 2: "Neutral"} return {"text": request.text, "sentiment": mapping[prediction]} # ========================================== # FLOW A: Document Pipeline (Multi-Model RAG) # ========================================== @app.post("/analyze/document") async def analyze_document(file: UploadFile = File(None), text_block: str = Form(None)): global vector_store extracted_text = "" if file: if not file.filename.endswith('.pdf'): raise HTTPException(status_code=400, detail="Only PDF files are supported.") pdf_bytes = await file.read() pdf_reader = PdfReader(io.BytesIO(pdf_bytes)) for page in pdf_reader.pages: extracted_text += page.extract_text() + "\n" elif text_block: extracted_text = text_block else: raise HTTPException(status_code=400, detail="Provide a PDF or text block.") # 1. Chunking splitter = RecursiveCharacterTextSplitter(chunk_size=600, chunk_overlap=100) chunks = splitter.split_text(extracted_text) # 2. Run FinBERT on chunks & build Vector DB payload analyzed_chunks = [] tagged_chunks_for_db = [] bullish_texts = [] bearish_texts = [] mapping = {0: "Bullish", 1: "Bearish", 2: "Neutral"} for chunk in chunks: inputs = tokenizer(chunk, padding=True, truncation=True, max_length=128, return_tensors='pt').to(device) with torch.no_grad(): outputs = finbert_model(**inputs) sentiment = mapping[torch.argmax(outputs.logits, dim=-1).item()] # Keep original clean text for the UI Heatmap analyzed_chunks.append({"text": chunk, "sentiment": sentiment}) # Inject the quantitative tag for the LLM tagged_text = f"[FINBERT QUANTITATIVE ANALYSIS: {sentiment.upper()}] {chunk}" tagged_chunks_for_db.append(tagged_text) if sentiment == "Bullish": bullish_texts.append(tagged_text) if sentiment == "Bearish": bearish_texts.append(tagged_text) # 3. Store in DB for Q&A if vector_store: try: vector_store.delete_collection() except: pass # Feed the explicitly TAGGED chunks to the Vector Database vector_store = Chroma.from_texts(texts=tagged_chunks_for_db, embedding=embeddings) # 4. LLM Executive Summary (Only feed it the extreme sentiments) summary = "Neutral document. No extreme financial divergence detected." if bullish_texts or bearish_texts: prompt = PromptTemplate.from_template( "You are a Wall Street quantitative analyst. Based ONLY on the excerpts below, write a comprehensive 3-bullet executive summary. " "Rule 1: Do not include ANY introductory or concluding conversational text. " "Rule 2: Each bullet point should be a complete sentence (20-40 words) that explains both the financial metric and its business implication.\n\n" "Bullish: {bull}\nBearish: {bear}" ) chain = prompt | llm response = chain.invoke({"bull": " ".join(bullish_texts[:3]), "bear": " ".join(bearish_texts[:3])}) summary = response.content return { "summary": summary, "chunks": analyzed_chunks } # ========================================== # FLOW C: The Chat Bridge # ========================================== @app.post("/chat") def chat_with_ai(request: ChatRequest): if request.context: # Flow B Chat: Anchored Synthesis prompt = ( f"You are a Wall Street quantitative analyst. " f"Context: '{request.context}'\n\n" f"Rule 1: Your primary data point is the provided FINBERT RATING. Anchor your analysis in this rating. " f"Rule 2: Do NOT simply agree with the user's premise. Base your argument strictly on the text. " f"Rule 3: IF the text contains nuanced context that contradicts the FinBERT rating, point out that divergence. " f"Rule 4: Provide a complete, well-reasoned answer in 1 to 2 short paragraphs. Bullet points are encouraged for readability. Cut the conversational fluff, but do not truncate your financial reasoning.\n\n" f"User asks: {request.query}" ) response = llm.invoke(prompt) return {"answer": response.content} else: # Flow A Chat: Query the Vector DB docs = vector_store.similarity_search(request.query, k=3) retrieved_context = "\n".join([d.page_content for d in docs]) prompt = ( f"You are a Wall Street financial analyst. Answer the user's question using ONLY this document context. " f"Rule 1: Be objective and anchor your analysis in the provided data. " f"Rule 2: Provide a complete, well-reasoned answer in 1 to 2 short paragraphs or use bullet points for clarity. " f"Rule 3: Cut the conversational filler, but fully explain the financial implications of your answer.\n\n" f"Context: {retrieved_context}\n\n" f"Question: {request.query}" ) response = llm.invoke(prompt) return {"answer": response.content} # Frontend Serving frontend_path = os.path.join(BASE_DIR, "frontend") app.mount("/static", StaticFiles(directory=frontend_path), name="static") @app.get("/") def read_index(): return FileResponse(os.path.join(frontend_path, "index.html")) if __name__ == "__main__": import uvicorn print("Starting Server for Hugging Face (Port 7860)...") uvicorn.run(app, host="0.0.0.0", port=7860)