Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,120 +1,47 @@
|
|
| 1 |
from flask import Flask, render_template, request, jsonify
|
|
|
|
|
|
|
|
|
|
| 2 |
import yaml
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
import threading
|
| 6 |
-
from threading import Lock
|
| 7 |
-
import time
|
| 8 |
-
|
| 9 |
-
# Set up logging
|
| 10 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 11 |
-
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
app = Flask(__name__)
|
| 14 |
|
| 15 |
# Load configuration
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
config = yaml.safe_load(f)
|
| 19 |
-
except FileNotFoundError as e:
|
| 20 |
-
logger.error("Configuration file config.yaml not found in config/ directory: %s", e)
|
| 21 |
-
raise
|
| 22 |
-
|
| 23 |
-
# Lazy loading setup
|
| 24 |
-
retrieval_system = None
|
| 25 |
-
response_generator = None
|
| 26 |
-
history_manager = None
|
| 27 |
-
init_lock = Lock()
|
| 28 |
-
is_initialized = False
|
| 29 |
-
|
| 30 |
-
def initialize_components():
|
| 31 |
-
global retrieval_system, response_generator, history_manager, is_initialized
|
| 32 |
-
with init_lock:
|
| 33 |
-
if not is_initialized:
|
| 34 |
-
try:
|
| 35 |
-
from src.retrieval import RetrievalSystem
|
| 36 |
-
from src.generation import ResponseGenerator
|
| 37 |
-
from src.history import HistoryManager
|
| 38 |
-
|
| 39 |
-
# Retry mechanism for model initialization
|
| 40 |
-
for attempt in range(1, 4):
|
| 41 |
-
try:
|
| 42 |
-
retrieval_system = RetrievalSystem(config["data"]["document_path"], config["retrieval"]["model"])
|
| 43 |
-
response_generator = ResponseGenerator(config["generation"]["model_name"])
|
| 44 |
-
history_manager = HistoryManager(config["data"]["history_path"])
|
| 45 |
-
break
|
| 46 |
-
except Exception as e:
|
| 47 |
-
logger.warning("Attempt %d failed to initialize components: %s", attempt, e)
|
| 48 |
-
if attempt == 3:
|
| 49 |
-
logger.error("Failed to initialize components after 3 attempts: %s", e)
|
| 50 |
-
raise
|
| 51 |
-
time.sleep(5) # Wait before retrying
|
| 52 |
|
| 53 |
-
|
| 54 |
-
logger.info("Successfully initialized RetrievalSystem, ResponseGenerator, and HistoryManager")
|
| 55 |
-
except Exception as e:
|
| 56 |
-
logger.error("Initialization error: %s", e)
|
| 57 |
-
raise
|
| 58 |
-
|
| 59 |
-
# Start background thread to initialize models
|
| 60 |
-
threading.Thread(target=initialize_components, daemon=True).start()
|
| 61 |
-
|
| 62 |
-
# Quick replies for Rupeia categories
|
| 63 |
QUICK_REPLIES = [
|
| 64 |
-
{"title": "
|
| 65 |
-
{"title": "
|
| 66 |
-
{"title": "
|
| 67 |
-
{"title": "Gadgets", "value": "Help me save for a gadget"},
|
| 68 |
-
{"title": "News & Blogs", "value": "Show me financial news"}
|
| 69 |
]
|
| 70 |
|
| 71 |
@app.route('/')
|
| 72 |
-
def
|
| 73 |
return render_template('index.html')
|
| 74 |
|
| 75 |
@app.route('/api/chat', methods=['POST'])
|
| 76 |
def chat():
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
logger.info("Sent welcome message")
|
| 98 |
-
return jsonify({"text": response, "quickReplies": QUICK_REPLIES})
|
| 99 |
-
|
| 100 |
-
# Retrieve context using RAG
|
| 101 |
-
context = retrieval_system.get_context(user_input)
|
| 102 |
-
logger.info("Retrieved context: %s", context)
|
| 103 |
-
|
| 104 |
-
# Generate response
|
| 105 |
-
response = response_generator.generate_response(user_input, context, history)
|
| 106 |
-
logger.info("Generated response: %s", response)
|
| 107 |
-
|
| 108 |
-
# Update history
|
| 109 |
-
history.append((user_input, response))
|
| 110 |
-
history_manager.save_history(history)
|
| 111 |
-
|
| 112 |
-
# Return response with quick replies
|
| 113 |
-
return jsonify({"text": response, "quickReplies": QUICK_REPLIES})
|
| 114 |
-
|
| 115 |
-
except Exception as e:
|
| 116 |
-
logger.error("Error processing chat request: %s", e)
|
| 117 |
-
return jsonify({"text": f"Sorry, we're experiencing technical difficulties: {str(e)}", "quickReplies": []}), 500
|
| 118 |
-
|
| 119 |
-
if __name__ == "__main__":
|
| 120 |
-
app.run(host="0.0.0.0", port=8000, debug=True)
|
|
|
|
| 1 |
from flask import Flask, render_template, request, jsonify
|
| 2 |
+
from src.retrieval import retrieve_relevant_documents
|
| 3 |
+
from src.generation import generate_response
|
| 4 |
+
from src.history import save_conversation, load_conversation
|
| 5 |
import yaml
|
| 6 |
+
import os
|
| 7 |
+
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
app = Flask(__name__)
|
| 10 |
|
| 11 |
# Load configuration
|
| 12 |
+
with open('config/config.yaml', 'r') as f:
|
| 13 |
+
config = yaml.safe_load(f)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# Initialize quick replies
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
QUICK_REPLIES = [
|
| 17 |
+
{"title": "Investment options", "value": "investment options"},
|
| 18 |
+
{"title": "Saving goals", "value": "saving goals"},
|
| 19 |
+
{"title": "Account benefits", "value": "account benefits"}
|
|
|
|
|
|
|
| 20 |
]
|
| 21 |
|
| 22 |
@app.route('/')
|
| 23 |
+
def home():
|
| 24 |
return render_template('index.html')
|
| 25 |
|
| 26 |
@app.route('/api/chat', methods=['POST'])
|
| 27 |
def chat():
|
| 28 |
+
user_message = request.json.get('message', '')
|
| 29 |
+
conversation_id = request.json.get('conversation_id', str(datetime.now().timestamp()))
|
| 30 |
+
|
| 31 |
+
# Retrieve relevant documents
|
| 32 |
+
context = retrieve_relevant_documents(user_message)
|
| 33 |
+
|
| 34 |
+
# Generate response
|
| 35 |
+
bot_response = generate_response(user_message, context)
|
| 36 |
+
|
| 37 |
+
# Save conversation
|
| 38 |
+
save_conversation(conversation_id, user_message, bot_response)
|
| 39 |
+
|
| 40 |
+
return jsonify({
|
| 41 |
+
'text': bot_response,
|
| 42 |
+
'quickReplies': QUICK_REPLIES,
|
| 43 |
+
'conversation_id': conversation_id
|
| 44 |
+
})
|
| 45 |
+
|
| 46 |
+
if __name__ == '__main__':
|
| 47 |
+
app.run(host='0.0.0.0', port=8000, debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|