import os from fastapi import FastAPI, Request, UploadFile, File, Form, HTTPException from fastapi.responses import HTMLResponse from fastapi.middleware.cors import CORSMiddleware from langchain_groq import ChatGroq import uvicorn import requests from bs4 import BeautifulSoup import io app = FastAPI() # 1. Groq Setup (ApiKey ENV se uthayega) try: llm = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"), model_name="llama3-70b-8192") except Exception as e: llm = None print(f"Error initializing Groq: {e}") # 2. CORS (Internal requests ke liye zaruri nahi, lekin safety ke liye) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) # 3. Simple Web Scraper Function def simple_scrape(url): try: response = requests.get(url, timeout=10) soup = BeautifulSoup(response.text, 'html.parser') # Sirf main text nikalte hain (headers, paragraphs, lists) text_content = "" for element in soup.find_all(['h1', 'h2', 'h3', 'p', 'li']): text_content += element.get_text() + "\n" return text_content[:5000] # Groq ki context limit ke liye chunking except Exception as e: return f"Error scraping URL: {str(e)}" # --- FRONTEND (Hugging Face Special Edition - No Vercel Needed) --- html_content = """ AGENT-3 :: Naqi Qreatives :: HF Engine

AGENT-3 v1.0 // hf

Naqi Qreatives Neural Extraction Engine

Drag & Drop or Click to attach (PDF/TXT)

""" @app.get("/", response_class=HTMLResponse) async def get_index(): return html_content @app.post("/process") async def process_data(url: str = Form(None), file: UploadFile = File(None)): if not llm: return {"ai_answer": "Error: GROQ_API_KEY is missing from environment variables."} context = "" # 1. Scrape URL if provided if url: context += f"*** SCRAPED CONTENT FROM {url} ***\\n\\n" context += simple_scrape(url) + "\\n\\n" # 2. Process File if uploaded if file: context += f"*** CONTENT FROM UPLOADED FILE: {file.filename} ***\\n\\n" try: # We read text files, but you could add PDF extraction here content = await file.read() context += content.decode('utf-8', errors='ignore')[:3000] # Chunk file content context += "\\n\\n" except Exception as e: context += f"Error reading file: {str(e)}\\n\\n" # 3. Analyze with Groq if not context: raise HTTPException(status_code=400, detail="No URL or file data provided.") system_prompt = "You are a highly advanced cyber-intelligence agent. Analyze the provided data and extract key insights, data points, or a concise summary. Use a professional, analytical tone." user_prompt = f"Data received:\\n{context}\\n\\nExtract insights:" try: response = llm.invoke(system_prompt + "\\n\\n" + user_prompt) return {"ai_answer": response.content} except Exception as e: return {"ai_answer": f"Error during Groq Analysis: {str(e)}"} if __name__ == "__main__": # Hugging Face Spaces require port 7860 uvicorn.run(app, host="0.0.0.0", port=7860)