Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
from flask import Flask, request, jsonify
|
| 3 |
+
|
| 4 |
+
app = Flask(__name__)
|
| 5 |
+
|
| 6 |
+
# Your PythonAnywhere API endpoint
|
| 7 |
+
PYTHONANYWHERE_URL = "https://omarnuwara.pythonanywhere.com/get-response"
|
| 8 |
+
|
| 9 |
+
@app.route('/chat', methods=['POST'])
|
| 10 |
+
def chat():
|
| 11 |
+
try:
|
| 12 |
+
# Ensure the request contains JSON and a "message" key
|
| 13 |
+
user_input = request.json.get("message", "") if request.is_json else None
|
| 14 |
+
|
| 15 |
+
if not user_input:
|
| 16 |
+
return jsonify({"error": "No message provided in the request."}), 400
|
| 17 |
+
|
| 18 |
+
# Create the payload to send to PythonAnywhere
|
| 19 |
+
data = {"message": user_input}
|
| 20 |
+
|
| 21 |
+
# Forward the request to PythonAnywhere
|
| 22 |
+
response = requests.post(PYTHONANYWHERE_URL, json=data)
|
| 23 |
+
|
| 24 |
+
if response.status_code == 200:
|
| 25 |
+
response_json = response.json()
|
| 26 |
+
ai_response = response_json.get("response", "No 'response' key found in the JSON.")
|
| 27 |
+
ai_response = ai_response.encode('latin1').decode('utf-8', 'ignore')
|
| 28 |
+
return (ai_response)
|
| 29 |
+
else:
|
| 30 |
+
# Handle errors from PythonAnywhere
|
| 31 |
+
return jsonify({
|
| 32 |
+
"error": "Error from PythonAnywhere",
|
| 33 |
+
"details": response.text
|
| 34 |
+
}), response.status_code
|
| 35 |
+
|
| 36 |
+
except Exception as e:
|
| 37 |
+
# Catch any unexpected errors
|
| 38 |
+
return jsonify({"error": "An error occurred", "details": str(e)}), 500
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
app.run(host="0.0.0.0", port=7860)
|