steve7909 commited on
Commit
8ba168f
·
1 Parent(s): 004a816

intitial commit

Browse files
Files changed (3) hide show
  1. .gitignore +4 -0
  2. app.py +336 -0
  3. requirements.txt +5 -0
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ environment.yml
2
+ .DS_Store
3
+ .env
4
+ Dockerfile
app.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from dotenv import load_dotenv
3
+ import os
4
+ import pandas as pd
5
+ import uuid
6
+ from datetime import datetime
7
+
8
+
9
+
10
+ use_local_llm = False
11
+
12
+
13
+ sentences_URL = "https://docs.google.com/spreadsheets/d/1w_MHR9coQQ7egMWbqMP8HkEysr31gKnqH2ysBzjQYfk/edit#gid=1183579691"
14
+ csv_sentence_URL = sentences_URL.replace('/edit#gid=', '/export?format=csv&gid=')
15
+
16
+ def get_sheets_sentences():
17
+
18
+ try:
19
+ csv_sheets_sentences_df = pd.read_csv(csv_sentence_URL)
20
+ print("### Successfully read CSV file from sheets")
21
+ except:
22
+ print("### Error reading CSV file from sheets")
23
+ return None
24
+
25
+ return csv_sheets_sentences_df
26
+
27
+ # Define a function to set the client based on the selection
28
+ def set_client(selection):
29
+
30
+ global use_local_llm
31
+
32
+ if selection == "Llama3":
33
+ import ollama
34
+ client = ollama.Client(host='http://10.236.173.45:11434')
35
+ use_local_llm = True
36
+ print("Using Llama3")
37
+ gr.Info(f"Using {selection}. Type in the chatbox to start.")
38
+ print(client.chat( # prime the model
39
+ model='llama3:70b',
40
+ messages=[{"role": "system", "content": "Get ready."}],
41
+ keep_alive= -1, # to prevent reloading model
42
+ options = {
43
+ 'num_predict':1
44
+ }
45
+ ))
46
+ print("### Llama3 model loaded")
47
+ else:
48
+ from openai import OpenAI
49
+
50
+ # Load environment variables from .env file
51
+ load_dotenv()
52
+ client = OpenAI(
53
+ api_key=os.getenv('OPENAI_API_KEY')
54
+ )
55
+ #OPEN_AI_KEY = ""
56
+ #client = OpenAI(api_key=OPEN_AI_KEY) # gross
57
+ use_local_llm = False
58
+ print("Using OpenAI")
59
+ gr.Info(f"Using {selection}. Type in the chatbox to start.")
60
+ return client
61
+
62
+ # Initialise the client (default to OpenAI)
63
+ client = set_client("OpenAI")
64
+
65
+ #file_path = 'anki_japanese_english_pairs.csv'
66
+ file_path = 'GPT generated Japanese English sentence pairs - Sheet2.csv'
67
+
68
+ def get_sentence_pair(level):
69
+
70
+ # Load the CSV file
71
+ #df = pd.read_csv(file_path)
72
+
73
+ df = get_sheets_sentences()
74
+
75
+ print(df.head())
76
+
77
+ if level == None:
78
+ level = 'Easy'
79
+ print("### Level not found - default to Easy")
80
+
81
+ # Filter the DataFrame based on the desired level
82
+ filtered_df = df[df['Difficulty'] == level]
83
+
84
+ # If the filtered DataFrame is empty, return None
85
+ if filtered_df.empty:
86
+ print("### No sentences found for this level")
87
+ return None
88
+
89
+ print(filtered_df.head())
90
+
91
+ # Select a random row from the filtered DataFrame
92
+ random_row = filtered_df.sample(1)
93
+
94
+ # Extract the Japanese and English sentences
95
+ japanese_sentence = str(random_row.iloc[0, 0])
96
+ english_sentence = str(random_row.iloc[0, 1])
97
+
98
+ print(f"### Level: {level}")
99
+ print(f"### Japanese sentence: {japanese_sentence}")
100
+ print(f"### English sentence: {english_sentence}")
101
+
102
+ return (japanese_sentence, english_sentence)
103
+
104
+ def generate_system_prompt(chat_id, japanese_sentence, english_sentence):
105
+
106
+ # removed_from_system_prompt = f'''
107
+
108
+ # - Do not respond in Japanese - always respond in English even if the student uses Japanese with you.
109
+ # '''
110
+
111
+ system_prompt = f'''
112
+ **Translation Training Session**
113
+
114
+ **Feedback form:**
115
+ [Feedback Form](https://docs.google.com/forms/d/e/1FAIpQLSdqllTmXz8tEGsXSQnX1dSxbOTHxsAeBLepdDYj8DNSTYautw/viewform?usp=pp_url&entry.1679182700={chat_id})
116
+
117
+ You are an assistant to help with Japanese to English translation practice.
118
+ Help students enhance their translation skills.
119
+
120
+ **Guidelines:**
121
+ - Use hints to improve the translation iteratively.
122
+ - Do not give the correct translation (model answer) directly. Let the student work it out.
123
+ - Provide your feedback as a list where possible.
124
+
125
+ - Where the translation is correct, don't ask for another attempt. Translations are correct where they are grammatically accurate and convey the same meaning as the model answer.
126
+ - When the translation is correct, always provide the user with the feedback form.
127
+ - Where possible make any corrections bold.
128
+ - Always explain any corrections you make clearly and concisely.
129
+ - Don't say you are making a correction if you are not changing anything about the provided translation.
130
+ - When giving hints, don't reveal the correct translation and don't repeat the same hint.
131
+ - When asked about the words, give the translation for each word individually, not the full sentence translation.
132
+ - Use Japanese quotes for Japanese text. I.e. 「問題」.
133
+ - Don't ask whether you should provide the feedback form, just provide it when the translation is correct.
134
+ - Do not ask if the student would like the feedback form, just provide it.
135
+
136
+ **Japanese Sentence to Translate:**
137
+ "{japanese_sentence}"
138
+
139
+ **English Sentence model answer:**
140
+ "{english_sentence}"
141
+
142
+ **Execute the following tasks:**
143
+ 1. Welcome the student. Ask the student to translate the Japanese Sentence to English. Show the Japanese sentence to the student.
144
+ 2. Suggest simple corrections (i.e., spelling, grammar, and punctuation). Where relevant, provide hints to improve the translation.
145
+ 3. If the translation is correct or or there are only minor errors, go to step 4. If not, ask for another translation attempt for the same sentence until the translation is correct (or close).
146
+ 4. When the translation is correct or the student gives up, provide the user with the feedback form (to get their thoughts on the chat). It is very important to show this form to the student.
147
+
148
+ **Feedback form:**
149
+ [Feedback Form](https://docs.google.com/forms/d/e/1FAIpQLSdqllTmXz8tEGsXSQnX1dSxbOTHxsAeBLepdDYj8DNSTYautw/viewform?usp=pp_url&entry.1679182700={chat_id})
150
+ '''
151
+
152
+ return system_prompt
153
+
154
+
155
+ def print_chat(openai_format):
156
+ for message in openai_format:
157
+ print(f"{message['role'].capitalize()}: {message['content']}")
158
+
159
+
160
+ def predict(message, history, chat_id, sentence_pair, level='Easy'):
161
+
162
+ print("### initial predict chat_id:", chat_id)
163
+ print("history length", len(history))
164
+ print("### sentence_pair:", sentence_pair)
165
+
166
+ # if not chat_id:
167
+ # chat_id = str(uuid.uuid4())[:8]
168
+
169
+ if not sentence_pair:
170
+ print("### Sentence not found - getting new sentence pair")
171
+ japanese_sentence, english_sentence = get_sentence_pair(level=level)
172
+ else:
173
+ japanese_sentence, english_sentence = sentence_pair[0], sentence_pair[1]
174
+
175
+ history_openai_format = [{"role": "system", "content": generate_system_prompt(chat_id, japanese_sentence, english_sentence)}]
176
+
177
+ for human, assistant in history:#[1:]:
178
+ history_openai_format.append({"role": "user", "content": human })
179
+ history_openai_format.append({"role": "assistant", "content":assistant})
180
+ history_openai_format.append({"role": "user", "content": message})
181
+
182
+ if use_local_llm:
183
+ stream = client.chat(
184
+ model='llama3:70b',
185
+ messages=history_openai_format,
186
+ stream=True,
187
+ keep_alive= -1, # to prevent reloading model
188
+ options = {
189
+ #'temperature': 1.5, # very creative
190
+ 'temperature': 0.2 # very conservative (good for correct syntax)
191
+
192
+ }
193
+ )
194
+
195
+ partial_message = ""
196
+ response_text = ""
197
+ for chunk in stream:
198
+ response_text += chunk['message']['content'] # steve added for full response text for export
199
+ partial_message = partial_message + chunk['message']['content']
200
+ yield partial_message
201
+ else:
202
+
203
+ response = client.chat.completions.create(
204
+ model='gpt-3.5-turbo',
205
+ messages= history_openai_format,
206
+ temperature=0.2,
207
+ stream=True
208
+ )
209
+
210
+ partial_message = ""
211
+ response_text = ""
212
+ for chunk in response:
213
+ if chunk.choices[0].delta.content is not None:
214
+ response_text += chunk.choices[0].delta.content # steve added for full response text for export
215
+ partial_message = partial_message + chunk.choices[0].delta.content
216
+ yield partial_message
217
+
218
+ # after display to user, for export and print
219
+ history_openai_format.append({"role": "assistant", "content": response_text})
220
+
221
+ #print("### final chat_id:", chat_id)
222
+ export_conversation(history_openai_format, chat_id)
223
+ print_chat(history_openai_format)
224
+
225
+ #return chat_id
226
+
227
+ css = """
228
+ h1 {
229
+ text-align: center;
230
+ display: block;
231
+ }
232
+ """
233
+
234
+ def generate_unique_id():
235
+ return str(uuid.uuid4())[:8]
236
+
237
+ # TODO: Add LLM type to messages; add difficulty level to messages
238
+ def export_conversation(history_openai_format, chat_id):
239
+
240
+ export_file_name = f"chat_{chat_id}.txt"
241
+
242
+ with open(export_file_name, "a") as file:
243
+
244
+ if file.tell() == 0:
245
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
246
+ file.write(f"Chat started: {chat_id} {timestamp}\n\n")
247
+
248
+ for message in history_openai_format:
249
+ #timestamp = datetime.now().strftime("%H:%M:%S")
250
+ #file.write(f"{timestamp}\t{message['role'].capitalize()}: {message['content']}\n")
251
+ file.write(f"{message['role'].capitalize()}: {message['content']}\n")
252
+
253
+ def reset(input):
254
+ return [], []
255
+
256
+ with gr.Blocks(css=css) as app:
257
+ gr.Markdown("""# <center><font size=8>{}</center>""".format("Hi, it's Tammy!"))
258
+
259
+ with gr.Row():
260
+
261
+ with gr.Column(scale=1):
262
+
263
+ gr.Markdown("""## Instructions""")
264
+ gr.Markdown("""
265
+ **Welcome to Tammy!**
266
+ - Type your message in the textbox and press enter or Submit to send.
267
+ - Click Retry if the chatbot is stuck or the response is a little strange.
268
+ - Your chats are recorded for quality assurance and training purposes. Behave.
269
+ """)
270
+
271
+
272
+ difficulty_level = gr.Dropdown(choices=["Easy", "Intermediate", "Advanced"], value="Easy", label="Difficulty Level", interactive=True)
273
+ # llm_type = gr.Dropdown(choices=["Llama3", "OpenAI"], value="OpenAI", label="Choose LLM Type")
274
+
275
+ # Define a function to handle changes in dropdown
276
+ # def update_client(llm):
277
+ # global client
278
+ # client = set_client(llm)
279
+
280
+ # Button to apply the change
281
+ # apply_btn = gr.Button("Apply")
282
+ # apply_btn.click(fn=update_client, inputs=llm_type, outputs=None)
283
+
284
+ # gr.Markdown(f"""[Click here](https://docs.google.com/forms/d/e/1FAIpQLSdqllTmXz8tEGsXSQnX1dSxbOTHxsAeBLepdDYj8DNSTYautw/viewform?usp=pp_url&entry.1679182700={chat_id})
285
+ # """)
286
+
287
+ with gr.Column(scale=3):
288
+
289
+ bot = gr.Chatbot(render=False, height=550)
290
+
291
+ sentence_pair_state = gr.State(get_sentence_pair(level=difficulty_level.value))
292
+ chat_id = gr.State(generate_unique_id)
293
+
294
+ #print("### ui chat_id:", chat_id)
295
+
296
+ chat = gr.ChatInterface(
297
+ predict,
298
+ chatbot=bot,
299
+ additional_inputs=[chat_id, sentence_pair_state, difficulty_level],
300
+ examples=[
301
+ ["Help me start", None, None, None],
302
+ ["Give me a hint", None, None, None],
303
+ ["I need more help", None, None, None],
304
+ ["What do you mean?", None, None, None],
305
+ ["What do the words mean?", None, None, None],
306
+ ["Let's stop now", None, None, None]
307
+ ],
308
+ )
309
+
310
+ difficulty_level.input(fn=reset, inputs=difficulty_level, outputs=[bot, chat.chatbot_state])
311
+
312
+ def update_sentence_pair(level):
313
+
314
+ global sentence_pair_state
315
+ gr.Info(f"New {level} sentence selected. Type in the chatbox to start.")
316
+ print("### updating level:", level)
317
+ sentence_pair = get_sentence_pair(level)
318
+ print("### new sentence pair:", sentence_pair)
319
+ sentence_pair_state = gr.State(sentence_pair)
320
+ return sentence_pair
321
+
322
+ # def clear_chat_history(level):
323
+ # bot.clear()
324
+ # gr.Info(f"New {level} sentence selected. Type in the chatbox to start.")
325
+ # print("### updating level:", level)
326
+ # sentence_pair.data = get_sentence_pair(level=level)
327
+
328
+ #difficulty_level.change(clear_chat_history, inputs=difficulty_level, outputs=sentence_pair)
329
+
330
+
331
+ difficulty_level.change(update_sentence_pair, inputs=difficulty_level, outputs=sentence_pair_state)
332
+
333
+
334
+ app.launch()
335
+
336
+
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio==4.27.0
2
+ ollama==0.1.8
3
+ openai==1.23.3
4
+ pandas==2.2.2
5
+ python-dotenv==1.0.1