aldan.creo commited on
Commit
1373604
1 Parent(s): f412709

Working inference

Browse files
Files changed (3) hide show
  1. app.py +109 -16
  2. build_training_ds.py +29 -21
  3. requirements.txt +1 -0
app.py CHANGED
@@ -7,6 +7,46 @@ from functools import partial
7
  import gradio as gr
8
  from datasets import Dataset, load_dataset
9
  from dotenv import load_dotenv
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  logging.basicConfig(level=logging.INFO)
12
  logger = logging.getLogger(__name__)
@@ -14,6 +54,12 @@ logger.setLevel(logging.INFO)
14
 
15
  load_dotenv()
16
 
 
 
 
 
 
 
17
  # dataset = load_dataset("detection-datasets/coco")
18
  it_dataset = (
19
  load_dataset("imagenet-1k", split="train", streaming=True, trust_remote_code=True)
@@ -108,18 +154,24 @@ theme = gr.themes.Default(primary_hue="cyan", secondary_hue="fuchsia")
108
 
109
  translation_table = {
110
  "Maker Faire Bot": "Maker Faire Bot",
111
- "**Think about these objects...**": "**Tænk på disse objekter...**",
112
  "We want to build a Maker Faire Bot that can generate creative ideas. Help us by providing ideas on what you'd build with the following three objects!": "Vi vil bygge en Maker Faire Bot, der kan generere kreative ideer. Hjælp os ved at give ideer til, hvad du ville bygge med de følgende tre objekter!",
113
  "Change": "Skift",
114
  "What would you build with these 3 things?": "Hvad ville du bygge med disse 3 ting?",
115
  "For example, if you have a roll of string, a camera, and a loudspeaker, you could build an electronic guitar. If you can write in Danish, that's great!": "For eksempel, hvis du har en rulle snor, et kamera og en højttaler, kunne du bygge en elektronisk guitar. Hvis du kan skrive på dansk, er det fantastisk!",
116
  "It doesn't need to be a very long explanation, just a few sentences to help the bot understand your idea.": "Det behøver ikke være en meget lang forklaring, bare et par sætninger for at hjælpe robotten med at forstå din idé.",
117
- "Submit": "Indsend",
118
  "New Prompt": "Ny opgave",
119
  "How would you build it?": "Hvordan ville du bygge det?",
120
  "This is an experimental project. Your data is anonymous and will be used to train an AI model. By using this tool, you agree to our policy.": "Dette er et eksperimentelt projekt. Dine data er anonyme og vil blive brugt til at træne en AI-model. Ved at bruge dette værktøj accepterer du vores politik.",
121
  "(example): An digital electronic guitar": "(eksempel): En digital elektronisk guitar",
122
  """I would use the roll of string to create the strings of the guitar, and the camera to analyze the hand movements. Then, I would use an AI model to predict the chords and play the sound through the loudspeaker.""": """Jeg ville bruge snoren til at skabe guitarens strenge, og kameraet til at analysere håndbevægelserne. Derefter ville jeg bruge en AI-model til at forudsige akkorderne og afspille lyden gennem højttaleren.""",
 
 
 
 
 
 
123
  }
124
 
125
 
@@ -144,15 +196,24 @@ with gr.Blocks(theme=theme) as demo:
144
  )
145
 
146
  user_prompt = gr.State(get_user_prompt())
 
147
 
148
- gr.Markdown(get_bilingual_string("**Think about these objects...**"))
149
  gr.Markdown(
150
  get_bilingual_string(
151
  "We want to build a Maker Faire Bot that can generate creative ideas. Help us by providing ideas on what you'd build with the following three objects!"
 
 
 
 
 
 
152
  )
153
  )
 
154
  image_components = []
155
  with gr.Row(variant="panel") as row:
 
156
  def change_image(this_i, user_prompt):
157
  logger.info(
158
  f"Current user prompt: {user_prompt}, current image index: {this_i}"
@@ -161,9 +222,9 @@ with gr.Blocks(theme=theme) as demo:
161
  new_user_prompt = user_prompt.copy()
162
  new_user_prompt["images"][this_i] = data["image"]
163
  new_user_prompt["machine_labels"][this_i] = data["label"]
164
- new_user_prompt["human_labels"][this_i] = dataset.features[
165
- "label"
166
- ].int2str(data["label"])
167
  logger.info(f"New user prompt: {new_user_prompt}")
168
  return (
169
  new_user_prompt,
@@ -182,7 +243,7 @@ with gr.Blocks(theme=theme) as demo:
182
  show_share_button=False,
183
  )
184
  image_components.append(img)
185
- btn = gr.Button(get_bilingual_string("Change"), variant="secondary")
186
 
187
  btn.click(
188
  lambda *args: change_image(0, *args),
@@ -200,7 +261,7 @@ with gr.Blocks(theme=theme) as demo:
200
  show_share_button=False,
201
  )
202
  image_components.append(img)
203
- btn = gr.Button(get_bilingual_string("Change"), variant="secondary")
204
 
205
  btn.click(
206
  lambda *args: change_image(1, *args),
@@ -218,7 +279,7 @@ with gr.Blocks(theme=theme) as demo:
218
  show_share_button=False,
219
  )
220
  image_components.append(img)
221
- btn = gr.Button(get_bilingual_string("Change"), variant="secondary")
222
 
223
  btn.click(
224
  lambda *args: change_image(2, *args),
@@ -228,20 +289,30 @@ with gr.Blocks(theme=theme) as demo:
228
  postprocess=True,
229
  )
230
 
 
 
 
 
 
 
 
 
231
  user_answer_object = gr.Textbox(
232
- autofocus=True,
233
  placeholder=get_bilingual_string("(example): An digital electronic guitar"),
234
- label=get_bilingual_string("What would you build with these 3 things?"),
235
- info=get_bilingual_string("For example, if you have a roll of string, a camera, and a loudspeaker, you could build an electronic guitar. If you can write in Danish, that's great!")
 
 
236
  )
237
  user_answer_explanation = gr.TextArea(
238
- autofocus=True,
239
- label=get_bilingual_string("How would you build it?"),
240
  # The example uses a roll of string, a camera, and a loudspeaker to build an electronic guitar.
241
  placeholder=get_bilingual_string(
242
  """I would use the roll of string to create the strings of the guitar, and the camera to analyze the hand movements. Then, I would use an AI model to predict the chords and play the sound through the loudspeaker."""
243
  ),
244
- info=get_bilingual_string("It doesn't need to be a very long explanation, just a few sentences to help the bot understand your idea.")
 
 
245
  )
246
 
247
  csv_writer.setup(
@@ -253,9 +324,22 @@ with gr.Blocks(theme=theme) as demo:
253
  flagging_dir="user_data_hf",
254
  )
255
 
256
- submit_btn = gr.Button(get_bilingual_string("Submit"), variant="primary")
 
 
257
 
258
  def log_results(prompt, object, explanation):
 
 
 
 
 
 
 
 
 
 
 
259
  logger.info(f"logging - Prompt: {prompt}")
260
  # csv_writer.flag(
261
  # [
@@ -286,6 +370,8 @@ with gr.Blocks(theme=theme) as demo:
286
  preprocess=True,
287
  )
288
 
 
 
289
  # def renew_prompt(image_components):
290
  # new_prompt = get_user_prompt()
291
  # for i in range(len(new_prompt["images"])):
@@ -308,5 +394,12 @@ with gr.Blocks(theme=theme) as demo:
308
  "This is an experimental project. Your data is anonymous and will be used to train an AI model. By using this tool, you agree to our policy."
309
  )
310
  )
 
 
 
 
 
 
 
311
  if __name__ == "__main__":
312
  demo.launch()
 
7
  import gradio as gr
8
  from datasets import Dataset, load_dataset
9
  from dotenv import load_dotenv
10
+ import tempfile
11
+ import base64
12
+ import vertexai
13
+ from vertexai.generative_models import GenerativeModel, Part, GenerationResponse
14
+ import vertexai.preview.generative_models as generative_models
15
+
16
+
17
+ def multiturn_generate_content(things) -> GenerationResponse:
18
+ vertexai.init(project="134994101092", location="europe-west6")
19
+ model = GenerativeModel(
20
+ "projects/134994101092/locations/europe-west6/endpoints/1920706076236316672",
21
+ system_instruction=[textsi_1],
22
+ )
23
+ chat = model.start_chat()
24
+ json_objects = json.dumps({"things": things})
25
+ response = chat.send_message(
26
+ [
27
+ json_objects
28
+ ],
29
+ generation_config=generation_config,
30
+ safety_settings=safety_settings,
31
+ )
32
+ return response
33
+
34
+
35
+ textsi_1 = """You are a creative chatbot called MakerBot, built for Maker Faire Aarhus. You have been built by Aldan Creo, an AI researcher. Your job is to invent new things that can be built using three things. The user will give you a list of three things, in JSON format, and you need to write what you would build, and how you would build it. The names of the things can be multiple words. Commas indicate synonyms or different ways to call that thing. You should try to use the three things. If it is impossible to use the three things to build something, you must explicitly say that you have not been able to think about how to use that thing, and say what it is. You must answer in Danish. Your answer must follow the structure {\"What\": \"Navn på opfindelsen\", \"How\": \"Hvordan man bygger den ting ved hjælp af de tre objekter, som brugeren har givet.\"}."""
36
+
37
+ generation_config = {
38
+ "max_output_tokens": 2048,
39
+ "temperature": 1,
40
+ "top_p": 1,
41
+ }
42
+
43
+ safety_settings = {
44
+ generative_models.HarmCategory.HARM_CATEGORY_HATE_SPEECH: generative_models.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
45
+ generative_models.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: generative_models.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
46
+ generative_models.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: generative_models.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
47
+ generative_models.HarmCategory.HARM_CATEGORY_HARASSMENT: generative_models.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
48
+ }
49
+
50
 
51
  logging.basicConfig(level=logging.INFO)
52
  logger = logging.getLogger(__name__)
 
54
 
55
  load_dotenv()
56
 
57
+ # Get the credentials to use the Google API from the env variable GOOGLE_APP_CREDENTIALS_JSON and save it to a temp file
58
+ with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".json") as f:
59
+ f.write(os.environ["GOOGLE_APP_CREDENTIALS_JSON"])
60
+ f.flush()
61
+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = f.name
62
+
63
  # dataset = load_dataset("detection-datasets/coco")
64
  it_dataset = (
65
  load_dataset("imagenet-1k", split="train", streaming=True, trust_remote_code=True)
 
154
 
155
  translation_table = {
156
  "Maker Faire Bot": "Maker Faire Bot",
157
+ "Think about these objects...": "## Tænk på disse objekter...",
158
  "We want to build a Maker Faire Bot that can generate creative ideas. Help us by providing ideas on what you'd build with the following three objects!": "Vi vil bygge en Maker Faire Bot, der kan generere kreative ideer. Hjælp os ved at give ideer til, hvad du ville bygge med de følgende tre objekter!",
159
  "Change": "Skift",
160
  "What would you build with these 3 things?": "Hvad ville du bygge med disse 3 ting?",
161
  "For example, if you have a roll of string, a camera, and a loudspeaker, you could build an electronic guitar. If you can write in Danish, that's great!": "For eksempel, hvis du har en rulle snor, et kamera og en højttaler, kunne du bygge en elektronisk guitar. Hvis du kan skrive på dansk, er det fantastisk!",
162
  "It doesn't need to be a very long explanation, just a few sentences to help the bot understand your idea.": "Det behøver ikke være en meget lang forklaring, bare et par sætninger for at hjælpe robotten med at forstå din idé.",
163
+ "Submit Your Answer": "Indsend dit svar",
164
  "New Prompt": "Ny opgave",
165
  "How would you build it?": "Hvordan ville du bygge det?",
166
  "This is an experimental project. Your data is anonymous and will be used to train an AI model. By using this tool, you agree to our policy.": "Dette er et eksperimentelt projekt. Dine data er anonyme og vil blive brugt til at træne en AI-model. Ved at bruge dette værktøj accepterer du vores politik.",
167
  "(example): An digital electronic guitar": "(eksempel): En digital elektronisk guitar",
168
  """I would use the roll of string to create the strings of the guitar, and the camera to analyze the hand movements. Then, I would use an AI model to predict the chords and play the sound through the loudspeaker.""": """Jeg ville bruge snoren til at skabe guitarens strenge, og kameraet til at analysere håndbevægelserne. Derefter ville jeg bruge en AI-model til at forudsige akkorderne og afspille lyden gennem højttaleren.""",
169
+ "Ask the Bot": "Spørg robotten",
170
+ "The bot needs human ideas to learn - can you provide a new one?": "Robotten har brug for menneskelige ideer for at lære - kan du give en ny?",
171
+ "This demo has been built by [Aldan Creo](https://acmc-website.web.app/) for [Maker Faire Aarhus](https://aarhus.makerfaire.com/). The images are from the [ImageNet](https://www.image-net.org/) dataset.": "Denne demo er lavet af [Aldan Creo](https://acmc-website.web.app/) til [Maker Faire Aarhus](https://aarhus.makerfaire.com/). Billederne er fra [ImageNet](https://www.image-net.org/)-datasættet.",
172
+ "The explanation should have at least 20 characters.": "Forklaringen skal have mindst 20 tegn.",
173
+ "Can you think of something better? **Teach the bot** by writing your own idea above!": "Kan du tænke på noget bedre? **Lær robotten** ved at skrive din egen idé ovenfor!",
174
+ "This is an experimental project where we teach a bot to think like a Maker. You can choose three objects by clicking the 'Change' button under the images below. Then, you can **ask the bot what it would build with those objects** by clicking on the 'Ask the Bot' button. What will it come up with?": "Dette er et eksperimentelt projekt, hvor vi lærer en robot at tænke som en Maker. Du kan vælge tre objekter ved at klikke på 'Skift'-knappen under billederne nedenfor. Derefter kan du **spørge robotten, hvad den ville bygge med de objekter** ved at klikke på 'Spørg robotten'-knappen. Hvad vil den finde på?",
175
  }
176
 
177
 
 
196
  )
197
 
198
  user_prompt = gr.State(get_user_prompt())
199
+ last_bot_response = gr.State({"What": "", "How": ""})
200
 
201
+ gr.Markdown(get_bilingual_string("Think about these objects...") + " 🤔")
202
  gr.Markdown(
203
  get_bilingual_string(
204
  "We want to build a Maker Faire Bot that can generate creative ideas. Help us by providing ideas on what you'd build with the following three objects!"
205
+ ) + " 🙌",
206
+ visible=False,
207
+ )
208
+ gr.Markdown(
209
+ get_bilingual_string(
210
+ "This is an experimental project where we teach a bot to think like a Maker. You can choose three objects by clicking the 'Change' button under the images below. Then, you can **ask the bot what it would build with those objects** by clicking on the 'Ask the Bot' button. What will it come up with?"
211
  )
212
  )
213
+
214
  image_components = []
215
  with gr.Row(variant="panel") as row:
216
+
217
  def change_image(this_i, user_prompt):
218
  logger.info(
219
  f"Current user prompt: {user_prompt}, current image index: {this_i}"
 
222
  new_user_prompt = user_prompt.copy()
223
  new_user_prompt["images"][this_i] = data["image"]
224
  new_user_prompt["machine_labels"][this_i] = data["label"]
225
+ new_user_prompt["human_labels"][this_i] = dataset.features["label"].int2str(
226
+ data["label"]
227
+ )
228
  logger.info(f"New user prompt: {new_user_prompt}")
229
  return (
230
  new_user_prompt,
 
243
  show_share_button=False,
244
  )
245
  image_components.append(img)
246
+ btn = gr.Button(get_bilingual_string("Change") + " 🔁", variant="secondary")
247
 
248
  btn.click(
249
  lambda *args: change_image(0, *args),
 
261
  show_share_button=False,
262
  )
263
  image_components.append(img)
264
+ btn = gr.Button(get_bilingual_string("Change") + " 🔁", variant="secondary")
265
 
266
  btn.click(
267
  lambda *args: change_image(1, *args),
 
279
  show_share_button=False,
280
  )
281
  image_components.append(img)
282
+ btn = gr.Button(get_bilingual_string("Change") + " 🔁", variant="secondary")
283
 
284
  btn.click(
285
  lambda *args: change_image(2, *args),
 
289
  postprocess=True,
290
  )
291
 
292
+ def ask_the_bot(user_prompt):
293
+ response = multiturn_generate_content(things=user_prompt["human_labels"])
294
+ json_bot_response = json.loads(response.candidates[0].text)
295
+ logger.info(f"Bot response: {json_bot_response}")
296
+ return json_bot_response, json_bot_response["What"], json_bot_response["How"]
297
+
298
+ ask_the_bot_btn = gr.Button(get_bilingual_string("Ask the Bot") + " 🤖", variant="primary")
299
+
300
  user_answer_object = gr.Textbox(
 
301
  placeholder=get_bilingual_string("(example): An digital electronic guitar"),
302
+ label=get_bilingual_string("What would you build with these 3 things?") + " 🤔",
303
+ info=get_bilingual_string(
304
+ "For example, if you have a roll of string, a camera, and a loudspeaker, you could build an electronic guitar. If you can write in Danish, that's great!"
305
+ ),
306
  )
307
  user_answer_explanation = gr.TextArea(
308
+ label=get_bilingual_string("How would you build it?") + " 🛠️",
 
309
  # The example uses a roll of string, a camera, and a loudspeaker to build an electronic guitar.
310
  placeholder=get_bilingual_string(
311
  """I would use the roll of string to create the strings of the guitar, and the camera to analyze the hand movements. Then, I would use an AI model to predict the chords and play the sound through the loudspeaker."""
312
  ),
313
+ info=get_bilingual_string(
314
+ "It doesn't need to be a very long explanation, just a few sentences to help the bot understand your idea."
315
+ ),
316
  )
317
 
318
  csv_writer.setup(
 
324
  flagging_dir="user_data_hf",
325
  )
326
 
327
+ gr.Markdown(get_bilingual_string("Can you think of something better? **Teach the bot** by writing your own idea above!") + " 🧠")
328
+
329
+ submit_btn = gr.Button(get_bilingual_string("Submit Your Answer") + " 📩", variant="primary")
330
 
331
  def log_results(prompt, object, explanation):
332
+ # Is the last bot response the same as the object or explanation?
333
+ # If so, we don't want to log it
334
+ if (
335
+ last_bot_response.value["What"] == object
336
+ or last_bot_response.value["How"] == explanation
337
+ ):
338
+ raise gr.Error(get_bilingual_string("The bot needs human ideas to learn - can you provide a new one?"))
339
+
340
+ # The description should have at least 20 characters
341
+ if len(explanation) < 20:
342
+ raise gr.Error(get_bilingual_string("The explanation should have at least 20 characters."))
343
  logger.info(f"logging - Prompt: {prompt}")
344
  # csv_writer.flag(
345
  # [
 
370
  preprocess=True,
371
  )
372
 
373
+ ask_the_bot_btn.click(ask_the_bot, inputs=[user_prompt], outputs=[last_bot_response, user_answer_object, user_answer_explanation], preprocess=True)
374
+
375
  # def renew_prompt(image_components):
376
  # new_prompt = get_user_prompt()
377
  # for i in range(len(new_prompt["images"])):
 
394
  "This is an experimental project. Your data is anonymous and will be used to train an AI model. By using this tool, you agree to our policy."
395
  )
396
  )
397
+
398
+ # Attribution information
399
+ gr.Markdown(
400
+ get_bilingual_string(
401
+ "This demo has been built by [Aldan Creo](https://acmc-website.web.app/) for [Maker Faire Aarhus](https://aarhus.makerfaire.com/). The images are from the [ImageNet](https://www.image-net.org/) dataset."
402
+ )
403
+ )
404
  if __name__ == "__main__":
405
  demo.launch()
build_training_ds.py CHANGED
@@ -1,30 +1,38 @@
1
  from datasets import load_dataset
2
  import json
 
 
3
 
4
- # Load the dataset
5
- dataset = load_dataset("acmc/maker-faire-bot")
6
-
7
- print(dataset["train"][0])
8
 
 
 
9
 
10
  def turn_into_ai_train_example(example):
11
- user_prompt = json.loads(example['Unnamed: 0'])
12
- return [
13
- {
14
- "role": "system",
15
- "content": 'You are a creative chatbot called MakerBot, built for Maker Faire Aarhus. You have been built by Aldan Creo, an AI researcher. Your job is to invent new things that can be built using three things. The user will give you a list of three things, in JSON format, and you need to write what you would build, and how you would build it. The names of the things can be multiple words. Commas indicate synonyms or different ways to call that thing. You should try to use the three things. If it is impossible to use the three things to build something, you must explicitly say that you have not been able to think about how to use that thing, and say what it is. You must answer in Danish. Your answer must follow the structure {"What": "Navn på opfindelsen", "How": "Hvordan man bygger den ting ved hjælp af de tre objekter, som brugeren har givet."}.',
16
- },
17
- {
18
- "role": "user",
19
- "content": f'{{"things": ["{user_prompt["human_labels"][0]}", "{user_prompt["human_labels"][1]}", "{user_prompt["human_labels"][2]}"]}}',
20
- },
21
- {
22
- "role": "model",
23
- "content": f'{{"What": "{json.dumps(example["Hvad ville du bygge? // What would you build?"])}", "How": "{json.dumps(example["Hvordan ville du bygge det? // How would you build it?"])}"}}',
24
- },
25
- ]
 
 
 
 
 
 
 
26
 
27
- processed_dataset = dataset.map(turn_into_ai_train_example)
28
 
29
  # Save as a JSONl file
30
- processed_dataset.to_json("maker_faire_bot.jsonl")
 
1
  from datasets import load_dataset
2
  import json
3
+ import logging
4
+ import ast
5
 
6
+ logging.basicConfig(level=logging.INFO)
 
 
 
7
 
8
+ # Load the dataset
9
+ dataset = load_dataset("acmc/maker-faire-bot")['train']
10
 
11
  def turn_into_ai_train_example(example):
12
+ try:
13
+ user_prompt = ast.literal_eval(example["Unnamed: 0"])
14
+ except Exception as e:
15
+ logging.exception(f"Could not parse from {example['Unnamed: 0']}")
16
+ raise e
17
+ return {
18
+ "messages": [
19
+ {
20
+ "role": "system",
21
+ "content": 'You are a creative chatbot called MakerBot, built for Maker Faire Aarhus. You have been built by Aldan Creo, an AI researcher. Your job is to invent new things that can be built using three things. The user will give you a list of three things, in JSON format, and you need to write what you would build, and how you would build it. The names of the things can be multiple words. Commas indicate synonyms or different ways to call that thing. You should try to use the three things. If it is impossible to use the three things to build something, you must explicitly say that you have not been able to think about how to use that thing, and say what it is. You must answer in Danish. Your answer must follow the structure {"What": "Navn på opfindelsen", "How": "Hvordan man bygger den ting ved hjælp af de tre objekter, som brugeren har givet."}.',
22
+ },
23
+ {
24
+ "role": "user",
25
+ "content": f'{{"things": ["{user_prompt["human_labels"][0]}", "{user_prompt["human_labels"][1]}", "{user_prompt["human_labels"][2]}"]}}',
26
+ },
27
+ {
28
+ "role": "model",
29
+ "content": f'{{"What": "{json.dumps(example["Hvad ville du bygge? // What would you build?"], ensure_ascii=False)}", "How": "{json.dumps(example["Hvordan ville du bygge det? // How would you build it?"], ensure_ascii=False)}"}}',
30
+ },
31
+ ]
32
+ }
33
+
34
 
35
+ processed_dataset = dataset.map(turn_into_ai_train_example, remove_columns=dataset.column_names)
36
 
37
  # Save as a JSONl file
38
+ processed_dataset.to_json("maker_faire_bot.jsonl", force_ascii=False)
requirements.txt CHANGED
@@ -1,3 +1,4 @@
1
  datasets==2.19.0
2
  python-dotenv==1.0.1
3
  gradio==4.28.0
 
 
1
  datasets==2.19.0
2
  python-dotenv==1.0.1
3
  gradio==4.28.0
4
+ google-cloud-aiplatform==1.48.0