Spaces:
Running
Running
from fastapi import FastAPI, HTTPException | |
from fastapi.middleware.cors import CORSMiddleware | |
from pydantic import BaseModel | |
from googlesearch import search | |
import uvicorn | |
app = FastAPI(title="HuggingFace Search Worker") | |
# Enable CORS | |
app.add_middleware( | |
CORSMiddleware, | |
allow_origins=["*"], | |
allow_credentials=True, | |
allow_methods=["*"], | |
allow_headers=["*"], | |
) | |
class SearchQuery(BaseModel): | |
query: str | |
num_results: int = 10 # Default to 10 results | |
class SearchResult(BaseModel): | |
url: str | |
position: int | |
def read_root(): | |
return {"status": "ok", "message": "Search Worker is running"} | |
def perform_search(search_query: SearchQuery): | |
try: | |
results = [] | |
for i, url in enumerate(search(search_query.query, num_results=search_query.num_results)): | |
results.append({"url": url, "position": i + 1}) | |
return {"query": search_query.query, "results": results} | |
except Exception as e: | |
raise HTTPException(status_code=500, detail=f"Search error: {str(e)}") | |
if __name__ == "__main__": | |
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True) |