junaid17 commited on
Commit
bd26479
·
verified ·
1 Parent(s): 294408d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -119
app.py CHANGED
@@ -1,119 +1,163 @@
1
- from fastapi import FastAPI, HTTPException
2
- from pydantic import BaseModel, Field
3
- from typing import Annotated, Literal
4
- from prediction_helper import predict
5
- from one_shot_bot import generate_advice
6
- from chatbot_advisor import ask_chatbot
7
-
8
- class ModelInput(BaseModel):
9
- gender: Annotated[Literal["male", "female"], Field(description="Enter your gender")]
10
- marital_status: Annotated[Literal["married", "unmarried"], Field(description="Enter your marital status")]
11
- age: Annotated[int, Field(gt=0, lt=110, description="Enter your age")]
12
- number_of_dependants: Annotated[int, Field(gt=0, lt=8)]
13
- income_lakhs: Annotated[float, Field(gt=0,description="Enter your annual income in lakhs")]
14
- genetical_risk: Annotated[int, Field(gt=0, lt=6)]
15
- insurance_plan: Annotated[Literal['Bronze', 'Silver', 'Gold'], Field(description="Choose one of the given plans")]
16
- employment_status: Annotated[Literal['Salaried', 'Self-Employed', 'Freelancer'], Field()]
17
- bmi_category: Annotated[Literal['Normal', 'Obesity', 'Overweight', 'Underweight'], Field()]
18
- smoking_status: Annotated[Literal['No Smoking', 'Regular', 'Occasional'], Field()]
19
- region: Annotated[Literal['Northwest', 'Southeast', 'Northeast', 'Southwest'], Field()]
20
- medical_history: Annotated[
21
- Literal[
22
- 'No Disease', 'Diabetes', 'High blood pressure', 'Diabetes & High blood pressure',
23
- 'Thyroid', 'Heart disease', 'High blood pressure & Heart disease',
24
- 'Diabetes & Thyroid', 'Diabetes & Heart disease'
25
- ],
26
- Field()
27
- ]
28
-
29
- class ModelOutput(BaseModel):
30
- yearly : float
31
- monthly : float
32
- advice : str
33
-
34
- class ChatMessage(BaseModel):
35
- thread_id : str
36
- message : str
37
- yearly_cost : float
38
- monthly_cost : float
39
- ai_summary : str
40
-
41
- app = FastAPI()
42
-
43
- @app.get("/plans")
44
- def plans():
45
- return {
46
- "Bronze": "Basic coverage, low premium.",
47
- "Silver": "Balance of premium and coverage.",
48
- "Gold": "Premium cost with highest benefits."
49
- }
50
-
51
-
52
- @app.get("/home")
53
- def home():
54
- return {"message": "Welcome! The API is live"}
55
-
56
- @app.post("/predict", response_model=ModelOutput)
57
- def predict_output(input_data: ModelInput):
58
- try:
59
- data = input_data.model_dump()
60
-
61
- converted_data = {
62
- "Gender": data["gender"].title(),
63
- "Marital Status": data["marital_status"].title(),
64
- "Age": data["age"],
65
- "Number of Dependants": data["number_of_dependants"],
66
- "Income in Lakhs": data["income_lakhs"],
67
- "Genetical Risk": data["genetical_risk"],
68
- "Insurance Plan": data["insurance_plan"].title(),
69
- "Employment Status": data["employment_status"],
70
- "BMI Category": data["bmi_category"],
71
- "Smoking Status": data["smoking_status"],
72
- "Region": data["region"],
73
- "Medical History": data["medical_history"]
74
- }
75
-
76
- yearly_prediction = float(predict(converted_data))
77
- monthly = round(yearly_prediction / 12, 2)
78
-
79
- advice = generate_advice(
80
- yearly_premium=yearly_prediction,
81
- monthly_premium=monthly,
82
- age=input_data.age,
83
- gender=input_data.gender,
84
- marital_status=input_data.marital_status,
85
- dependents=input_data.number_of_dependants,
86
- bmi_category=input_data.bmi_category,
87
- smoking_status=input_data.smoking_status,
88
- medical_history=input_data.medical_history,
89
- genetic_risk=input_data.genetical_risk,
90
- region=input_data.region,
91
- income_lakhs=input_data.income_lakhs,
92
- employment_status=input_data.employment_status,
93
- insurance_plan=input_data.insurance_plan
94
- )
95
-
96
- return ModelOutput(yearly=yearly_prediction, monthly=monthly, advice=advice)
97
-
98
- except Exception as e:
99
- raise HTTPException(status_code=500, detail=f"Prediction Failed: {str(e)}")
100
-
101
-
102
- @app.post('/chat')
103
- def chat(input_data : ChatMessage):
104
- try:
105
- yearly_cost = input_data.yearly_cost
106
- monthly_cost = input_data.monthly_cost
107
- ai_summary = input_data.ai_summary
108
-
109
- response = ask_chatbot(
110
- yearly_cost=yearly_cost,
111
- monthly_cost=monthly_cost,
112
- ai_summary=ai_summary,
113
- user_message=input_data.message,
114
- thread_id=input_data.thread_id
115
- )
116
- return {"response": response}
117
-
118
- except Exception as e:
119
- raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, UploadFile, File
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import FileResponse, StreamingResponse
4
+ from pydantic import BaseModel
5
+ import os
6
+ from one_shot_bot import generate_advice
7
+ from prediction_helper import predict
8
+ from chatbot_advisor import ask_chatbot
9
+ from utility import STT, TTS
10
+
11
+ app = FastAPI()
12
+
13
+ # ---------------- CORS ---------------- #
14
+ app.add_middleware(
15
+ CORSMiddleware,
16
+ allow_origins=["*"],
17
+ allow_credentials=True,
18
+ allow_methods=["*"],
19
+ allow_headers=["*"],
20
+ )
21
+
22
+ # ---------------- MODELS ---------------- #
23
+
24
+ class HealthInput(BaseModel):
25
+ gender: str
26
+ marital_status: str
27
+ age: int
28
+ number_of_dependants: int
29
+ income_lakhs: float
30
+ genetical_risk: int
31
+ insurance_plan: str
32
+ employment_status: str
33
+ bmi_category: str
34
+ smoking_status: str
35
+ region: str
36
+ medical_history: str
37
+
38
+
39
+ class HealthOutput(BaseModel):
40
+ yearly: float
41
+ monthly: float
42
+ advice: str
43
+
44
+
45
+ class ChatMessage(BaseModel):
46
+ thread_id: str
47
+ message: str
48
+ yearly_cost: float
49
+ monthly_cost: float
50
+ ai_summary: str
51
+
52
+
53
+ class TTSRequest(BaseModel):
54
+ text: str
55
+
56
+
57
+ # ---------------- BASIC ROUTE ---------------- #
58
+
59
+ @app.get("/")
60
+ def home():
61
+ return {"message": "Healthcare AI API is running."}
62
+
63
+
64
+ # ---------------- PREDICTION ---------------- #
65
+
66
+ @app.post("/predict", response_model=HealthOutput)
67
+ def predict_output(input_data: HealthInput):
68
+ try:
69
+ data = input_data.model_dump()
70
+
71
+ converted_data = {
72
+ "Gender": data["gender"].title(),
73
+ "Marital Status": data["marital_status"].title(),
74
+ "Age": data["age"],
75
+ "Number of Dependants": data["number_of_dependants"],
76
+ "Income in Lakhs": data["income_lakhs"],
77
+ "Genetical Risk": data["genetical_risk"],
78
+ "Insurance Plan": data["insurance_plan"].title(),
79
+ "Employment Status": data["employment_status"],
80
+ "BMI Category": data["bmi_category"],
81
+ "Smoking Status": data["smoking_status"],
82
+ "Region": data["region"],
83
+ "Medical History": data["medical_history"]
84
+ }
85
+
86
+ yearly_prediction = float(predict(converted_data))
87
+ monthly = round(yearly_prediction / 12, 2)
88
+
89
+ advice = generate_advice(
90
+ yearly_premium=yearly_prediction,
91
+ monthly_premium=monthly,
92
+ age=input_data.age,
93
+ gender=input_data.gender,
94
+ marital_status=input_data.marital_status,
95
+ dependents=input_data.number_of_dependants,
96
+ bmi_category=input_data.bmi_category,
97
+ smoking_status=input_data.smoking_status,
98
+ medical_history=input_data.medical_history,
99
+ genetic_risk=input_data.genetical_risk,
100
+ region=input_data.region,
101
+ income_lakhs=input_data.income_lakhs,
102
+ employment_status=input_data.employment_status,
103
+ insurance_plan=input_data.insurance_plan
104
+ )
105
+
106
+ return HealthOutput(yearly=yearly_prediction, monthly=monthly, advice=advice)
107
+
108
+ except Exception as e:
109
+ raise HTTPException(status_code=500, detail=f"Prediction Failed: {str(e)}")
110
+
111
+ # ---------------- CHAT STREAM ---------------- #
112
+
113
+ @app.post('/chat')
114
+ def chat(input_data : ChatMessage):
115
+ try:
116
+ yearly_cost = input_data.yearly_cost
117
+ monthly_cost = input_data.monthly_cost
118
+ ai_summary = input_data.ai_summary
119
+
120
+ response = ask_chatbot(
121
+ yearly_cost=yearly_cost,
122
+ monthly_cost=monthly_cost,
123
+ ai_summary=ai_summary,
124
+ user_message=input_data.message,
125
+ thread_id=input_data.thread_id
126
+ )
127
+ return response
128
+
129
+ except Exception as e:
130
+ raise HTTPException(status_code=500, detail=str(e))
131
+
132
+
133
+ # ---------------- TTS ---------------- #
134
+
135
+ @app.post("/tts")
136
+ async def generate_tts(request: TTSRequest):
137
+ try:
138
+ if not request.text.strip():
139
+ raise HTTPException(status_code=400, detail="Text is empty")
140
+
141
+ audio_path = await TTS(text=request.text)
142
+
143
+ if not os.path.exists(audio_path):
144
+ raise HTTPException(status_code=500, detail="Audio file not created")
145
+
146
+ return FileResponse(
147
+ path=audio_path,
148
+ media_type="audio/mpeg",
149
+ filename="speech.mp3"
150
+ )
151
+
152
+ except Exception as e:
153
+ raise HTTPException(status_code=500, detail=str(e))
154
+
155
+
156
+ # ---------------- STT ---------------- #
157
+
158
+ @app.post("/stt")
159
+ async def transcribe_audio(file: UploadFile = File(...)):
160
+ try:
161
+ return await STT(file)
162
+ except Exception as e:
163
+ raise HTTPException(status_code=500, detail=str(e))