Spaces:
Sleeping
Sleeping
| """ | |
| HuggingFace Space: Web Search | |
| Free web search using DuckDuckGo | |
| """ | |
| from fastapi import FastAPI | |
| from pydantic import BaseModel | |
| from typing import List, Optional | |
| from duckduckgo_search import DDGS | |
| app = FastAPI( | |
| title="Web Search Space", | |
| description="Free web search using DuckDuckGo" | |
| ) | |
| class SearchRequest(BaseModel): | |
| query: str | |
| max_results: int = 5 | |
| region: str = "wt-wt" # Worldwide | |
| class SearchResult(BaseModel): | |
| title: str | |
| url: str | |
| snippet: str | |
| class SearchResponse(BaseModel): | |
| query: str | |
| results: List[SearchResult] | |
| error: Optional[str] = None | |
| async def root(): | |
| return {"status": "running", "service": "web_search"} | |
| async def search(request: SearchRequest): | |
| """Search the web using DuckDuckGo""" | |
| try: | |
| results = [] | |
| with DDGS() as ddgs: | |
| for r in ddgs.text( | |
| request.query, | |
| max_results=request.max_results, | |
| region=request.region | |
| ): | |
| results.append(SearchResult( | |
| title=r.get("title", ""), | |
| url=r.get("href", ""), | |
| snippet=r.get("body", "") | |
| )) | |
| return SearchResponse( | |
| query=request.query, | |
| results=results | |
| ) | |
| except Exception as e: | |
| return SearchResponse( | |
| query=request.query, | |
| results=[], | |
| error=str(e) | |
| ) | |
| async def search_news(request: SearchRequest): | |
| """Search news articles""" | |
| try: | |
| results = [] | |
| with DDGS() as ddgs: | |
| for r in ddgs.news( | |
| request.query, | |
| max_results=request.max_results | |
| ): | |
| results.append({ | |
| "title": r.get("title", ""), | |
| "url": r.get("url", ""), | |
| "snippet": r.get("body", ""), | |
| "date": r.get("date", ""), | |
| "source": r.get("source", "") | |
| }) | |
| return {"query": request.query, "results": results} | |
| except Exception as e: | |
| return {"query": request.query, "results": [], "error": str(e)} | |
| # Gradio interface | |
| def gradio_interface(): | |
| import gradio as gr | |
| def search_wrapper(query, max_results): | |
| response = search(SearchRequest(query=query, max_results=max_results)) | |
| output = "" | |
| for i, result in enumerate(response.results, 1): | |
| output += f"**{i}. {result.title}**\n" | |
| output += f"{result.url}\n" | |
| output += f"{result.snippet}\n\n" | |
| return output or "No results found" | |
| iface = gr.Interface( | |
| fn=search_wrapper, | |
| inputs=[ | |
| gr.Textbox(label="Search Query"), | |
| gr.Slider(1, 10, value=5, label="Max Results") | |
| ], | |
| outputs=gr.Markdown(label="Results"), | |
| title="Web Search", | |
| description="Search the web using DuckDuckGo" | |
| ) | |
| return iface | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |