agent3 / app.py
MrBro123's picture
Update app.py
ceb650b verified
Raw History Blame Contribute Delete
13.6 kB
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 = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AGENT-3 :: Naqi Qreatives :: HF Engine</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* Base Styling */
body { background-color: #000000; color: white; font-family: 'Inter', sans-serif; overflow-x: hidden; }
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-thumb { background-color: rgba(168, 85, 247, 0.3); border-radius: 10px; }
/* Neon Glow Effects */
.neon-border { box-shadow: 0 0 15px rgba(168, 85, 247, 0.4), 0 0 5px rgba(168, 85, 247, 0.2); border-color: rgba(168, 85, 247, 0.3); }
.neon-text { text-shadow: 0 0 10px rgba(168, 85, 247, 0.6); }
.neon-glow { background-color: rgba(168, 85, 247, 0.1); border-color: rgba(168, 85, 247, 0.2); }
/* Glassmorphism */
.glass { background: rgba(255, 255, 255, 0.02); backdrop-filter: blur(15px); border: 1px solid rgba(255, 255, 255, 0.05); }
/* Animations */
@keyframes pulse-slow { 0%, 100% { opacity: 0.15; } 50% { opacity: 0.25; } }
.animate-pulse-slow { animation: pulse-slow 8s infinite; }
.animate-in { animation: slideIn 0.5s ease-out; }
@keyframes slideIn { from { transform: translateY(10px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
/* Custom Styles for inputs/buttons */
.input-dark { background-color: rgba(0, 0, 0, 0.6); border: 1px solid rgba(255, 255, 255, 0.1); transition: all 0.3s; }
.input-dark:focus { border-color: rgba(168, 85, 247, 0.6); box-shadow: 0 0 10px rgba(168, 85, 247, 0.3); outline: none; }
.btn-execute { background: linear-gradient(135deg, #a855f7, #60a5fa); transition: all 0.3s; color: white; font-weight: 800; }
.btn-execute:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(168, 85, 247, 0.5); }
.btn-execute:active { transform: translateY(1px); }
</style>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;800;900&display=swap" rel="stylesheet">
</head>
<body class="p-4 md:p-8 selection:bg-purple-500/20">
<div class="fixed inset-0 pointer-events-none z-0">
<div class="absolute top-[-15%] left-[-10%] w-[55%] h-[55%] bg-purple-900 blur-[130px] rounded-full animate-pulse-slow"></div>
<div class="absolute bottom-[-15%] right-[-10%] w-[55%] h-[55%] bg-blue-900 blur-[130px] rounded-full animate-pulse-slow"></div>
</div>
<main class="relative z-10 max-w-3xl mx-auto mt-8 md:mt-16">
<header class="flex items-center gap-5 mb-12">
<div class="p-4 glass rounded-2xl neon-border shadow-lg">
<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-purple-400">
<rect x="4" y="4" width="16" height="16" rx="2" ry="2"/>
<rect x="9" y="9" width="6" height="6"/>
<line x1="9" y1="1" x2="9" y2="4"/>
<line x1="15" y1="1" x2="15" y2="4"/>
<line x1="9" y1="20" x2="9" y2="23"/>
<line x1="15" y1="20" x2="15" y2="23"/>
<line x1="20" y1="9" x2="23" y2="9"/>
<line x1="20" y1="15" x2="23" y2="15"/>
<line x1="1" y1="9" x2="4" y2="9"/>
<line x1="1" y1="15" x2="4" y2="15"/>
</svg>
</div>
<div>
<h1 class="text-4xl md:text-5xl font-extrabold italic tracking-tighter neon-text">
AGENT<span class="text-gray-500 font-light">-</span>3
<span class="text-sm font-mono text-purple-400 border border-purple-400/20 px-2.5 py-1 rounded-full uppercase tracking-widest ml-3">v1.0 // hf</span>
</h1>
<p class="text-gray-500 text-xs font-mono tracking-widest uppercase mt-1">Naqi Qreatives Neural Extraction Engine</p>
</div>
</header>
<div class="backdrop-blur-3xl glass neon-glow rounded-3xl p-8 md:p-10 shadow-[0_0_40px_rgba(0,0,0,0.5)] space-y-9">
<div class="animate-in" style="animation-delay: 0.1s;">
<label class="flex items-center gap-2.5 text-xs font-mono text-purple-300 uppercase mb-3 block tracking-widest">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
Scraper: Command Target URL
</label>
<input id="url" type="text" placeholder="https://intel-target.com" class="input-dark w-full rounded-2xl p-5 text-sm font-light text-gray-200">
</div>
<div class="animate-in" style="animation-delay: 0.2s;">
<label class="flex items-center gap-2.5 text-xs font-mono text-blue-300 uppercase mb-3 block tracking-widest">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
Analysis: Local Document Upload
</label>
<div class="relative group border-2 border-dashed border-white/5 group-hover:border-blue-500/30 rounded-2xl p-10 transition-all bg-white/[0.005] text-center cursor-pointer">
<input id="file" type="file" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10" onchange="updateFileName(this)">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="mx-auto text-gray-600 group-hover:text-blue-400 mb-4 transition-colors">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>
</svg>
<p id="fileName" class="text-sm text-gray-500 group-hover:text-gray-300 font-medium transition-colors">Drag & Drop or Click to attach (PDF/TXT)</p>
</div>
</div>
<div class="animate-in" style="animation-delay: 0.3s;">
<button onclick="runAgent()" id="btn" class="btn-execute w-full rounded-2xl p-5 flex items-center justify-center gap-3 active:scale-[0.98]">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="22" y1="2" x2="11" y2="13"/><polyline points="22 2 15 22 11 13 2 9 22 2"/></svg>
<span id="btnText">EXECUTE AGENT SYSTEM</span>
</button>
</div>
</div>
<div id="outputContainer" class="hidden mt-10 backdrop-blur-3xl glass neon-glow rounded-3xl p-8 md:p-10 shadow-2xl animate-in">
<div class="flex items-center gap-3 text-green-400 mb-6 font-mono text-xs uppercase tracking-widest neon-text">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/></svg>
Extraction_Log_v1.0.cfg: // GROQ Analysis Complete
</div>
<div id="output" class="text-gray-300 leading-relaxed font-light text-sm whitespace-pre-wrap selection:bg-green-500/20 font-sans">
// System Status: Initializing Neural Extraction...
</div>
</div>
</main>
<footer class="mt-20 text-center text-gray-700 text-xs font-mono tracking-widest animate-in" style="animation-delay: 0.5s;">
&copy; 2026 NAQI QREATIVES // ALL RIGHTS RESERVED // POWERED BY GROQ & HF_ENGINE // v1.0
</footer>
<script>
function updateFileName(input) {
const fileNameDisplay = document.getElementById('fileName');
if (input.files && input.files[0]) {
fileNameDisplay.innerText = "Attached: " + input.files[0].name;
fileNameDisplay.classList.remove('text-gray-500');
fileNameDisplay.classList.add('text-blue-300');
}
}
async function runAgent() {
const urlInput = document.getElementById('url').value;
const fileInput = document.getElementById('file').files[0];
const btnText = document.getElementById('btnText');
const outputContainer = document.getElementById('outputContainer');
const output = document.getElementById('output');
const btn = document.getElementById('btn');
if (!urlInput && !fileInput) {
alert("Jani, at least give a URL or upload a file first!");
return;
}
// Start Processing State
btnText.innerText = "PROCESSING EXTRACTION...";
btn.disabled = true;
outputContainer.classList.remove('hidden');
output.innerText = "// Connecting Neural Link... // Scrambling Data... // Groq LLM Engaged...\\n\\nAnalyzing target...";
const formData = new FormData();
if(urlInput) formData.append('url', urlInput);
if(fileInput) formData.append('file', fileInput);
try {
const res = await fetch('/process', { method: 'POST', body: formData });
if (!res.ok) throw new Error("Backend connection failed.");
const data = await res.json();
// Clear output and animate new content
output.innerText = "";
let aiResponse = data.ai_answer || "// Extraction failed: No intelligible data received from the LLM.";
output.innerText = aiResponse;
// Reset Button
btnText.innerText = "EXECUTE AGENT SYSTEM";
btn.disabled = false;
} catch (e) {
output.innerText = "// ERROR: UNABLE TO CONNECT TO AGENT BACKEND.\\n// HF Space might be sleeping or the request timed out.";
btnText.innerText = "EXECUTE AGENT SYSTEM";
btn.disabled = false;
}
}
</script>
</body>
</html>
"""
@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)