Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -89,6 +89,45 @@ def classify_query_with_gemini(query: str):
|
|
| 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():
|
|
@@ -125,23 +164,36 @@ def process_query():
|
|
| 125 |
}), 200
|
| 126 |
else:
|
| 127 |
print(f"Session {session_id}: No image required. Forwarding to '{classification.get('category')}' API.")
|
| 128 |
-
|
| 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 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
| 138 |
del SESSIONS[session_id]
|
| 139 |
print(f"Session {session_id} closed.")
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
@app.route('/process_with_image', methods=['POST'])
|
| 147 |
def process_with_image():
|
|
@@ -165,41 +217,32 @@ def process_with_image():
|
|
| 165 |
|
| 166 |
print(f"Session {session_id}: Image received. Preparing to forward to '{category}' API.")
|
| 167 |
|
| 168 |
-
#
|
| 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 |
-
#
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 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":
|
| 190 |
-
"
|
| 191 |
-
}
|
| 192 |
-
|
| 193 |
-
#
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
return jsonify({"status": "error", "message": f"Backend service call failed: {e}"}), 503
|
| 203 |
|
| 204 |
if __name__ == '__main__':
|
| 205 |
app.run(debug=True, port=5000)
|
|
|
|
| 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 |
+
# Different categories ke liye different request formats
|
| 97 |
+
if category == "medicine_info":
|
| 98 |
+
if files:
|
| 99 |
+
response = requests.post(endpoint_url, files=files, data={"main_query": query}, timeout=30)
|
| 100 |
+
else:
|
| 101 |
+
response = requests.post(endpoint_url, json={"main_query": query}, timeout=30)
|
| 102 |
+
else:
|
| 103 |
+
if files:
|
| 104 |
+
response = requests.post(endpoint_url, files=files, data={"main_query": query}, timeout=30)
|
| 105 |
+
else:
|
| 106 |
+
response = requests.post(endpoint_url, data={"main_query": query}, timeout=30)
|
| 107 |
+
|
| 108 |
+
# Status code check karein
|
| 109 |
+
response.raise_for_status()
|
| 110 |
+
|
| 111 |
+
# Content-Type check karein
|
| 112 |
+
content_type = response.headers.get('content-type', '')
|
| 113 |
+
|
| 114 |
+
if 'application/json' in content_type:
|
| 115 |
+
return {"success": True, "data": response.json()}
|
| 116 |
+
else:
|
| 117 |
+
# Agar JSON nahi hai to text return karein
|
| 118 |
+
return {"success": True, "data": {"message": response.text}}
|
| 119 |
+
|
| 120 |
+
except requests.exceptions.ConnectionError:
|
| 121 |
+
return {"success": False, "error": "API service unavailable. Please check if the service is running."}
|
| 122 |
+
except requests.exceptions.Timeout:
|
| 123 |
+
return {"success": False, "error": "API request timed out. Please try again."}
|
| 124 |
+
except requests.exceptions.HTTPError as e:
|
| 125 |
+
return {"success": False, "error": f"API returned error: {e.response.status_code}"}
|
| 126 |
+
except requests.exceptions.JSONDecodeError:
|
| 127 |
+
return {"success": False, "error": "API returned invalid JSON response"}
|
| 128 |
+
except Exception as e:
|
| 129 |
+
return {"success": False, "error": f"Unexpected error: {str(e)}"}
|
| 130 |
+
|
| 131 |
# Step 4: API Routes (Endpoints)
|
| 132 |
@app.route('/start_session', methods=['POST'])
|
| 133 |
def start_session():
|
|
|
|
| 164 |
}), 200
|
| 165 |
else:
|
| 166 |
print(f"Session {session_id}: No image required. Forwarding to '{classification.get('category')}' API.")
|
| 167 |
+
|
| 168 |
# Session se query aur classification nikalein
|
| 169 |
query = SESSIONS[session_id].get('query')
|
| 170 |
classification = SESSIONS[session_id].get('classification')
|
| 171 |
category = classification['category']
|
| 172 |
endpoint_url = API_ENDPOINTS.get(category)
|
| 173 |
+
|
| 174 |
+
# External API call with error handling
|
| 175 |
+
api_result = call_external_api(endpoint_url, category, query)
|
| 176 |
+
|
| 177 |
+
# Session close karein
|
| 178 |
del SESSIONS[session_id]
|
| 179 |
print(f"Session {session_id} closed.")
|
| 180 |
+
|
| 181 |
+
if api_result["success"]:
|
| 182 |
+
return jsonify({
|
| 183 |
+
"status": "success",
|
| 184 |
+
"response": api_result["data"],
|
| 185 |
+
"category": category
|
| 186 |
+
})
|
| 187 |
+
else:
|
| 188 |
+
# API call fail ho gaya, mock response bhejein
|
| 189 |
+
return jsonify({
|
| 190 |
+
"status": "success",
|
| 191 |
+
"response": {
|
| 192 |
+
"message": f"Service temporarily unavailable. Mock response: Information about '{query}' from {category} service.",
|
| 193 |
+
"error_details": api_result["error"]
|
| 194 |
+
},
|
| 195 |
+
"category": category
|
| 196 |
+
})
|
| 197 |
|
| 198 |
@app.route('/process_with_image', methods=['POST'])
|
| 199 |
def process_with_image():
|
|
|
|
| 217 |
|
| 218 |
print(f"Session {session_id}: Image received. Preparing to forward to '{category}' API.")
|
| 219 |
|
| 220 |
+
# File payload prepare karein
|
|
|
|
|
|
|
|
|
|
| 221 |
files_payload = {'file': (file.filename, file.stream, file.mimetype)}
|
| 222 |
|
| 223 |
+
# External API call with error handling
|
| 224 |
+
api_result = call_external_api(endpoint_url, category, query, files=files_payload)
|
| 225 |
+
|
| 226 |
+
# Session close karein
|
| 227 |
+
del SESSIONS[session_id]
|
| 228 |
+
print(f"Session {session_id} closed.")
|
| 229 |
+
|
| 230 |
+
if api_result["success"]:
|
| 231 |
+
return jsonify({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
"status": "success",
|
| 233 |
+
"response": api_result["data"],
|
| 234 |
+
"category": category
|
| 235 |
+
})
|
| 236 |
+
else:
|
| 237 |
+
# API call fail ho gaya, mock response bhejein
|
| 238 |
+
return jsonify({
|
| 239 |
+
"status": "success",
|
| 240 |
+
"response": {
|
| 241 |
+
"message": f"Service temporarily unavailable. Mock response: Analysis for '{query}' based on your image from {category} service.",
|
| 242 |
+
"error_details": api_result["error"]
|
| 243 |
+
},
|
| 244 |
+
"category": category
|
| 245 |
+
})
|
|
|
|
| 246 |
|
| 247 |
if __name__ == '__main__':
|
| 248 |
app.run(debug=True, port=5000)
|