Spaces:
Runtime error
Runtime error
| from flask import Flask, request, jsonify, send_from_directory | |
| from flask_cors import CORS | |
| import os | |
| import logging | |
| import requests | |
| from typing import Dict, List, Tuple, Optional | |
| # Configure logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' | |
| ) | |
| logger = logging.getLogger(__name__) | |
| app = Flask(__name__, static_folder='static') | |
| CORS(app) | |
| # Hugging Face Space Configuration | |
| HF_API_URL = os.getenv("HF_API_URL", "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta") | |
| HF_TOKEN = os.getenv("HF_TOKEN") # Will use Spaces secrets | |
| FALLBACK_ENABLED = True | |
| MODEL_TIMEOUT = 10 # seconds | |
| class RupeiaChatbot: | |
| def __init__(self): | |
| self.fallback_responses = self._load_responses() | |
| self.quick_replies = self._load_quick_replies() | |
| def _load_responses(self) -> Dict[str, Dict[str, str]]: | |
| """Load all predefined responses""" | |
| return { | |
| "sip": { | |
| "response": "To start an SIP with Rupeia: 1) Login 2) Go to Investments 3) Select SIP option 4) Choose fund and amount. Minimum ₹500/month.", | |
| "quick_replies": ["sip vs lumpsum", "pause sip"] | |
| }, | |
| # Add other responses similarly | |
| } | |
| def get_fallback(self, message: str) -> Tuple[str, List[str]]: | |
| """Get fallback response""" | |
| message = message.lower() | |
| for intent, data in self.fallback_responses.items(): | |
| if intent in message: | |
| return data["response"], data["quick_replies"] | |
| return "I can help with investments, goals, and more. Please ask clearly.", ["start sip", "set goal"] | |
| def query_model(self, message: str) -> Optional[str]: | |
| """Query HF model with error handling""" | |
| if not HF_TOKEN: | |
| return None | |
| headers = {"Authorization": f"Bearer {HF_TOKEN}"} | |
| payload = { | |
| "inputs": f"""<|system|> | |
| You are Rupeia, a financial assistant. Respond concisely to: | |
| {message}</s><|assistant|>""", | |
| "parameters": {"max_new_tokens": 250} | |
| } | |
| try: | |
| response = requests.post( | |
| HF_API_URL, | |
| headers=headers, | |
| json=payload, | |
| timeout=MODEL_TIMEOUT | |
| ) | |
| response.raise_for_status() | |
| return response.json()[0]['generated_text'] | |
| except Exception as e: | |
| logger.error(f"Model error: {str(e)}") | |
| return None | |
| def chat(): | |
| try: | |
| data = request.get_json() | |
| message = data.get('message', '').strip() | |
| chatbot = RupeiaChatbot() | |
| model_response = chatbot.query_model(message) | |
| if model_response: | |
| return jsonify({ | |
| 'text': model_response, | |
| 'source': 'model' | |
| }) | |
| if FALLBACK_ENABLED: | |
| text, replies = chatbot.get_fallback(message) | |
| return jsonify({ | |
| 'text': text, | |
| 'quick_replies': replies, | |
| 'source': 'fallback' | |
| }) | |
| except Exception as e: | |
| logger.error(f"Chat error: {str(e)}") | |
| return jsonify({ | |
| 'text': "Service unavailable. Please try later.", | |
| 'source': 'error' | |
| }), 503 | |
| def home(): | |
| return send_from_directory('templates', 'index.html') | |
| if __name__ == '__main__': | |
| app.run(debug=False, host='0.0.0.0', port=8080) |