upd server

This commit is contained in:
Oleh Poiasnik 2025-05-08 16:26:26 +00:00
parent 972e475233
commit 2fc7a2eb4a

View File

@ -1,365 +1,375 @@
import time import time
import re import re
from flask import Flask, request, jsonify from flask import Flask, request, jsonify
from flask_cors import CORS from flask_cors import CORS
from google.oauth2 import id_token from google.oauth2 import id_token
from google.auth.transport import requests as google_requests from google.auth.transport import requests as google_requests
import logging import logging
import psycopg2 import psycopg2
from psycopg2.extras import RealDictCursor from psycopg2.extras import RealDictCursor
from model import process_query_with_mistral from model import process_query_with_mistral
_real_time = time.time _real_time = time.time
time.time = lambda: _real_time() - 1 time.time = lambda: _real_time() - 1
# Database connection parameters # Database connection parameters
DATABASE_CONFIG = { DATABASE_CONFIG = {
"dbname": "HealthAIDB", "dbname": "HealthAIDB",
"user": "postgres", "user": "postgres",
"password": "Oleg2005", "password": "Oleg2005",
"host": "postgres", "host": "localhost",
"port": 5432, "port": 5432,
} }
import logging import logging
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
try: try:
conn = psycopg2.connect(**DATABASE_CONFIG) conn = psycopg2.connect(**DATABASE_CONFIG)
logger.info("Database connection established successfully") logger.info("Database connection established successfully")
except Exception as e: except Exception as e:
logger.error(f"Error connecting to database: {e}", exc_info=True) logger.error(f"Error connecting to database: {e}", exc_info=True)
conn = None conn = None
def init_db(): def init_db():
create_users_query = """ create_users_query = """
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
name TEXT NOT NULL, name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL, email TEXT UNIQUE NOT NULL,
google_id TEXT, google_id TEXT,
password TEXT, password TEXT,
phone TEXT, phone TEXT,
role TEXT, role TEXT,
bio TEXT, bio TEXT,
picture TEXT picture TEXT
); );
""" """
create_chat_history_query = """ create_chat_history_query = """
CREATE TABLE IF NOT EXISTS chat_history ( CREATE TABLE IF NOT EXISTS chat_history (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
user_email TEXT NOT NULL, user_email TEXT NOT NULL,
chat TEXT NOT NULL, chat TEXT NOT NULL,
user_data TEXT, user_data TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
); );
""" """
try: try:
with conn.cursor() as cur: with conn.cursor() as cur:
cur.execute(create_users_query) cur.execute(create_users_query)
cur.execute(create_chat_history_query) cur.execute(create_chat_history_query)
conn.commit() conn.commit()
logger.info("Database tables initialized successfully") logger.info("Database tables initialized successfully")
except Exception as e: except Exception as e:
logger.error(f"Error initializing database tables: {e}", exc_info=True) logger.error(f"Error initializing database tables: {e}", exc_info=True)
conn.rollback() conn.rollback()
if conn: if conn:
init_db() init_db()
app = Flask(__name__) app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}}) CORS(app, resources={r"/api/*": {"origins": "*"}})
CLIENT_ID = "532143017111-4eqtlp0oejqaovj6rf5l1ergvhrp4vao.apps.googleusercontent.com" CLIENT_ID = "532143017111-4eqtlp0oejqaovj6rf5l1ergvhrp4vao.apps.googleusercontent.com"
def save_user_to_db(name, email, google_id=None, password=None): def save_user_to_db(name, email, google_id=None, password=None):
logger.info(f"Saving user {name} with email: {email} to the database") logger.info(f"Saving user {name} with email: {email} to the database")
try: try:
with conn.cursor(cursor_factory=RealDictCursor) as cur: with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute( cur.execute(
""" """
INSERT INTO users (name, email, google_id, password) INSERT INTO users (name, email, google_id, password)
VALUES (%s, %s, %s, %s) VALUES (%s, %s, %s, %s)
ON CONFLICT (email) DO NOTHING ON CONFLICT (email) DO NOTHING
""", """,
(name, email, google_id, password) (name, email, google_id, password)
) )
conn.commit() conn.commit()
logger.info(f"User {name} ({email}) saved successfully") logger.info(f"User {name} ({email}) saved successfully")
except Exception as e: except Exception as e:
logger.error(f"Error saving user {name} ({email}) to database: {e}", exc_info=True) logger.error(f"Error saving user {name} ({email}) to database: {e}", exc_info=True)
@app.route('/api/verify', methods=['POST']) @app.route('/api/verify', methods=['POST'])
def verify_token(): def verify_token():
logger.info("Received token verification request") logger.info("Received token verification request")
data = request.get_json() data = request.get_json()
token = data.get('token') token = data.get('token')
if not token: if not token:
logger.warning("Token not provided in request") logger.warning("Token not provided in request")
return jsonify({'error': 'No token provided'}), 400 return jsonify({'error': 'No token provided'}), 400
try: try:
id_info = id_token.verify_oauth2_token(token, google_requests.Request(), CLIENT_ID) id_info = id_token.verify_oauth2_token(token, google_requests.Request(), CLIENT_ID)
user_email = id_info.get('email') user_email = id_info.get('email')
user_name = id_info.get('name') user_name = id_info.get('name')
google_id = id_info.get('sub') google_id = id_info.get('sub')
logger.info(f"Token verified for user: {user_name} ({user_email})") logger.info(f"Token verified for user: {user_name} ({user_email})")
save_user_to_db(name=user_name, email=user_email, google_id=google_id) save_user_to_db(name=user_name, email=user_email, google_id=google_id)
return jsonify({'message': 'Authentication successful', 'user': {'email': user_email, 'name': user_name}}), 200 return jsonify({'message': 'Authentication successful', 'user': {'email': user_email, 'name': user_name}}), 200
except ValueError as e: except ValueError as e:
logger.error(f"Token verification error: {e}", exc_info=True) logger.error(f"Token verification error: {e}", exc_info=True)
return jsonify({'error': 'Invalid token'}), 400 return jsonify({'error': 'Invalid token'}), 400
@app.route('/api/register', methods=['POST'])
def register(): @app.errorhandler(404)
logger.info("Received new user registration request") def not_found(e):
data = request.get_json() return jsonify({'error': 'Not found'}), 404
name = data.get('name')
email = data.get('email') @app.errorhandler(500)
password = data.get('password') def internal_error(e):
if not all([name, email, password]): return jsonify({'error': 'Internal server error'}), 500
logger.warning("Not all required fields provided for registration")
return jsonify({'error': 'All fields are required'}), 400
try: @app.route('/api/register', methods=['POST'])
with conn.cursor(cursor_factory=RealDictCursor) as cur: def register():
cur.execute("SELECT * FROM users WHERE email = %s", (email,)) logger.info("Received new user registration request")
existing_user = cur.fetchone() data = request.get_json()
if existing_user: name = data.get('name')
logger.warning(f"User with email {email} already exists") email = data.get('email')
return jsonify({'error': 'User already exists'}), 409 password = data.get('password')
save_user_to_db(name=name, email=email, password=password) if not all([name, email, password]):
logger.info(f"User {name} ({email}) registered successfully") logger.warning("Not all required fields provided for registration")
return jsonify({'message': 'User registered successfully'}), 201 return jsonify({'error': 'All fields are required'}), 400
except Exception as e: try:
logger.error(f"Error during user registration: {e}", exc_info=True) with conn.cursor(cursor_factory=RealDictCursor) as cur:
return jsonify({'error': str(e)}), 500 cur.execute("SELECT * FROM users WHERE email = %s", (email,))
existing_user = cur.fetchone()
@app.route('/api/login', methods=['POST']) if existing_user:
def login(): logger.warning(f"User with email {email} already exists")
logger.info("Received login request") return jsonify({'error': 'User already exists'}), 409
data = request.get_json() save_user_to_db(name=name, email=email, password=password)
email = data.get('email') logger.info(f"User {name} ({email}) registered successfully")
password = data.get('password') return jsonify({'message': 'User registered successfully'}), 201
if not all([email, password]): except Exception as e:
logger.warning("Email or password not provided") logger.error(f"Error during user registration: {e}", exc_info=True)
return jsonify({'error': 'Email and password are required'}), 400 return jsonify({'error': str(e)}), 500
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur: @app.route('/api/login', methods=['POST'])
cur.execute("SELECT * FROM users WHERE email = %s", (email,)) def login():
user = cur.fetchone() logger.info("Received login request")
if not user or user.get('password') != password: data = request.get_json()
logger.warning(f"Invalid credentials for email: {email}") email = data.get('email')
return jsonify({'error': 'Invalid credentials'}), 401 password = data.get('password')
logger.info(f"User {user.get('name')} ({email}) logged in successfully") if not all([email, password]):
return jsonify({'message': 'Login successful', 'user': {'name': user.get('name'), 'email': user.get('email')}}), 200 logger.warning("Email or password not provided")
except Exception as e: return jsonify({'error': 'Email and password are required'}), 400
logger.error(f"Error during user login: {e}", exc_info=True) try:
return jsonify({'error': str(e)}), 500 with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute("SELECT * FROM users WHERE email = %s", (email,))
user = cur.fetchone()
@app.route('/api/update_profile', methods=['PUT']) if not user or user.get('password') != password:
def update_profile(): logger.warning(f"Invalid credentials for email: {email}")
data = request.get_json() return jsonify({'error': 'Invalid credentials'}), 401
email = data.get('email') logger.info(f"User {user.get('name')} ({email}) logged in successfully")
if not email: return jsonify({'message': 'Login successful', 'user': {'name': user.get('name'), 'email': user.get('email')}}), 200
return jsonify({'error': 'Email is required'}), 400 except Exception as e:
logger.error(f"Error during user login: {e}", exc_info=True)
# Fields to update; if not provided, the current value remains. return jsonify({'error': str(e)}), 500
name = data.get('name')
phone = data.get('phone')
role = data.get('role') @app.route('/api/update_profile', methods=['PUT'])
bio = data.get('bio') def update_profile():
picture = data.get('picture') data = request.get_json()
email = data.get('email')
try: if not email:
with conn.cursor(cursor_factory=RealDictCursor) as cur: return jsonify({'error': 'Email is required'}), 400
cur.execute(
""" # Fields to update; if not provided, the current value remains.
UPDATE users name = data.get('name')
SET name = COALESCE(%s, name), phone = data.get('phone')
phone = COALESCE(%s, phone), role = data.get('role')
role = COALESCE(%s, role), bio = data.get('bio')
bio = COALESCE(%s, bio), picture = data.get('picture')
picture = COALESCE(%s, picture)
WHERE email = %s try:
""", with conn.cursor(cursor_factory=RealDictCursor) as cur:
(name, phone, role, bio, picture, email) cur.execute(
) """
conn.commit() UPDATE users
logger.info(f"Profile updated for {email}") SET name = COALESCE(%s, name),
return jsonify({'message': 'Profile updated successfully'}), 200 phone = COALESCE(%s, phone),
except Exception as e: role = COALESCE(%s, role),
logger.error(f"Error updating profile: {e}") bio = COALESCE(%s, bio),
return jsonify({'error': str(e)}), 500 picture = COALESCE(%s, picture)
WHERE email = %s
@app.route('/api/chat', methods=['POST']) """,
def chat(): (name, phone, role, bio, picture, email)
logger.info("Received chat request") )
data = request.get_json() conn.commit()
query = data.get('query', '') logger.info(f"Profile updated for {email}")
user_email = data.get('email') return jsonify({'message': 'Profile updated successfully'}), 200
chat_id = data.get('chatId') except Exception as e:
logger.error(f"Error updating profile: {e}")
if not query: return jsonify({'error': str(e)}), 500
logger.warning("No query provided")
return jsonify({'error': 'No query provided'}), 400 @app.route('/api/chat', methods=['POST'])
def chat():
logger.info(f"Processing request for chatId: {chat_id if chat_id else 'new chat'} | Query: {query}") logger.info("Received chat request")
data = request.get_json()
# Retrieve chat context from the database query = data.get('query', '')
chat_context = "" user_email = data.get('email')
if chat_id: chat_id = data.get('chatId')
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur: if not query:
cur.execute("SELECT chat, user_data FROM chat_history WHERE id = %s", (chat_id,)) logger.warning("No query provided")
result = cur.fetchone() return jsonify({'error': 'No query provided'}), 400
if result:
chat_context = result.get("chat", "") logger.info(f"Processing request for chatId: {chat_id if chat_id else 'new chat'} | Query: {query}")
logger.info(f"Loaded chat context for chatId {chat_id}: {chat_context}")
else: # Retrieve chat context from the database
logger.info(f"No chat context found for chatId {chat_id}") chat_context = ""
except Exception as e: if chat_id:
logger.error(f"Error loading chat context from DB: {e}", exc_info=True) try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
logger.info("Calling process_query_with_mistral function") cur.execute("SELECT chat, user_data FROM chat_history WHERE id = %s", (chat_id,))
response_obj = process_query_with_mistral(query, chat_id=chat_id, chat_context=chat_context) result = cur.fetchone()
best_answer = response_obj.get("best_answer", "") if isinstance(response_obj, dict) else str(response_obj) if result:
logger.info(f"Response from process_query_with_mistral: {best_answer}") chat_context = result.get("chat", "")
logger.info(f"Loaded chat context for chatId {chat_id}: {chat_context}")
best_answer = re.sub(r'[*#]', '', best_answer) else:
best_answer = re.sub(r'(\d\.\s)', r'\n\n\1', best_answer) logger.info(f"No chat context found for chatId {chat_id}")
best_answer = re.sub(r':\s-', r':\n-', best_answer) except Exception as e:
logger.error(f"Error loading chat context from DB: {e}", exc_info=True)
# Update or create chat_history record including user_data if available
if chat_id: logger.info("Calling process_query_with_mistral function")
try: response_obj = process_query_with_mistral(query, chat_id=chat_id, chat_context=chat_context)
with conn.cursor(cursor_factory=RealDictCursor) as cur: best_answer = response_obj.get("best_answer", "") if isinstance(response_obj, dict) else str(response_obj)
cur.execute("SELECT chat FROM chat_history WHERE id = %s", (chat_id,)) logger.info(f"Response from process_query_with_mistral: {best_answer}")
existing_chat = cur.fetchone()
if existing_chat: best_answer = re.sub(r'[*#]', '', best_answer)
updated_chat = existing_chat['chat'] + f"\nUser: {query}\nBot: {best_answer}" best_answer = re.sub(r'(\d\.\s)', r'\n\n\1', best_answer)
if "patient_data" in response_obj: best_answer = re.sub(r':\s-', r':\n-', best_answer)
cur.execute("UPDATE chat_history SET chat = %s, user_data = %s WHERE id = %s",
(updated_chat, response_obj["patient_data"], chat_id)) # Update or create chat_history record including user_data if available
else: if chat_id:
cur.execute("UPDATE chat_history SET chat = %s WHERE id = %s", (updated_chat, chat_id)) try:
conn.commit() with conn.cursor(cursor_factory=RealDictCursor) as cur:
logger.info(f"Chat history for chatId {chat_id} updated successfully") cur.execute("SELECT chat FROM chat_history WHERE id = %s", (chat_id,))
else: existing_chat = cur.fetchone()
with conn.cursor(cursor_factory=RealDictCursor) as cur2: if existing_chat:
cur2.execute( updated_chat = existing_chat['chat'] + f"\nUser: {query}\nBot: {best_answer}"
"INSERT INTO chat_history (user_email, chat) VALUES (%s, %s) RETURNING id", if "patient_data" in response_obj:
(user_email, f"User: {query}\nBot: {best_answer}") cur.execute("UPDATE chat_history SET chat = %s, user_data = %s WHERE id = %s",
) (updated_chat, response_obj["patient_data"], chat_id))
new_chat_id = cur2.fetchone()['id'] else:
conn.commit() cur.execute("UPDATE chat_history SET chat = %s WHERE id = %s", (updated_chat, chat_id))
chat_id = new_chat_id conn.commit()
logger.info(f"New chat created with chatId: {chat_id}") logger.info(f"Chat history for chatId {chat_id} updated successfully")
except Exception as e: else:
logger.error(f"Error updating/creating chat history: {e}", exc_info=True) with conn.cursor(cursor_factory=RealDictCursor) as cur2:
return jsonify({'error': str(e)}), 500 cur2.execute(
else: "INSERT INTO chat_history (user_email, chat) VALUES (%s, %s) RETURNING id",
try: (user_email, f"User: {query}\nBot: {best_answer}")
with conn.cursor(cursor_factory=RealDictCursor) as cur: )
cur.execute( new_chat_id = cur2.fetchone()['id']
"INSERT INTO chat_history (user_email, chat) VALUES (%s, %s) RETURNING id", conn.commit()
(user_email, f"User: {query}\nBot: {best_answer}") chat_id = new_chat_id
) logger.info(f"New chat created with chatId: {chat_id}")
new_chat_id = cur.fetchone()['id'] except Exception as e:
conn.commit() logger.error(f"Error updating/creating chat history: {e}", exc_info=True)
chat_id = new_chat_id return jsonify({'error': str(e)}), 500
logger.info(f"New chat created with chatId: {chat_id}") else:
except Exception as e: try:
logger.error(f"Error creating new chat: {e}", exc_info=True) with conn.cursor(cursor_factory=RealDictCursor) as cur:
return jsonify({'error': str(e)}), 500 cur.execute(
"INSERT INTO chat_history (user_email, chat) VALUES (%s, %s) RETURNING id",
return jsonify({'response': {'best_answer': best_answer, 'model': response_obj.get("model", ""), 'chatId': chat_id}}), 200 (user_email, f"User: {query}\nBot: {best_answer}")
)
@app.route('/api/save_user_data', methods=['POST']) new_chat_id = cur.fetchone()['id']
def save_user_data(): conn.commit()
logger.info("Received request to save user data") chat_id = new_chat_id
data = request.get_json() logger.info(f"New chat created with chatId: {chat_id}")
chat_id = data.get('chatId') except Exception as e:
user_data = data.get('userData') logger.error(f"Error creating new chat: {e}", exc_info=True)
if not chat_id or not user_data: return jsonify({'error': str(e)}), 500
return jsonify({'error': 'chatId and userData are required'}), 400
try: return jsonify({'response': {'best_answer': best_answer, 'model': response_obj.get("model", ""), 'chatId': chat_id}}), 200
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute("UPDATE chat_history SET user_data = %s WHERE id = %s", (user_data, chat_id)) @app.route('/api/save_user_data', methods=['POST'])
conn.commit() def save_user_data():
logger.info(f"User data for chatId {chat_id} updated successfully") logger.info("Received request to save user data")
return jsonify({'message': 'User data updated successfully'}), 200 data = request.get_json()
except Exception as e: chat_id = data.get('chatId')
logger.error(f"Error updating user data: {e}", exc_info=True) user_data = data.get('userData')
return jsonify({'error': str(e)}), 500 if not chat_id or not user_data:
return jsonify({'error': 'chatId and userData are required'}), 400
@app.route('/api/chat_history', methods=['GET']) try:
def get_chat_history(): with conn.cursor(cursor_factory=RealDictCursor) as cur:
logger.info("Received request to get chat history") cur.execute("UPDATE chat_history SET user_data = %s WHERE id = %s", (user_data, chat_id))
user_email = request.args.get('email') conn.commit()
if not user_email: logger.info(f"User data for chatId {chat_id} updated successfully")
return jsonify({'error': 'User email is required'}), 400 return jsonify({'message': 'User data updated successfully'}), 200
try: except Exception as e:
with conn.cursor(cursor_factory=RealDictCursor) as cur: logger.error(f"Error updating user data: {e}", exc_info=True)
cur.execute( return jsonify({'error': str(e)}), 500
"SELECT id, chat, user_data, created_at FROM chat_history WHERE user_email = %s ORDER BY created_at DESC",
(user_email,) @app.route('/api/chat_history', methods=['GET'])
) def get_chat_history():
history = cur.fetchall() logger.info("Received request to get chat history")
return jsonify({'history': history}), 200 user_email = request.args.get('email')
except Exception as e: if not user_email:
logger.error(f"Error getting chat history for {user_email}: {e}", exc_info=True) return jsonify({'error': 'User email is required'}), 400
return jsonify({'error': str(e)}), 500 try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
@app.route('/api/chat_history', methods=['DELETE']) cur.execute(
def delete_chat(): "SELECT id, chat, user_data, created_at FROM chat_history WHERE user_email = %s ORDER BY created_at DESC",
logger.info("Received request to delete chat") (user_email,)
chat_id = request.args.get('id') )
if not chat_id: history = cur.fetchall()
return jsonify({'error': 'Chat id is required'}), 400 return jsonify({'history': history}), 200
try: except Exception as e:
with conn.cursor() as cur: logger.error(f"Error getting chat history for {user_email}: {e}", exc_info=True)
cur.execute("DELETE FROM chat_history WHERE id = %s", (chat_id,)) return jsonify({'error': str(e)}), 500
conn.commit()
return jsonify({'message': 'Chat deleted successfully'}), 200 @app.route('/api/chat_history', methods=['DELETE'])
except Exception as e: def delete_chat():
logger.error(f"Error deleting chat with chatId {chat_id}: {e}", exc_info=True) logger.info("Received request to delete chat")
return jsonify({'error': str(e)}), 500 chat_id = request.args.get('id')
if not chat_id:
@app.route('/api/get_user_data', methods=['GET']) return jsonify({'error': 'Chat id is required'}), 400
def get_user_data(): try:
chat_id = request.args.get('chatId') with conn.cursor() as cur:
if not chat_id: cur.execute("DELETE FROM chat_history WHERE id = %s", (chat_id,))
return jsonify({'error': 'Chat id is required'}), 400 conn.commit()
try: return jsonify({'message': 'Chat deleted successfully'}), 200
with conn.cursor(cursor_factory=RealDictCursor) as cur: except Exception as e:
cur.execute("SELECT user_data FROM chat_history WHERE id = %s", (chat_id,)) logger.error(f"Error deleting chat with chatId {chat_id}: {e}", exc_info=True)
result = cur.fetchone() return jsonify({'error': str(e)}), 500
if result and result.get("user_data"):
return jsonify({'user_data': result.get("user_data")}), 200 @app.route('/api/get_user_data', methods=['GET'])
else: def get_user_data():
return jsonify({'user_data': None}), 200 chat_id = request.args.get('chatId')
except Exception as e: if not chat_id:
logger.error(f"Error retrieving user data: {e}", exc_info=True) return jsonify({'error': 'Chat id is required'}), 400
return jsonify({'error': str(e)}), 500 try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
@app.route('/api/chat_history_detail', methods=['GET']) cur.execute("SELECT user_data FROM chat_history WHERE id = %s", (chat_id,))
def chat_history_detail(): result = cur.fetchone()
logger.info("Received request to get chat details") if result and result.get("user_data"):
chat_id = request.args.get('id') return jsonify({'user_data': result.get("user_data")}), 200
if not chat_id: else:
return jsonify({'error': 'Chat id is required'}), 400 return jsonify({'user_data': None}), 200
try: except Exception as e:
with conn.cursor(cursor_factory=RealDictCursor) as cur: logger.error(f"Error retrieving user data: {e}", exc_info=True)
cur.execute("SELECT id, chat, user_data, created_at FROM chat_history WHERE id = %s", (chat_id,)) return jsonify({'error': str(e)}), 500
chat = cur.fetchone()
if not chat: @app.route('/api/chat_history_detail', methods=['GET'])
return jsonify({'error': 'Chat not found'}), 404 def chat_history_detail():
return jsonify({'chat': chat}), 200 logger.info("Received request to get chat details")
except Exception as e: chat_id = request.args.get('id')
logger.error(f"Error getting chat details for chatId {chat_id}: {e}", exc_info=True) if not chat_id:
return jsonify({'error': str(e)}), 500 return jsonify({'error': 'Chat id is required'}), 400
try:
if __name__ == '__main__': with conn.cursor(cursor_factory=RealDictCursor) as cur:
logger.info("Starting Flask application") cur.execute("SELECT id, chat, user_data, created_at FROM chat_history WHERE id = %s", (chat_id,))
app.run(host='0.0.0.0', port=5000, debug=True) chat = cur.fetchone()
if not chat:
return jsonify({'error': 'Chat not found'}), 404
return jsonify({'chat': chat}), 200
except Exception as e:
logger.error(f"Error getting chat details for chatId {chat_id}: {e}", exc_info=True)
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
logger.info("Starting Flask application")
app.run(host='0.0.0.0', port=5000, debug=True)