Skip to content

Commit 9d45ca9

Browse files
committed
fixed_code generation issue with better stability
1 parent 5c00a73 commit 9d45ca9

14 files changed

Lines changed: 739 additions & 395 deletions

File tree

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,8 @@ templates/style.css
99
.gitignore
1010
/python
1111
.vscode/settings.json
12+
static/resource/20241126011143_Notification-and-Programme-for-BTech-RIST-Odd-Semester-December-2024.pdf
13+
static/resource/an-old-hope.min.css
14+
/.gitignore
15+
from ollama import chat.py
16+
demo.html

index.py

Lines changed: 101 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -6,63 +6,101 @@
66
import datetime
77
import threading
88
from queue import Queue
9-
9+
import uuid
1010
con_path = ""
11-
app = Flask(__name__, template_folder='templates')
12-
11+
date_str = ""
1312
conversation = []
1413
clients = []
1514
chat_history = []
1615
clients_lock = threading.Lock()
1716
stream_flow = False
18-
date_time = datetime.datetime.now()
19-
20-
# Save conversation in a new file
21-
def save_conversation():
22-
global con_path # Use the global variable to store the file path across calls
17+
chat_title = "Starting New chat"
18+
app = Flask(__name__, template_folder='templates')
2319

20+
def getId():
21+
global date_str
22+
current_time = datetime.datetime.now()
23+
formatted_time = current_time.strftime("%Y%m%d_%H%M%S")
24+
date_str = formatted_time
25+
print(date_str)
26+
getId()
27+
def save_conversation(create_new_file=False):
28+
global con_path, date_str,chat_title # Use the global variables to store the file path and date_str across calls
2429
# Define the folder where logs are stored
2530
folder_name = 'log_data/conversation_logs'
2631
if not os.path.exists(folder_name):
2732
os.makedirs(folder_name)
28-
29-
# Get the current date (without time) to use as part of the filename
30-
date_str = datetime.datetime.now().strftime("%Y-%m-%d-%h-%m")
31-
32-
# If `con_path` is None or if it doesn't match today's date, create a new file path
33-
if not con_path or date_str not in con_path:
33+
if create_new_file or not con_path or date_str not in con_path:
3434
filename = f'conversation_{date_str}.json'
3535
con_path = os.path.join(folder_name, filename)
36+
elif not create_new_file and con_path:
37+
pass
38+
if not date_str:
39+
date_str = str(uuid.uuid4()) # Generate a unique date_str for the conversation
40+
41+
# Prepare the data structure with only the conversation array for subsequent saves
42+
conversation_data = {
43+
"chat_title" : chat_title,
44+
"chat_id": date_str,
45+
"conversation": conversation # Assume `conversation` is a list holding conversation data
46+
}
3647

3748
# Save or update the conversation data in the JSON file
3849
if os.path.exists(con_path):
39-
# Load existing data and append new data to it
50+
# Load existing data
4051
with open(con_path, 'r+') as f:
4152
try:
4253
existing_data = json.load(f)
4354
except json.JSONDecodeError:
4455
existing_data = []
45-
existing_data.extend(conversation)
56+
57+
# Check if the file already contains the conversation with the same chat_id
58+
existing_chat_ids = [entry["chat_id"] for entry in existing_data]
59+
if date_str in existing_chat_ids:
60+
# If the chat_id already exists, just update the existing conversation array
61+
for entry in existing_data:
62+
if entry["chat_id"] == date_str:
63+
entry["conversation"] = conversation # Overwrite the conversation data
64+
break
65+
else:
66+
# Add new conversation if chat_id doesn't exist
67+
existing_data.append(conversation_data)
68+
69+
# Save the updated conversation data back to the file
4670
f.seek(0)
4771
json.dump(existing_data, f, indent=4)
72+
4873
else:
4974
# Create new file if it doesn't exist
5075
with open(con_path, 'w') as f:
51-
json.dump(conversation, f, indent=4)
76+
json.dump([conversation_data], f, indent=4) # Wrap in a list to store multiple conversations
5277

5378
print(f"Conversation saved to {con_path}")
5479

80+
def new_chat(title,create_new_file=False):
81+
print("Request for new chat.")
82+
global conversation, con_path, chat_title
83+
conversation = []
84+
con_path = ""
85+
chat_title = title
86+
getId()
87+
save_conversation(create_new_file=True)
88+
5589
def client(data):
5690
"""Send data to all connected clients."""
5791
with clients_lock:
5892
for client in clients:
5993
client.put(data)
6094

6195
# Generate LLM response
62-
def generate_response(prompt, model):
63-
print(prompt, model)
96+
def generate_response(prompt, model,chat_request):
97+
print(prompt, model,chat_request)
6498
if prompt == "":
6599
return
100+
if chat_request == True:
101+
print("true")
102+
new_chat(prompt[:20])
103+
66104
user_rep_st = "[|/__USER_START__/|]"
67105
client(user_rep_st)
68106
client(f"{prompt}")
@@ -98,18 +136,17 @@ def generate_response(prompt, model):
98136
save_conversation()
99137

100138
client(done_marker)
101-
102139
def process(message_chunk):
103-
match message_chunk:
104-
case _ if "\n" in message_chunk or message_chunk == "":
105-
message_chunk = "<br>"
106-
case _ if "\n\n\n" in message_chunk:
107-
message_chunk = "<hr><br><br>"
108-
case _:
109-
pass
110-
140+
# Replace patterns in the correct order
141+
if "\n\n\n" in message_chunk: # Triple line breaks
142+
message_chunk = message_chunk.replace("\n\n\n", "<hr><br><br>")
143+
if "\n\n" in message_chunk: # Double line breaks
144+
message_chunk = message_chunk.replace("\n\n", "<br><br>")
145+
if "\n" in message_chunk: # Single line breaks
146+
message_chunk = message_chunk.replace("\n", "<br>")
111147
client(message_chunk)
112148

149+
113150
@app.route('/')
114151
def index():
115152
return render_template('index.html')
@@ -120,7 +157,8 @@ def get_response():
120157
data = request.get_json()
121158
prompt = data.get('prompt')
122159
model = data.get('model_need')
123-
response = generate_response(prompt, model)
160+
chat_request = data.get("new_chat")
161+
response = generate_response(prompt, model,chat_request)
124162
return jsonify({'response': 'Success'})
125163

126164
@app.route("/get_cmd", methods=["POST"])
@@ -158,6 +196,40 @@ def list_llm():
158196
if request.method == 'POST':
159197
list = ollama.list()
160198
return jsonify({"list": list})
199+
@app.route('/get_chats', methods=['POST'])
200+
def get_chats():
201+
folder_name = 'log_data/conversation_logs'
202+
if not os.path.exists(folder_name):
203+
return jsonify({"cat": "empty", "response": "Start chat"})
204+
files = os.listdir(folder_name)
205+
206+
json_files = [file for file in files if file.endswith('.json')]
161207

208+
if not json_files:
209+
return jsonify({"cat": "empty", "response": "No chats found"})
210+
211+
chat_titles = []
212+
213+
# Iterate through each .json file and extract the chat_title
214+
for json_file in json_files:
215+
file_path = os.path.join(folder_name, json_file)
216+
217+
try:
218+
with open(file_path, 'r') as f:
219+
data = json.load(f)
220+
221+
# Check if data is a list (list of chats)
222+
if isinstance(data, list):
223+
for chat in data:
224+
# Ensure 'chat_title' exists in each chat
225+
if "chat_title" in chat:
226+
chat_titles.append(chat["chat_title"])
227+
except json.JSONDecodeError:
228+
continue
229+
if not chat_titles:
230+
return jsonify({"cat": "empty", "response": "No valid chat titles found"})
231+
232+
# Return the list of chat titles
233+
return jsonify({"cat": "success", "response": chat_titles})
162234
if __name__ == '__main__':
163235
app.run(debug=True)

others/imga.png

136 KB
Loading

others/imgb.png

24.9 KB
Loading

others/imgc.png

73.3 KB
Loading

static/extra.css

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ body {
236236

237237
/* Style the tab container */
238238
.tab {
239+
/* display: flex; */
239240
float: left;
240241
background-color: rgb(42, 36, 61);
241242
width: 25%;
@@ -249,7 +250,7 @@ body {
249250
background-color: inherit;
250251
color: white;
251252
background-color: rgb(42, 36, 61);
252-
padding: 16px;
253+
/* padding: 16px; */
253254
width: 100%;
254255
border: none;
255256
outline: none;

static/feature.js

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -138,17 +138,6 @@ function send_mic_input(userPrompt) {
138138
}
139139
}
140140

141-
const STT_source = new EventSource("/sst_event");
142-
STT_source.onmessage = function (event) {
143-
if(allow_user_mic){
144-
const resp = event.data;
145-
console.log(resp);
146-
prompt += resp;
147-
sst_content.innerHTML += resp;
148-
}else
149-
console.log("User not allowed this")
150-
151-
};
152141
// Handeling tab is setting modal
153142
function openTab(evt, tabName) {
154143
var i, tabcontent, tablinks;

0 commit comments

Comments
 (0)