Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Query, HTTPException
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import requests
|
| 5 |
+
from io import StringIO
|
| 6 |
+
|
| 7 |
+
app = FastAPI(title="IAPI", version="1.0.0")
|
| 8 |
+
|
| 9 |
+
app.add_middleware(
|
| 10 |
+
CORSMiddleware,
|
| 11 |
+
allow_origins=["*"],
|
| 12 |
+
allow_methods=["*"],
|
| 13 |
+
allow_headers=["*"],
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
DATA_URL = "https://raw.githubusercontent.com/live-by-unix/iapi-csv/refs/heads/main/iapi_data.csv"
|
| 17 |
+
|
| 18 |
+
def load_database():
|
| 19 |
+
try:
|
| 20 |
+
response = requests.get(DATA_URL)
|
| 21 |
+
response.raise_for_status()
|
| 22 |
+
return pd.read_csv(StringIO(response.text))
|
| 23 |
+
except Exception:
|
| 24 |
+
return pd.DataFrame(columns=["category", "title", "content"])
|
| 25 |
+
|
| 26 |
+
df = load_database()
|
| 27 |
+
|
| 28 |
+
@app.get("/")
|
| 29 |
+
async def root():
|
| 30 |
+
return {
|
| 31 |
+
"name": "IAPI",
|
| 32 |
+
"records": len(df),
|
| 33 |
+
"license": "CC BY-SA 4.0",
|
| 34 |
+
"attribution": "Data sourced from Wikipedia editors",
|
| 35 |
+
"status": "Online"
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
@app.get("/category/{category_name}")
|
| 39 |
+
async def get_category(category_name: str):
|
| 40 |
+
subset = df[df['category'].str.lower() == category_name.lower()]
|
| 41 |
+
if subset.empty:
|
| 42 |
+
raise HTTPException(status_code=404, detail="Category not found")
|
| 43 |
+
return subset.to_dict(orient="records")
|
| 44 |
+
|
| 45 |
+
@app.get("/search")
|
| 46 |
+
async def search(q: str = Query(..., min_length=2)):
|
| 47 |
+
mask = df['title'].str.contains(q, case=False, na=False) | \
|
| 48 |
+
df['content'].str.contains(q, case=False, na=False)
|
| 49 |
+
results = df[mask]
|
| 50 |
+
return results.to_dict(orient="records")
|
| 51 |
+
|
| 52 |
+
@app.get("/article/random")
|
| 53 |
+
async def get_random():
|
| 54 |
+
if df.empty:
|
| 55 |
+
raise HTTPException(status_code=503, detail="Database unavailable")
|
| 56 |
+
return df.sample(1).to_dict(orient="records")[0]
|
| 57 |
+
|
| 58 |
+
@app.get("/meta/stats")
|
| 59 |
+
async def get_stats():
|
| 60 |
+
return df['category'].value_counts().to_dict()
|