Spaces:
Runtime error
Runtime error
Delete main.py
Browse files
main.py
DELETED
|
@@ -1,97 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import re
|
| 3 |
-
import jwt
|
| 4 |
-
import faiss
|
| 5 |
-
import time
|
| 6 |
-
import numpy as np
|
| 7 |
-
import requests
|
| 8 |
-
from datetime import datetime, timedelta
|
| 9 |
-
from fastapi import FastAPI, Depends, HTTPException, status
|
| 10 |
-
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 11 |
-
from pydantic import BaseModel, validator
|
| 12 |
-
from sentence_transformers import SentenceTransformer
|
| 13 |
-
from typing import List
|
| 14 |
-
|
| 15 |
-
# --- SETTINGS ---
|
| 16 |
-
SECRET_KEY = "352f67b35a544f408c58c74c654cfd7e"
|
| 17 |
-
ALGORITHM = "HS256"
|
| 18 |
-
ACCESS_TOKEN_EXPIRE_MINUTES = 60
|
| 19 |
-
NEWS_API_KEY = os.getenv("NEWS_API_KEY")
|
| 20 |
-
security = HTTPBearer()
|
| 21 |
-
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 22 |
-
|
| 23 |
-
app = FastAPI(title="Finance News API", version="2.0.0")
|
| 24 |
-
|
| 25 |
-
# --- AUTH MODELS ---
|
| 26 |
-
class LoginSchema(BaseModel):
|
| 27 |
-
username: str
|
| 28 |
-
password: str
|
| 29 |
-
|
| 30 |
-
class QuerySchema(BaseModel):
|
| 31 |
-
query: str
|
| 32 |
-
|
| 33 |
-
@validator("query")
|
| 34 |
-
def sanitize_query(cls, v):
|
| 35 |
-
if not re.match("^[a-zA-Z0-9 .,!?()-]+$", v):
|
| 36 |
-
raise ValueError("Invalid characters in query")
|
| 37 |
-
return v
|
| 38 |
-
|
| 39 |
-
# --- JWT UTILS ---
|
| 40 |
-
def create_access_token(data: dict):
|
| 41 |
-
to_encode = data.copy()
|
| 42 |
-
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
| 43 |
-
to_encode.update({"exp": expire})
|
| 44 |
-
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 45 |
-
|
| 46 |
-
def get_current_user(token: HTTPAuthorizationCredentials = Depends(security)):
|
| 47 |
-
try:
|
| 48 |
-
payload = jwt.decode(token.credentials, SECRET_KEY, algorithms=[ALGORITHM])
|
| 49 |
-
return payload.get("sub")
|
| 50 |
-
except jwt.ExpiredSignatureError:
|
| 51 |
-
raise HTTPException(status_code=401, detail="Token expired")
|
| 52 |
-
except:
|
| 53 |
-
raise HTTPException(status_code=401, detail="Invalid token")
|
| 54 |
-
|
| 55 |
-
# --- LOGIN ---
|
| 56 |
-
@app.post("/login")
|
| 57 |
-
def login(data: LoginSchema):
|
| 58 |
-
if data.username == "admin" and data.password == "admin123":
|
| 59 |
-
token = create_access_token({"sub": data.username})
|
| 60 |
-
return {"access_token": token}
|
| 61 |
-
raise HTTPException(status_code=401, detail="Invalid login")
|
| 62 |
-
|
| 63 |
-
# --- NEWS FETCH ---
|
| 64 |
-
def fetch_news():
|
| 65 |
-
url = f"https://newsapi.org/v2/everything?q=india finance&apiKey={NEWS_API_KEY}"
|
| 66 |
-
r = requests.get(url)
|
| 67 |
-
articles = r.json().get("articles", [])[:20]
|
| 68 |
-
corpus = [a["title"] + " " + (a["description"] or "") for a in articles]
|
| 69 |
-
return articles, corpus
|
| 70 |
-
|
| 71 |
-
# --- VECTOR STORE ---
|
| 72 |
-
articles, corpus = fetch_news()
|
| 73 |
-
embeddings = model.encode(corpus)
|
| 74 |
-
dimension = embeddings.shape[1]
|
| 75 |
-
index = faiss.IndexFlatL2(dimension)
|
| 76 |
-
index.add(embeddings)
|
| 77 |
-
|
| 78 |
-
# --- SEARCH ---
|
| 79 |
-
def semantic_search(query: str, k: int = 5):
|
| 80 |
-
q_vec = model.encode([query])
|
| 81 |
-
distances, indices = index.search(q_vec, k)
|
| 82 |
-
|
| 83 |
-
return [articles[i] for i in indices[0] if i < len(articles)]
|
| 84 |
-
|
| 85 |
-
# --- SECURE QUERY ENDPOINT ---
|
| 86 |
-
@app.post("/secure-search")
|
| 87 |
-
def secure_search(
|
| 88 |
-
payload: QuerySchema,
|
| 89 |
-
user: str = Depends(get_current_user)
|
| 90 |
-
):
|
| 91 |
-
results = semantic_search(payload.query)
|
| 92 |
-
return {"results": results, "user": user}
|
| 93 |
-
|
| 94 |
-
# --- HEALTH ---
|
| 95 |
-
@app.get("/health")
|
| 96 |
-
def health():
|
| 97 |
-
return {"status": "OK", "faiss": index.ntotal}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|