-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
93 lines (75 loc) · 2.86 KB
/
api.py
File metadata and controls
93 lines (75 loc) · 2.86 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
87
88
89
90
91
92
93
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional
from py_cleo.core_agent import BaseAgent
from py_cleo.exam_service import ExamService
from py_cleo.go_searcher import GoSearcher
from py_cleo.reporter import generate_question_paper_pdf
import os
import uuid
import logging
# Configure Logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
app = FastAPI(title="Cleo API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize singletons that are thread-safe and stateless enough
searcher = GoSearcher()
# Ensure sample directory exists
if not os.path.exists("sample"):
os.makedirs("sample")
# Request model
class GenerateRequest(BaseModel):
topic: str
include_past_questions: bool = True
provider: str = "ollama"
model: str = "llama3"
api_key: Optional[str] = None
@app.post("/generate")
def generate_paper(request: GenerateRequest):
try:
run_id = str(uuid.uuid4())
filename = f"sample/{run_id}.pdf"
# Instantiate services dynamically based on request
logger.info(f"Request Provider: {request.provider}, Model: {request.model}, Topic: {request.topic}")
# Initialize Agent
agent = BaseAgent(
provider=request.provider,
model=request.model,
api_key=request.api_key
)
# Initialize Examiner with this agent
current_examiner = ExamService(agent=agent)
# Determine searcher
s = searcher if request.include_past_questions else None
# Generate QP
qp_data = current_examiner.generate_question_paper(request.topic, searcher=s)
if not qp_data:
logger.error("Failed to generate question paper data")
raise HTTPException(status_code=500, detail="Failed to generate question paper data")
generate_question_paper_pdf(filename, qp_data)
return {
"status": "success",
"download_url": f"/download/{run_id}.pdf",
"filename": f"{run_id}.pdf"
}
except Exception as e:
logger.error(f"API Error: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
from fastapi.responses import FileResponse
@app.get("/download/{filename}")
def download_file(filename: str):
path = f"sample/{filename}"
if os.path.exists(path):
return FileResponse(path, filename=filename, media_type='application/pdf')
raise HTTPException(status_code=404, detail="File not found")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)