Ubaidbhat commited on
Commit
3039852
·
verified ·
1 Parent(s): f068700

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +319 -0
app.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # App.py File.
2
+ import base64
3
+ import logging
4
+ import numpy as np
5
+ import os
6
+ import langchain
7
+ import base64
8
+ import gradio as gr
9
+ import shutil
10
+ import json
11
+ import re
12
+ from pathlib import Path
13
+ from openai import OpenAI
14
+ import soundfile as sf
15
+ from pydub import AudioSegment
16
+ from langchain_core.pydantic_v1 import BaseModel, Field
17
+ from langchain.chains import TransformChain
18
+ from langchain_core.messages import HumanMessage
19
+ from langchain_openai import ChatOpenAI
20
+ from langchain import globals
21
+ from langchain_core.runnables import chain
22
+ from langchain_core.output_parsers import JsonOutputParser
23
+ from langchain.memory import ConversationSummaryBufferMemory, ConversationBufferMemory
24
+
25
+ os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
26
+
27
+ client = OpenAI()
28
+
29
+ # Set up logging
30
+ logging.basicConfig(level=logging.INFO)
31
+ def transform_text_to_speech(text: str, user):
32
+ # Generate speech from transcription
33
+ speech_file_path_mp3 = Path.cwd() / f"{user}-speech.mp3"
34
+ speech_file_path_wav = Path.cwd() / f"{user}-speech.wav"
35
+ response = client.audio.speech.create(
36
+ model="tts-1",
37
+ voice="onyx",
38
+ input=text
39
+ )
40
+
41
+ with open(speech_file_path_mp3, "wb") as f:
42
+ f.write(response.content)
43
+
44
+ # Convert mp3 to wav
45
+ audio = AudioSegment.from_mp3(speech_file_path_mp3)
46
+ audio.export(speech_file_path_wav, format="wav")
47
+
48
+ # Read the audio file and encode it to base64
49
+ with open(speech_file_path_wav, "rb") as audio_file:
50
+ audio_data = audio_file.read()
51
+ audio_base64 = base64.b64encode(audio_data).decode('utf-8')
52
+
53
+ # Create an HTML audio player with autoplay
54
+ audio_html = f"""
55
+ <audio controls autoplay>
56
+ <source src="data:audio/wav;base64,{audio_base64}" type="audio/wav">
57
+ Your browser does not support the audio element.
58
+ </audio>
59
+ """
60
+ return audio_html
61
+
62
+
63
+ def transform_speech_to_text(audio, user):
64
+ file_path = f"{user}-saved_audio.wav"
65
+ sample_rate, audio_data = audio
66
+ sf.write(file_path, audio_data, sample_rate)
67
+ # Transcribe audio
68
+ with open(file_path, "rb") as audio_file:
69
+ transcription = client.audio.transcriptions.create(
70
+ model="whisper-1",
71
+ file=audio_file
72
+ )
73
+ return transcription.text
74
+
75
+
76
+
77
+ def load_image(inputs: dict) -> dict:
78
+ """Load image from file and encode it as base64."""
79
+ image_path = inputs["image_path"]
80
+
81
+ def encode_image(image_path):
82
+ with open(image_path, "rb") as image_file:
83
+ return base64.b64encode(image_file.read()).decode('utf-8')
84
+ image_base64 = encode_image(image_path)
85
+ return {"image": image_base64}
86
+
87
+ from langchain.chains import TransformChain
88
+ load_image_chain = TransformChain(
89
+ input_variables=["image_path"],
90
+ output_variables=["image"],
91
+ transform=load_image
92
+ )
93
+
94
+ class GenerateQuestion(BaseModel):
95
+ """Information about an image."""
96
+ question: str = Field(description= "React to the user input and ask a follow back question, using conversation and photo provded as a guide.")
97
+
98
+ class GenerateDescription(BaseModel):
99
+ """Information about an image."""
100
+ description: str = Field(description= "A description of the people and context in the photo in 2 lines and a question to start converstion around the photograph")
101
+
102
+ question_parser = JsonOutputParser(pydantic_object=GenerateQuestion)
103
+ description_parser = JsonOutputParser(pydantic_object=GenerateDescription)
104
+
105
+ # Set verbose
106
+ # globals.set_debug(True)
107
+
108
+ @chain
109
+ def image_model(inputs: dict) -> str | list[str] | dict:
110
+ """Invoke model with image and prompt."""
111
+ model = ChatOpenAI(temperature=0.5, model="gpt-4o", max_tokens=1024)
112
+ msg = model.invoke(
113
+ [HumanMessage(
114
+ content=[
115
+ {"type": "text", "text": inputs["prompt"]},
116
+ {"type": "text", "text": inputs["parser"].get_format_instructions()},
117
+ {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{inputs['image']}"}},
118
+ ])]
119
+ )
120
+ return msg.content
121
+
122
+ CONVERSATION_STARTER_PROMPT = """
123
+ Given the image uploaded by a old person named {name}.
124
+ You are Studs Terkel, and your role is to be a curious friend who is genuinely interested in the story behind the photograph that the older person has provided.
125
+ Provide the following information,
126
+ - A description of the image in 2 lines and a question that gives context to the photograph.
127
+ """
128
+
129
+
130
+ CONVERSATION_EXPANDING_PROMPT = """
131
+ Given the image uploaded by a old person named {name}.
132
+ Here is the conversation history around the Image between {name} and Studs Terkel:
133
+ {history}
134
+ You are Studs Terkel, and your role is to be a curious friend who is genuinely interested in the story behind the image uploaded by the {name}.
135
+ Your task is to use your external knowledge and conversation to respond to {name} recent reply and ask a question that encourages the person to expand on their answer about the photograph. Ask for more details or their feelings about the situation depicted in the photograph. Use the conversation history provided above and ask only one question at a time.
136
+ Use your knowledge to respond with the information.
137
+ Studs Terkel:
138
+ """
139
+
140
+
141
+ CONVERSATION_ENDING_PROMPT = """
142
+ Given the image uploaded by a old person named {name}.
143
+ Here is the conversation history around the Image between {name} and Stud's Terkel:
144
+ {history}
145
+ You are Studs Terkel, and your role is to be a curious friend who is genuinely interested in the story behind the image uploaded by the {name}.
146
+ Your task is to use your external knowledge , conversation history, image uploaded to respond to {name} recent reply and ask if they would like to tell more about the story depicted in the photograph, discuss anything that the photograph reminds them of, or if they are ready to move on to another photograph or stop reminiscing. Use the conversation history provided above and ask only one question at a time.
147
+ Studs Terkel:
148
+ """
149
+
150
+ def get_prompt(image_path: str, iter: int, memory: str, firstname: str) -> dict:
151
+
152
+ if iter == 1:
153
+ parser = description_parser
154
+ prompt = CONVERSATION_STARTER_PROMPT.format(name=firstname)
155
+ elif iter >= 2 and iter <= 5:
156
+ parser = question_parser
157
+ prompt= CONVERSATION_EXPANDING_PROMPT.format(name= firstname, history=memory)
158
+ else:
159
+ parser = question_parser
160
+ prompt= CONVERSATION_ENDING_PROMPT.format(name= firstname, history=memory)
161
+
162
+ vision_chain = load_image_chain | image_model | question_parser
163
+ return vision_chain.invoke({'image_path': f'{image_path}', 'prompt': prompt, 'parser':parser})
164
+
165
+
166
+
167
+ def retrieve_memory(input_filepath, name):
168
+ with open(input_filepath, 'r') as f:
169
+ conversation = f.read()
170
+ lines = conversation.strip().split('\n')
171
+ last_reply = None
172
+
173
+ # Loop through the lines from the end
174
+ for line in reversed(lines):
175
+ if re.match(r'(Studs Terkel|' + re.escape(name) + '):', line):
176
+ last_reply = line
177
+ break
178
+
179
+ # Determine who made the last reply, split it based on the colon, and return JSON
180
+ if last_reply:
181
+ speaker, message = last_reply.split(":", 1)
182
+ result = {
183
+ "speaker": speaker.strip(),
184
+ "reply": message.strip()
185
+ }
186
+ return result
187
+ else:
188
+ result = {
189
+ "speaker": "",
190
+ "reply": ""
191
+ }
192
+ return result
193
+
194
+ def load_counts(count_file_path):
195
+ if os.path.exists(count_file_path):
196
+ with open(count_file_path, 'r') as f:
197
+ return json.load(f)
198
+ return {"count": 0}
199
+
200
+ def save_counts(count_file_path, counts):
201
+ with open(count_file_path, 'w') as f:
202
+ json.dump(counts, f)
203
+
204
+ def increment_counts(count_file_path):
205
+ counts = load_counts(count_file_path)
206
+ counts["count"] += 1
207
+ save_counts(count_file_path, counts)
208
+ return counts["count"]
209
+
210
+ def pred(user_name, image_path, audio):
211
+
212
+ if image_path and user_name.strip() != "":
213
+ user_name = user_name.strip()
214
+ image_name = image_path.split("/")[-1]
215
+ new_image_name = f"{user_name}-{image_name}"
216
+ new_image_path = f"/data/{new_image_name}"
217
+ input_filename = f"{user_name}-{image_name}-conversation-memory.txt"
218
+ input_filepath = f"/data/{input_filename}"
219
+ count_file_path = f"/data/{user_name}-{image_name}-tracking.json"
220
+
221
+ if not os.path.exists(new_image_path):
222
+ shutil.copy(image_path, new_image_path)
223
+ iter = increment_counts(count_file_path)
224
+ output = get_prompt(new_image_path, iter, None, user_name)
225
+ res = output["description"]
226
+ with open(input_filepath, 'w') as f:
227
+ f.write("Studs Terkel: " + res)
228
+ return "New Photo Uploaded" , res, transform_text_to_speech(res, user_name)
229
+
230
+ else:
231
+
232
+ if audio is not None:
233
+ user_input = transform_speech_to_text(audio, user_name)
234
+
235
+ iter = increment_counts(count_file_path)
236
+ with open(input_filepath, 'a') as f:
237
+ f.write("\n" + user_name + ": " + user_input)
238
+ with open(input_filepath, 'r') as f:
239
+ content = f.read()
240
+ output = get_prompt(new_image_path, iter, content, user_name)
241
+ res = output["question"]
242
+ with open(input_filepath, 'a') as f:
243
+ f.write("\n" + "Studs Terkel: "+ res)
244
+ return user_input, res, transform_text_to_speech(res, user_name)
245
+
246
+
247
+
248
+
249
+ # decide the path from the contents of the conversation memory.
250
+ if os.path.exists(input_filepath):
251
+ res = retrieve_memory(input_filepath, user_name)
252
+ if res["speaker"] == "Studs Terkel":
253
+ if audio is None:
254
+ message = ""
255
+ return "Loading response, please wait...", "Loading response, please wait...", None
256
+ prefix = "Continuing from where we left off: "
257
+ return "" , prefix+ res["reply"], transform_text_to_speech(prefix+res["reply"], user_name)
258
+ else:
259
+ with open(input_filepath, 'a') as f:
260
+ f.write("\n" + user_name + ": " + "I'd like to continue our conversation about this photograph.")
261
+ with open(input_filepath, 'r') as f:
262
+ content = f.read()
263
+ iter = increment_counts(count_file_path)
264
+ output = get_prompt(new_image_path, iter, content, user_name)
265
+ res = output["question"]
266
+ with open(input_filepath, 'a') as f:
267
+ f.write("\n" + "Studs Terkel: "+ res)
268
+ return "I'd like to continue our conversation about this photograph.", res, transform_text_to_speech(res, user_name)
269
+
270
+ message = "Great! Please enter your name and upload a photo to share your story."
271
+ return "", message, None
272
+
273
+ # Backend function to clear inputs
274
+ def clear_inputs(user_name, image_path):
275
+ message = "Great! Please enter your name and upload a photo to share your story."
276
+ if user_name.strip() == "" or image_path == None:
277
+ return None, None, "", message, transform_text_to_speech(message, user_name)
278
+
279
+ image_name = image_path.split("/")[-1]
280
+ input_filename = f"{user_name}-{image_name}-conversation-memory.txt"
281
+ input_filepath = f"/data/{input_filename}"
282
+ if os.path.exists(input_filepath):
283
+ with open(input_filepath, 'a') as f:
284
+ f.write("\n" + f"{user_name}: " + "new photo uploaded")
285
+
286
+
287
+ return None, None, "", message, None
288
+
289
+ # Gradio Interface
290
+ with gr.Blocks(title = "KitchenTable.AI") as demo:
291
+ with gr.Row():
292
+ with gr.Column():
293
+ clear_button = gr.Button("Tell a new Story", elem_id="clear-button")
294
+ # Input fields
295
+ username = gr.Textbox(label="Enter your first name")
296
+ image_input = gr.Image(type="filepath", label="Upload an Image") # Removed the extra comma
297
+ audio_input = gr.Audio(sources="microphone", type="numpy", label="", render=True)
298
+ # text_input = gr.Textbox(label="Input here...")
299
+ # submit_button = gr.Button("Submit")
300
+
301
+
302
+ with gr.Column():
303
+ # Output fields
304
+ user_input_output = gr.Textbox(label="User Input")
305
+ stud_output = gr.Textbox(label="Studs Terkel")
306
+ audio_output = gr.HTML(label="Audio Player")
307
+
308
+ audio_input.change(pred, inputs=[username, image_input, audio_input], outputs=[ user_input_output, stud_output, audio_output])
309
+ image_input.change(pred, inputs=[username, image_input, audio_input], outputs=[ user_input_output, stud_output, audio_output])
310
+
311
+ # Linking the submit button with the save_audio function
312
+ # submit_button.click(fn=pred, inputs=[username, image_input, audio_input],
313
+ # outputs=[ user_input_output, stud_output, audio_output])
314
+
315
+ # Linking the clear button with the clear_inputs function
316
+ clear_button.click(fn=clear_inputs, inputs=[username, image_input], outputs=[image_input, audio_input, user_input_output, stud_output, audio_output])
317
+
318
+ # Launch the interface
319
+ demo.launch(share=True, debug=True)