Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -89,98 +89,6 @@ def classify_query_with_gemini(query: str):
|
|
| 89 |
print(f"Gemini API call ya JSON parsing mein error: {e}")
|
| 90 |
return None
|
| 91 |
|
| 92 |
-
# Helper function to safely call external APIs
|
| 93 |
-
def call_external_api(endpoint_url, category, query, files=None):
|
| 94 |
-
"""External API ko safely call karta hai aur response handle karta hai."""
|
| 95 |
-
try:
|
| 96 |
-
# Category-specific request handling based on your actual APIs
|
| 97 |
-
if category == "medicine_info":
|
| 98 |
-
# Medicine API expects JSON format with "query" parameter
|
| 99 |
-
if files:
|
| 100 |
-
# For file upload, use multipart form data
|
| 101 |
-
response = requests.post(
|
| 102 |
-
endpoint_url,
|
| 103 |
-
files=files,
|
| 104 |
-
data={"query": query}, # Medicine API uses "query" not "main_query"
|
| 105 |
-
timeout=30
|
| 106 |
-
)
|
| 107 |
-
else:
|
| 108 |
-
# For text-only queries, use JSON
|
| 109 |
-
response = requests.post(
|
| 110 |
-
endpoint_url,
|
| 111 |
-
json={"query": query}, # Medicine API uses "query" not "main_query"
|
| 112 |
-
headers={'Content-Type': 'application/json'},
|
| 113 |
-
timeout=30
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
elif category == "disease_query":
|
| 117 |
-
# Disease query API - try multiple formats since we're not sure
|
| 118 |
-
if files:
|
| 119 |
-
response = requests.post(
|
| 120 |
-
endpoint_url,
|
| 121 |
-
files=files,
|
| 122 |
-
data={"main_query": query},
|
| 123 |
-
timeout=30
|
| 124 |
-
)
|
| 125 |
-
else:
|
| 126 |
-
# Try JSON first, fallback to form data if needed
|
| 127 |
-
try:
|
| 128 |
-
response = requests.post(
|
| 129 |
-
endpoint_url,
|
| 130 |
-
json={"main_query": query},
|
| 131 |
-
headers={'Content-Type': 'application/json'},
|
| 132 |
-
timeout=30
|
| 133 |
-
)
|
| 134 |
-
except requests.exceptions.HTTPError as json_error:
|
| 135 |
-
if json_error.response.status_code == 415:
|
| 136 |
-
# Try form data format
|
| 137 |
-
response = requests.post(
|
| 138 |
-
endpoint_url,
|
| 139 |
-
data={"main_query": query},
|
| 140 |
-
timeout=30
|
| 141 |
-
)
|
| 142 |
-
else:
|
| 143 |
-
raise
|
| 144 |
-
|
| 145 |
-
else:
|
| 146 |
-
# For other categories (skin_disease, report_reading)
|
| 147 |
-
if files:
|
| 148 |
-
response = requests.post(
|
| 149 |
-
endpoint_url,
|
| 150 |
-
files=files,
|
| 151 |
-
data={"main_query": query},
|
| 152 |
-
timeout=30
|
| 153 |
-
)
|
| 154 |
-
else:
|
| 155 |
-
response = requests.post(
|
| 156 |
-
endpoint_url,
|
| 157 |
-
data={"main_query": query},
|
| 158 |
-
timeout=30
|
| 159 |
-
)
|
| 160 |
-
|
| 161 |
-
# Status code check karein
|
| 162 |
-
response.raise_for_status()
|
| 163 |
-
|
| 164 |
-
# Content-Type check karein
|
| 165 |
-
content_type = response.headers.get('content-type', '')
|
| 166 |
-
|
| 167 |
-
if 'application/json' in content_type:
|
| 168 |
-
return {"success": True, "data": response.json()}
|
| 169 |
-
else:
|
| 170 |
-
# Agar JSON nahi hai to text return karein
|
| 171 |
-
return {"success": True, "data": {"message": response.text}}
|
| 172 |
-
|
| 173 |
-
except requests.exceptions.ConnectionError:
|
| 174 |
-
return {"success": False, "error": "API service unavailable. Please check if the service is running."}
|
| 175 |
-
except requests.exceptions.Timeout:
|
| 176 |
-
return {"success": False, "error": "API request timed out. Please try again."}
|
| 177 |
-
except requests.exceptions.HTTPError as e:
|
| 178 |
-
return {"success": False, "error": f"API returned error: {e.response.status_code}"}
|
| 179 |
-
except requests.exceptions.JSONDecodeError:
|
| 180 |
-
return {"success": False, "error": "API returned invalid JSON response"}
|
| 181 |
-
except Exception as e:
|
| 182 |
-
return {"success": False, "error": f"Unexpected error: {str(e)}"}
|
| 183 |
-
|
| 184 |
# Step 4: API Routes (Endpoints)
|
| 185 |
@app.route('/start_session', methods=['POST'])
|
| 186 |
def start_session():
|
|
@@ -189,65 +97,6 @@ def start_session():
|
|
| 189 |
print(f"Session started: {session_id}")
|
| 190 |
return jsonify({"session_id": session_id}), 200
|
| 191 |
|
| 192 |
-
# Temporary debugging endpoint
|
| 193 |
-
@app.route('/test_api', methods=['POST'])
|
| 194 |
-
def test_api():
|
| 195 |
-
"""Debugging endpoint to test different API formats"""
|
| 196 |
-
data = request.get_json()
|
| 197 |
-
query = data.get('query', 'test query')
|
| 198 |
-
endpoint_url = data.get('endpoint', 'http://localhost:5001/ask')
|
| 199 |
-
|
| 200 |
-
results = {}
|
| 201 |
-
|
| 202 |
-
# Test 1: JSON format
|
| 203 |
-
try:
|
| 204 |
-
response = requests.post(
|
| 205 |
-
endpoint_url,
|
| 206 |
-
json={"main_query": query},
|
| 207 |
-
headers={'Content-Type': 'application/json'},
|
| 208 |
-
timeout=10
|
| 209 |
-
)
|
| 210 |
-
results['json_format'] = {
|
| 211 |
-
'status_code': response.status_code,
|
| 212 |
-
'content_type': response.headers.get('content-type'),
|
| 213 |
-
'response': response.text[:200] if response.text else 'Empty'
|
| 214 |
-
}
|
| 215 |
-
except Exception as e:
|
| 216 |
-
results['json_format'] = {'error': str(e)}
|
| 217 |
-
|
| 218 |
-
# Test 2: Form data format
|
| 219 |
-
try:
|
| 220 |
-
response = requests.post(
|
| 221 |
-
endpoint_url,
|
| 222 |
-
data={"main_query": query},
|
| 223 |
-
timeout=10
|
| 224 |
-
)
|
| 225 |
-
results['form_format'] = {
|
| 226 |
-
'status_code': response.status_code,
|
| 227 |
-
'content_type': response.headers.get('content-type'),
|
| 228 |
-
'response': response.text[:200] if response.text else 'Empty'
|
| 229 |
-
}
|
| 230 |
-
except Exception as e:
|
| 231 |
-
results['form_format'] = {'error': str(e)}
|
| 232 |
-
|
| 233 |
-
# Test 3: Alternative parameter name
|
| 234 |
-
try:
|
| 235 |
-
response = requests.post(
|
| 236 |
-
endpoint_url,
|
| 237 |
-
json={"query": query},
|
| 238 |
-
headers={'Content-Type': 'application/json'},
|
| 239 |
-
timeout=10
|
| 240 |
-
)
|
| 241 |
-
results['alt_param_json'] = {
|
| 242 |
-
'status_code': response.status_code,
|
| 243 |
-
'content_type': response.headers.get('content-type'),
|
| 244 |
-
'response': response.text[:200] if response.text else 'Empty'
|
| 245 |
-
}
|
| 246 |
-
except Exception as e:
|
| 247 |
-
results['alt_param_json'] = {'error': str(e)}
|
| 248 |
-
|
| 249 |
-
return jsonify(results)
|
| 250 |
-
|
| 251 |
@app.route('/process_query', methods=['POST'])
|
| 252 |
def process_query():
|
| 253 |
data = request.get_json()
|
|
@@ -276,36 +125,23 @@ def process_query():
|
|
| 276 |
}), 200
|
| 277 |
else:
|
| 278 |
print(f"Session {session_id}: No image required. Forwarding to '{classification.get('category')}' API.")
|
| 279 |
-
|
| 280 |
# Session se query aur classification nikalein
|
| 281 |
query = SESSIONS[session_id].get('query')
|
| 282 |
classification = SESSIONS[session_id].get('classification')
|
| 283 |
category = classification['category']
|
| 284 |
endpoint_url = API_ENDPOINTS.get(category)
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
# Session close karein
|
| 290 |
del SESSIONS[session_id]
|
| 291 |
print(f"Session {session_id} closed.")
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
"category": category
|
| 298 |
-
})
|
| 299 |
-
else:
|
| 300 |
-
# API call fail ho gaya, mock response bhejein
|
| 301 |
-
return jsonify({
|
| 302 |
-
"status": "success",
|
| 303 |
-
"response": {
|
| 304 |
-
"message": f"Service temporarily unavailable. Mock response: Information about '{query}' from {category} service.",
|
| 305 |
-
"error_details": api_result["error"]
|
| 306 |
-
},
|
| 307 |
-
"category": category
|
| 308 |
-
})
|
| 309 |
|
| 310 |
@app.route('/process_with_image', methods=['POST'])
|
| 311 |
def process_with_image():
|
|
@@ -329,34 +165,38 @@ def process_with_image():
|
|
| 329 |
|
| 330 |
print(f"Session {session_id}: Image received. Preparing to forward to '{category}' API.")
|
| 331 |
|
| 332 |
-
#
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
# Other APIs might expect 'photo' or 'image'
|
| 338 |
-
files_payload = {'file': (file.filename, file.stream, file.mimetype)}
|
| 339 |
-
|
| 340 |
-
# External API call with error handling
|
| 341 |
-
api_result = call_external_api(endpoint_url, category, query, files=files_payload)
|
| 342 |
|
| 343 |
-
#
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
|
|
|
| 356 |
"status": "success",
|
| 357 |
-
"response":
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
print(f"Gemini API call ya JSON parsing mein error: {e}")
|
| 90 |
return None
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
# Step 4: API Routes (Endpoints)
|
| 93 |
@app.route('/start_session', methods=['POST'])
|
| 94 |
def start_session():
|
|
|
|
| 97 |
print(f"Session started: {session_id}")
|
| 98 |
return jsonify({"session_id": session_id}), 200
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
@app.route('/process_query', methods=['POST'])
|
| 101 |
def process_query():
|
| 102 |
data = request.get_json()
|
|
|
|
| 125 |
}), 200
|
| 126 |
else:
|
| 127 |
print(f"Session {session_id}: No image required. Forwarding to '{classification.get('category')}' API.")
|
| 128 |
+
# Asli API ko call karein (Abhi ke liye mock response)
|
| 129 |
# Session se query aur classification nikalein
|
| 130 |
query = SESSIONS[session_id].get('query')
|
| 131 |
classification = SESSIONS[session_id].get('classification')
|
| 132 |
category = classification['category']
|
| 133 |
endpoint_url = API_ENDPOINTS.get(category)
|
| 134 |
+
if category == "medicine_info":
|
| 135 |
+
response = requests.post(endpoint_url, json={"main_query": query})
|
| 136 |
+
else:
|
| 137 |
+
response = requests.post(endpoint_url, data={"main_query": query})
|
|
|
|
| 138 |
del SESSIONS[session_id]
|
| 139 |
print(f"Session {session_id} closed.")
|
| 140 |
+
return jsonify({
|
| 141 |
+
"status": "success",
|
| 142 |
+
"response": response.json(),
|
| 143 |
+
"data": f"Information about '{query}': This is a tuned response from the {classification.get('category')} service."
|
| 144 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
@app.route('/process_with_image', methods=['POST'])
|
| 147 |
def process_with_image():
|
|
|
|
| 165 |
|
| 166 |
print(f"Session {session_id}: Image received. Preparing to forward to '{category}' API.")
|
| 167 |
|
| 168 |
+
# *** NEW: FORWARDING LOGIC THAT MATCHES YOUR CURL COMMAND ***
|
| 169 |
+
# The file object from Flask needs its stream to be readable by `requests`
|
| 170 |
+
# We pass the file stream, filename, and mimetype to requests
|
| 171 |
+
# The dictionary key 'file' matches the '-F file=@...' part of your curl command
|
| 172 |
+
files_payload = {'file': (file.filename, file.stream, file.mimetype)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
+
# The dictionary key 'query' matches the '-F query=...' part
|
| 175 |
+
data_payload = {'query': query}
|
| 176 |
+
|
| 177 |
+
try:
|
| 178 |
+
# NOTE: Neeche di gayi line asli API call hai.
|
| 179 |
+
# Jab aapka backend service (e.g., http://localhost:5002/api/query) taiyaar ho,
|
| 180 |
+
# to is line ko uncomment kar dein.
|
| 181 |
+
|
| 182 |
+
response_from_service = requests.post(endpoint_url, files=files_payload, data=data_payload)
|
| 183 |
+
response_from_service.raise_for_status() # Agar 4xx/5xx error ho to exception raise karega
|
| 184 |
+
tuned_response = response_from_service.json() # Assume service returns JSON
|
| 185 |
+
|
| 186 |
+
# Abhi ke liye, hum ek mock response bhej rahe hain
|
| 187 |
+
mock_response = {
|
| 188 |
"status": "success",
|
| 189 |
+
"response": tuned_response,
|
| 190 |
+
"data": f"Analysis for '{query}' based on your image: This is a tuned MOCK response from the {category} service."
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
# Session close karein
|
| 194 |
+
del SESSIONS[session_id]
|
| 195 |
+
print(f"Session {session_id} closed.")
|
| 196 |
+
|
| 197 |
+
return jsonify(mock_response)
|
| 198 |
+
|
| 199 |
+
except requests.exceptions.RequestException as e:
|
| 200 |
+
del SESSIONS[session_id]
|
| 201 |
+
print(f"Session {session_id} closed after failed API call.")
|
| 202 |
+
return jsonify({"status": "error", "message": f"Backend service call failed: {e}"}), 503
|