Spaces:
Sleeping
Sleeping
Update question_generation.py
Browse files- question_generation.py +96 -96
question_generation.py
CHANGED
|
@@ -1,100 +1,100 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
from dotenv import load_dotenv
|
| 4 |
-
from pydantic import BaseModel, ValidationError
|
| 5 |
-
from typing import List
|
| 6 |
-
from prompts import PROMPTS
|
| 7 |
-
import google.generativeai as genai
|
| 8 |
-
from fastapi import FastAPI, HTTPException
|
| 9 |
import uvicorn
|
| 10 |
-
|
| 11 |
-
# Setup
|
| 12 |
-
load_dotenv()
|
| 13 |
-
google_api_key = os.getenv("GOOGLE_API_KEY")
|
| 14 |
-
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
| 15 |
-
model = genai.GenerativeModel(os.getenv("LLM_MODEL", "gemini-pro"))
|
| 16 |
-
|
| 17 |
-
# Models
|
| 18 |
-
class TopicRequest(BaseModel):
|
| 19 |
-
topic: str
|
| 20 |
-
num_questions: int = 10
|
| 21 |
-
|
| 22 |
-
class GeneratedQuestionModel(BaseModel):
|
| 23 |
-
question_language: str
|
| 24 |
-
question_list: List[str]
|
| 25 |
-
|
| 26 |
-
# Functions
|
| 27 |
-
def chat_with_model(prompt: str) -> str:
|
| 28 |
-
try:
|
| 29 |
-
response = model.generate_content(prompt)
|
| 30 |
-
return response.text if response.text else "Error: Empty response"
|
| 31 |
-
except Exception as e:
|
| 32 |
-
return f"Error: {e}"
|
| 33 |
-
|
| 34 |
-
def clean_json_text(text: str) -> str:
|
| 35 |
-
if text.startswith("Error:"):
|
| 36 |
-
return text
|
| 37 |
-
if text.startswith("```"):
|
| 38 |
-
lines = text.split('\n')
|
| 39 |
-
text = '\n'.join(lines[1:-1]) if len(lines) > 2 else text.strip("`").replace("json", "", 1).strip()
|
| 40 |
-
first, last = text.find("{"), text.rfind("}")
|
| 41 |
-
return text[first:last+1] if first != -1 and last != -1 else text
|
| 42 |
-
|
| 43 |
-
def validate_answer(raw_output: str):
|
| 44 |
-
cleaned = clean_json_text(raw_output)
|
| 45 |
-
if cleaned.startswith("Error:"):
|
| 46 |
-
return {"error": cleaned, "question_language": "Odia", "question_list": []}
|
| 47 |
-
try:
|
| 48 |
-
return GeneratedQuestionModel.model_validate_json(cleaned).model_dump()
|
| 49 |
-
except ValidationError:
|
| 50 |
-
try:
|
| 51 |
-
return GeneratedQuestionModel(**json.loads(cleaned)).model_dump()
|
| 52 |
-
except:
|
| 53 |
-
return {"error": "Invalid JSON", "question_language": "Odia", "question_list": []}
|
| 54 |
-
|
| 55 |
-
def final_pipeline(user_input: str, num_questions: int = 10):
|
| 56 |
-
prompt = PROMPTS["questions_only"].format(language="Odia", topic=user_input, num_questions=num_questions)
|
| 57 |
-
return validate_answer(chat_with_model(prompt))
|
| 58 |
-
|
| 59 |
-
# API
|
| 60 |
-
app = FastAPI()
|
| 61 |
-
|
| 62 |
-
@app.get("/health")
|
| 63 |
-
async def health_check():
|
| 64 |
-
try:
|
| 65 |
-
# Test model connectivity
|
| 66 |
-
test_response = model.generate_content("Test")
|
| 67 |
-
return {
|
| 68 |
-
"status": "healthy",
|
| 69 |
-
"model": os.getenv("LLM_MODEL", "gemini-pro"),
|
| 70 |
-
"api_configured": bool(google_api_key)
|
| 71 |
-
}
|
| 72 |
-
except Exception as e:
|
| 73 |
-
return {
|
| 74 |
-
"status": "unhealthy",
|
| 75 |
-
"error": str(e),
|
| 76 |
-
"api_configured": bool(google_api_key)
|
| 77 |
-
}
|
| 78 |
-
@app.get("/")
|
| 79 |
-
async def root():
|
| 80 |
-
return {"message": "Odia Question Generating API is running", "status": "healthy"}
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
@app.post("/generate-questions")
|
| 84 |
-
async def generate_questions(request: TopicRequest):
|
| 85 |
-
if not request.topic.strip():
|
| 86 |
-
raise HTTPException(status_code=400, detail="Topic cannot be empty")
|
| 87 |
-
if not 1 <= request.num_questions <= 50:
|
| 88 |
-
raise HTTPException(status_code=400, detail="Questions must be between 1-50")
|
| 89 |
-
|
| 90 |
-
result = final_pipeline(request.topic.strip(), request.num_questions)
|
| 91 |
-
|
| 92 |
-
if "error" in result and "Error:" in result["error"]:
|
| 93 |
-
raise HTTPException(status_code=500, detail=result["error"])
|
| 94 |
-
|
| 95 |
-
return {"success": True, "data": result}
|
| 96 |
-
|
| 97 |
if __name__ == "__main__":
|
| 98 |
host = os.getenv("QUESTION_SERVICE_HOST", "0.0.0.0")
|
| 99 |
port = int(os.getenv("QUESTION_SERVICE_PORT", "8000"))
|
| 100 |
-
uvicorn.run(app, host=
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
from pydantic import BaseModel, ValidationError
|
| 5 |
+
from typing import List
|
| 6 |
+
from prompts import PROMPTS
|
| 7 |
+
import google.generativeai as genai
|
| 8 |
+
from fastapi import FastAPI, HTTPException
|
| 9 |
import uvicorn
|
| 10 |
+
|
| 11 |
+
# Setup
|
| 12 |
+
load_dotenv()
|
| 13 |
+
google_api_key = os.getenv("GOOGLE_API_KEY")
|
| 14 |
+
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
| 15 |
+
model = genai.GenerativeModel(os.getenv("LLM_MODEL", "gemini-pro"))
|
| 16 |
+
|
| 17 |
+
# Models
|
| 18 |
+
class TopicRequest(BaseModel):
|
| 19 |
+
topic: str
|
| 20 |
+
num_questions: int = 10
|
| 21 |
+
|
| 22 |
+
class GeneratedQuestionModel(BaseModel):
|
| 23 |
+
question_language: str
|
| 24 |
+
question_list: List[str]
|
| 25 |
+
|
| 26 |
+
# Functions
|
| 27 |
+
def chat_with_model(prompt: str) -> str:
|
| 28 |
+
try:
|
| 29 |
+
response = model.generate_content(prompt)
|
| 30 |
+
return response.text if response.text else "Error: Empty response"
|
| 31 |
+
except Exception as e:
|
| 32 |
+
return f"Error: {e}"
|
| 33 |
+
|
| 34 |
+
def clean_json_text(text: str) -> str:
|
| 35 |
+
if text.startswith("Error:"):
|
| 36 |
+
return text
|
| 37 |
+
if text.startswith("```"):
|
| 38 |
+
lines = text.split('\n')
|
| 39 |
+
text = '\n'.join(lines[1:-1]) if len(lines) > 2 else text.strip("`").replace("json", "", 1).strip()
|
| 40 |
+
first, last = text.find("{"), text.rfind("}")
|
| 41 |
+
return text[first:last+1] if first != -1 and last != -1 else text
|
| 42 |
+
|
| 43 |
+
def validate_answer(raw_output: str):
|
| 44 |
+
cleaned = clean_json_text(raw_output)
|
| 45 |
+
if cleaned.startswith("Error:"):
|
| 46 |
+
return {"error": cleaned, "question_language": "Odia", "question_list": []}
|
| 47 |
+
try:
|
| 48 |
+
return GeneratedQuestionModel.model_validate_json(cleaned).model_dump()
|
| 49 |
+
except ValidationError:
|
| 50 |
+
try:
|
| 51 |
+
return GeneratedQuestionModel(**json.loads(cleaned)).model_dump()
|
| 52 |
+
except:
|
| 53 |
+
return {"error": "Invalid JSON", "question_language": "Odia", "question_list": []}
|
| 54 |
+
|
| 55 |
+
def final_pipeline(user_input: str, num_questions: int = 10):
|
| 56 |
+
prompt = PROMPTS["questions_only"].format(language="Odia", topic=user_input, num_questions=num_questions)
|
| 57 |
+
return validate_answer(chat_with_model(prompt))
|
| 58 |
+
|
| 59 |
+
# API
|
| 60 |
+
app = FastAPI()
|
| 61 |
+
|
| 62 |
+
@app.get("/health")
|
| 63 |
+
async def health_check():
|
| 64 |
+
try:
|
| 65 |
+
# Test model connectivity
|
| 66 |
+
test_response = model.generate_content("Test")
|
| 67 |
+
return {
|
| 68 |
+
"status": "healthy",
|
| 69 |
+
"model": os.getenv("LLM_MODEL", "gemini-pro"),
|
| 70 |
+
"api_configured": bool(google_api_key)
|
| 71 |
+
}
|
| 72 |
+
except Exception as e:
|
| 73 |
+
return {
|
| 74 |
+
"status": "unhealthy",
|
| 75 |
+
"error": str(e),
|
| 76 |
+
"api_configured": bool(google_api_key)
|
| 77 |
+
}
|
| 78 |
+
@app.get("/")
|
| 79 |
+
async def root():
|
| 80 |
+
return {"message": "Odia Question Generating API is running", "status": "healthy"}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@app.post("/generate-questions")
|
| 84 |
+
async def generate_questions(request: TopicRequest):
|
| 85 |
+
if not request.topic.strip():
|
| 86 |
+
raise HTTPException(status_code=400, detail="Topic cannot be empty")
|
| 87 |
+
if not 1 <= request.num_questions <= 50:
|
| 88 |
+
raise HTTPException(status_code=400, detail="Questions must be between 1-50")
|
| 89 |
+
|
| 90 |
+
result = final_pipeline(request.topic.strip(), request.num_questions)
|
| 91 |
+
|
| 92 |
+
if "error" in result and "Error:" in result["error"]:
|
| 93 |
+
raise HTTPException(status_code=500, detail=result["error"])
|
| 94 |
+
|
| 95 |
+
return {"success": True, "data": result}
|
| 96 |
+
|
| 97 |
if __name__ == "__main__":
|
| 98 |
host = os.getenv("QUESTION_SERVICE_HOST", "0.0.0.0")
|
| 99 |
port = int(os.getenv("QUESTION_SERVICE_PORT", "8000"))
|
| 100 |
+
uvicorn.run(app, host=0.0.0.0, port=8000)
|