File size: 7,051 Bytes
bc939ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import re
import requests
from datetime import datetime
import uuid
import json
import os
import random
import streamlit as st
from ollama_integration import (
    get_ollama_response,
    stream_ollama_response,
    get_ai_response,
    stream_ai_response,
    get_active_backend,
    is_banking_query
)

USER_FILE = "users.json"
SESSION_FILE = "session.json"
HISTORY_FILE = "chat_history.json"
INTENTS_FILE = os.path.join("data", "intents.json")

@st.cache_data
def load_intents():
    if not os.path.exists(INTENTS_FILE):
        return {"intents": []}
    try:
        with open(INTENTS_FILE, "r") as f:
            return json.load(f)
    except Exception as e:
        print(f"Error loading intents: {e}")
        return {"intents": []}

# Global intents data, initialized from cached function
intents_data = load_intents()

def persist_user(username, email, password):
    users = get_persisted_users()
    users[username] = {"email": email, "password": password}
    with open(USER_FILE, "w") as f:
        json.dump(users, f)

def get_persisted_users():
    if not os.path.exists(USER_FILE):
        return {}
    try:
        with open(USER_FILE, "r") as f:
            return json.load(f)
    except:
        return {}

def save_active_session(username):
    with open(SESSION_FILE, "w") as f:
        json.dump({"username": username}, f)

def get_active_session():
    if not os.path.exists(SESSION_FILE):
        return None
    try:
        with open(SESSION_FILE, "r") as f:
            data = json.load(f)
            return data.get("username")
    except:
        return None

def clear_active_session():
    if os.path.exists(SESSION_FILE):
        os.remove(SESSION_FILE)

def validate_email(email):
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None

def validate_password_strength(password):
    if len(password) < 8:
        return False, "Password must be at least 8 characters long"
    
    if not re.search(r'[A-Z]', password):
        return False, "Password must contain at least one uppercase letter"
    
    if not re.search(r'[a-z]', password):
        return False, "Password must contain at least one lowercase letter"
    
    if not re.search(r'\d', password):
        return False, "Password must contain at least one number"
    
    if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
        return False, "Password must contain at least one special character"
    
    return True, "Password is strong"

def format_currency(amount):
    return f"₹{amount:,.2f}"

def get_timestamp():
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

def generate_session_id():
    return str(uuid.uuid4())

def get_chat_preview(messages, max_length=50):
    if not messages:
        return "Empty chat"
    
    for msg in messages:
        if msg["role"] == "user":
            content = msg["content"]
            if len(content) > max_length:
                return content[:max_length] + "..."
            return content
    
    return "No user messages"

@st.cache_data(ttl=30)
def load_history_file():
    if not os.path.exists(HISTORY_FILE):
        return {}
    try:
        with open(HISTORY_FILE, "r") as f:
            return json.load(f)
    except:
        return {}

def save_history_file(history):
    with open(HISTORY_FILE, "w") as f:
        json.dump(history, f, indent=4)

def get_all_chat_sessions(username):
    history = load_history_file()
    return history.get(username, [])

def save_chat_session(username, session_state, messages, session_id=None):
    if not messages or len(messages) == 0:
        return None
    
    history = load_history_file()
    user_sessions = history.get(username, [])
    
    if session_id:
        # Update existing session
        found = False
        for session in user_sessions:
            if session["session_id"] == session_id:
                session["messages"] = messages
                session["preview"] = get_chat_preview(messages)
                session["timestamp"] = get_timestamp()
                found = True
                break
        
        # Also update in-memory session_state for immediate UI feedback
        for session in session_state.chat_sessions:
            if session["session_id"] == session_id:
                session["messages"] = messages
                session["preview"] = get_chat_preview(messages)
                session["timestamp"] = get_timestamp()
                break
    else:
        # Create new session
        session_id = generate_session_id()
        new_session = {
            "session_id": session_id,
            "timestamp": get_timestamp(),
            "messages": messages,
            "preview": get_chat_preview(messages)
        }
        user_sessions.insert(0, new_session)
        
        if "chat_sessions" not in session_state:
            session_state.chat_sessions = []
        session_state.chat_sessions.insert(0, new_session)

    history[username] = user_sessions
    save_history_file(history)
    return session_id

def load_chat_session(username, session_id):
    user_sessions = get_all_chat_sessions(username)
    for session in user_sessions:
        if session["session_id"] == session_id:
            return session["messages"]
    return None

def delete_chat_session(username, session_state, session_id):
    history = load_history_file()
    user_sessions = history.get(username, [])
    
    user_sessions = [s for s in user_sessions if s["session_id"] != session_id]
    history[username] = user_sessions
    save_history_file(history)
    
    if "chat_sessions" in session_state:
        session_state.chat_sessions = [s for s in session_state.chat_sessions if s["session_id"] != session_id]
    return True

def clear_all_chat_history(username, session_state):
    history = load_history_file()
    history[username] = []
    save_history_file(history)
    
    session_state.chat_sessions = []
    return True

@st.cache_data(ttl=10)
def check_ollama_connection():
    from ollama_integration import check_ollama_connection as _check
    return _check()

def get_faq_response(prompt):
    """
    Checks if the user's prompt matches any common frequently asked questions
    using the structured intents.json data.
    """
    prompt_lower = prompt.lower().strip()
    
    if not intents_data or "intents" not in intents_data:
        return None

    # Iterate through intents to find a matching pattern
    for intent in intents_data["intents"]:
        for pattern in intent["patterns"]:
            p_lower = pattern.lower()
            # For short patterns (like 'hi'), use word boundary check
            if len(p_lower) <= 3:
                if re.search(rf"\b{re.escape(p_lower)}\b", prompt_lower):
                    return random.choice(intent["responses"])
            # For longer patterns, substring match is usually fine and more flexible
            elif p_lower in prompt_lower:
                return random.choice(intent["responses"])
            
    return None