From 7eb29cce83aa0a6b4e5a87fbeddd1024c17c7201 Mon Sep 17 00:00:00 2001 From: Russell Ballestrini Date: Tue, 11 Apr 2023 12:15:59 -0400 Subject: [PATCH] shove chat history into sqlite3 --- .gitignore | 2 ++ app.py | 54 +++++++++++++++++++++++++++++++++++++++++++-- requirements.txt | 5 ++--- templates/chat.html | 29 ++++++++++++++++++++++-- 4 files changed, 83 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 3bf2621..5c4119f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ *.swp env +instance/ +__pycache__/ diff --git a/app.py b/app.py index a6845fc..75a4d80 100644 --- a/app.py +++ b/app.py @@ -5,12 +5,36 @@ import eventlet import openai +openai.api_key = "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" + import markdown app = Flask(__name__) app.config['SECRET_KEY'] = 'your_secret_key' socketio = SocketIO(app, async_mode='eventlet') + +from flask_sqlalchemy import SQLAlchemy +app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///chat.db' +app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False +db = SQLAlchemy(app) + + +class Message(db.Model): + id = db.Column(db.Integer, primary_key=True) + username = db.Column(db.String(128), nullable=False) + content = db.Column(db.String(1024), nullable=False) + room = db.Column(db.String(128), nullable=False) + + def __init__(self, username, content, room): + self.username = username + self.content = content + self.room = room + +# Create the database and tables +#with app.app_context(): +# db.create_all() + @app.route('/') def index(): return render_template('index.html') @@ -23,13 +47,31 @@ def chat(room): def on_join(data): room = data['room'] join_room(room) + + # Fetch previous messages from the database + previous_messages = Message.query.filter_by(room=room).all() + + for message in previous_messages: + emit( + 'previous_messages', + {'username': message.username, 'message': message.content}, + room=request.sid + ) + emit('message', f"{data['username']} has joined the room.", room=room) @socketio.on('message') def handle_message(data): + # Save the message to the database + new_message = Message(username=data['username'], content=data['message'], room=data['room']) + db.session.add(new_message) + db.session.commit() + emit('message', f"{data['username']}: {data['message']}", room=data['room']) - openai.api_key = "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" + # Emit a temporary message indicating that GPT is processing + emit('message', f"Processing...", room=data['room']) + # Call the chat_gpt function without blocking using eventlet.spawn eventlet.spawn(chat_gpt, data['username'], data['room'], data['message']) @@ -48,9 +90,17 @@ def chat_gpt(username, room, message): # Convert response_text to Markdown response_md = markdown.markdown(response_text, extensions=['fenced_code']) + # Save ChatGPT's response in the database + with app.app_context(): + chatgpt_response_message = Message(username="GPT-3.5", content=response_md, room=room) + db.session.add(chatgpt_response_message) + db.session.commit() + + socketio.emit('delete_processing_message', "", room=room) + # Emit the response to the room socketio.emit('message', f"{username} (GPT-3.5): {response_md}", room=room) if __name__ == '__main__': - socketio.run(app, host='0.0.0.0', port=5000) + socketio.run(app, host='0.0.0.0', port=5001) diff --git a/requirements.txt b/requirements.txt index 859657a..e4ce108 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,6 +4,5 @@ eventlet openai markdown -# code highlights -Pygments -mdx_codehilite +# sqlite +Flask-SQLAlchemy diff --git a/templates/chat.html b/templates/chat.html index 282e76a..2349092 100644 --- a/templates/chat.html +++ b/templates/chat.html @@ -20,7 +20,7 @@ flex-direction: column; justify-content: center; align-items: center; - height: 100vh; + height: 75vh; margin: 0; } #chat-container { @@ -75,8 +75,33 @@ }); socket.on('message', (message) => { - $('#chat').append('

' + message + '

'); + var newMessage = document.createElement('p'); + newMessage.innerHTML = message; + $('#chat').append(newMessage); + + // Apply syntax highlighting to the new message + newMessage.querySelectorAll('pre code').forEach((block) => { + hljs.highlightElement(block); + }); + + // Scroll to the bottom of the chat container + $('#chat').scrollTop($('#chat')[0].scrollHeight); }); + + socket.on('previous_messages', (data) => { + $('#chat').append('

' + data.username + ': ' + data.message + '

'); + $('pre code').each((i, block) => { + hljs.highlightBlock(block); + }); + }); + + socket.on('delete_processing_message', (data) => { + const tempMessage = document.getElementById("processing"); + if (tempMessage) { + tempMessage.remove(); + } + }); +