ayush2917 commited on
Commit
95058d6
·
verified ·
1 Parent(s): b24d396

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -105
app.py CHANGED
@@ -1,120 +1,47 @@
1
  from flask import Flask, render_template, request, jsonify
 
 
 
2
  import yaml
3
- import json
4
- import logging
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
- try:
17
- with open("config/config.yaml", "r") as f:
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
- is_initialized = True
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": "Investments", "value": "Tell me about investments"},
65
- {"title": "Goals", "value": "How can I set financial goals?"},
66
- {"title": "Benefits", "value": "What are the benefits of Rupeia?"},
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 index():
73
  return render_template('index.html')
74
 
75
  @app.route('/api/chat', methods=['POST'])
76
  def chat():
77
- # Ensure components are initialized
78
- if not is_initialized:
79
- initialize_components()
80
-
81
- try:
82
- data = request.get_json()
83
- user_input = data.get('message', '').strip()
84
- if not user_input:
85
- return jsonify({"text": "Please provide a message.", "quickReplies": []}), 400
86
-
87
- logger.info("Received user message: %s", user_input)
88
-
89
- # Load history
90
- history = history_manager.load_history()
91
-
92
- # Handle welcome message
93
- if user_input.lower() == "hello":
94
- response = "Hi there! How can I help you today?"
95
- history.append(("hello", response))
96
- history_manager.save_history(history)
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)