Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,49 +1,44 @@
|
|
| 1 |
-
|
| 2 |
-
from
|
| 3 |
-
from
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
# --- 3. RUN THE APP ---
|
| 46 |
-
if __name__ == '__main__':
|
| 47 |
-
# Check if the app is running in debug mode
|
| 48 |
-
is_debug = os.environ.get('FLASK_DEBUG', 'False').lower() == 'true'
|
| 49 |
-
app.run(host='0.0.0.0', port=5000, debug=is_debug)
|
|
|
|
| 1 |
+
from flask import Flask, request, render_template
|
| 2 |
+
from flask_cors import CORS
|
| 3 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 4 |
+
|
| 5 |
+
# --- 1. SETUP ---
|
| 6 |
+
app = Flask(__name__)
|
| 7 |
+
CORS(app)
|
| 8 |
+
|
| 9 |
+
MODEL_NAME = "facebook/blenderbot-400M-distill"
|
| 10 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)
|
| 11 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 12 |
+
print(f"Successfully loaded model: {MODEL_NAME}")
|
| 13 |
+
|
| 14 |
+
# --- 2. API ENDPOINTS ---
|
| 15 |
+
@app.route('/')
|
| 16 |
+
def home():
|
| 17 |
+
"""Serves the main HTML page for the chatbot."""
|
| 18 |
+
return render_template('index.html')
|
| 19 |
+
|
| 20 |
+
@app.route('/chatbot', methods=['POST'])
|
| 21 |
+
def chatbot_endpoint():
|
| 22 |
+
"""The main endpoint to handle chatbot conversations."""
|
| 23 |
+
if not request.is_json:
|
| 24 |
+
return {"error": "Request must be a JSON"}, 400
|
| 25 |
+
|
| 26 |
+
data = request.get_json()
|
| 27 |
+
user_input = data.get("prompt")
|
| 28 |
+
|
| 29 |
+
if not user_input:
|
| 30 |
+
return {"error": "Missing 'prompt' in request body"}, 400
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
inputs = tokenizer(user_input, return_tensors="pt")
|
| 34 |
+
outputs = model.generate(**inputs, max_length=60)
|
| 35 |
+
response_text = tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
|
| 36 |
+
return {"response": response_text}
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"Error during model inference: {e}")
|
| 39 |
+
return {"error": "Failed to generate a response"}, 500
|
| 40 |
+
|
| 41 |
+
# --- 3. RUN THE APP ---
|
| 42 |
+
if __name__ == '__main__':
|
| 43 |
+
# Use port 7860, the standard for Hugging Face Spaces web apps
|
| 44 |
+
app.run(host='0.0.0.0', port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|