-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
86 lines (71 loc) · 1.93 KB
/
Copy pathapi.py
File metadata and controls
86 lines (71 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from fastapi import FastAPI
from pydantic import BaseModel
from sqlalchemy import create_engine, text
import pandas as pd
app = FastAPI()
engine = create_engine("sqlite:///./amazon.db")
class Query(BaseModel):
question: str
def generate_sql(question):
q = question.lower()
if "category" in q:
return """
SELECT category, COUNT(*) as count
FROM amazon
GROUP BY category
ORDER BY count DESC
LIMIT 10
"""
elif "total" in q:
return """
SELECT category, SUM(discounted_price) as total
FROM amazon
GROUP BY category
ORDER BY total DESC
LIMIT 10
"""
elif "rating" in q:
return """
SELECT category, AVG(rating) as avg_rating
FROM amazon
GROUP BY category
ORDER BY avg_rating DESC
LIMIT 10
"""
elif "top" in q:
return """
SELECT product_name, discounted_price
FROM amazon
ORDER BY discounted_price DESC
LIMIT 5
"""
elif "cheap" in q or "lowest" in q:
return """
SELECT product_name, discounted_price
FROM amazon
ORDER BY discounted_price ASC
LIMIT 5
"""
elif "all" in q:
return "SELECT * FROM amazon LIMIT 50"
else:
return """
SELECT category, COUNT(*) as count
FROM amazon
GROUP BY category
ORDER BY count DESC
LIMIT 10
"""
@app.post("/query")
def run_query(data: Query):
sql = generate_sql(data.question)
try:
with engine.connect() as conn:
result = conn.execute(text(sql))
df = pd.DataFrame(result.fetchall(), columns=result.keys())
return {
"sql": sql,
"data": df.to_dict()
}
except Exception as e:
return {"error": str(e)}