Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Query, HTTPException
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
import wikipedia
|
| 4 |
+
|
| 5 |
+
app = FastAPI(title="Wikipedia URL Finder")
|
| 6 |
+
|
| 7 |
+
@app.get("/")
|
| 8 |
+
async def get_wikipedia_url(topic: str = Query(..., description="Topic to search on Wikipedia")):
|
| 9 |
+
try:
|
| 10 |
+
# Get the exact page for the topic
|
| 11 |
+
page = wikipedia.page(topic, auto_suggest=False)
|
| 12 |
+
return JSONResponse(content={"topic": page.title, "url": page.url})
|
| 13 |
+
except wikipedia.DisambiguationError as e:
|
| 14 |
+
suggestion = e.options[0] if e.options else None
|
| 15 |
+
raise HTTPException(status_code=400, detail=f"Disambiguation error. Try: {suggestion}")
|
| 16 |
+
except wikipedia.PageError:
|
| 17 |
+
raise HTTPException(status_code=404, detail="Page not found.")
|
| 18 |
+
except Exception as e:
|
| 19 |
+
raise HTTPException(status_code=500, detail=str(e))
|