CoolFace
Apppublic

Gracoy/Recipe_Generator

sourceHugging Faceotherupdated 3y agoView on Hugging Face
0likes
app.py199 linesDownload Raw Back to root
1import os2import openai3import gradio as gr4 5openai.api_key = os.environ["OpenAI_Key"]6HUGGINGFACE_TOKEN = os.environ["HF_Key"]7 8# huggingface-cli login --token $HUGGINGFACE_TOKEN9 10from transformers import TFGPT2LMHeadModel, AutoTokenizer11 12tokenizer = AutoTokenizer.from_pretrained('Gracoy/ingredients_compatibility_GPT2_S')13model = TFGPT2LMHeadModel.from_pretrained('Gracoy/ingredients_compatibility_GPT2_S')14 15def assistant(assist_prompt):16  response = openai.ChatCompletion.create(17  model='gpt-3.5-turbo',18  messages=assist_prompt,19  temperature=0.7)20  return response["choices"][0]["message"]["content"].strip()21 22def proper_ingredient(ingredients, meal):23 24  if not ingredients:25    return26 27  assist_prompt1 = [{"role": "user",    "content": f"列出三道使用{ingredients}裡食材適合當{meal}的料理,列舉即可不須詳細說明"}]28 29  prompt = [30        {"role": "system",   "content": "你是一個烹飪經驗豐富的廚師,知道哪些食材適合拿來搭配來製作平易近人且美味的料理"},31        {"role": "assistant",  "content": assistant(assist_prompt1)},32        {"role": "user",    "content": f"請給我三組在{ingredients}中適合一起烹飪的食材組合,不需要料理名稱只要寫出食材和為何他們適合搭配在一起就好,\33                                          列出的食材組合需至少包含一樣原本提供的食材,###輸出格式:至少一樣原本食材+新增食材:為何適合搭配在一起###"}34        ]35 36  response = openai.ChatCompletion.create(37      model='gpt-3.5-turbo',38      messages=prompt,39      temperature=0.7)40 41  return response["choices"][0]["message"]["content"].strip()42 43def get_ingre(ingredients):44  final_ingre = ingredients45  return final_ingre46 47def gen_recipe(final_ingredients, flavor, meal):48  global step49  global round50  global history51 52  step = 953  round = 054  history = []55 56  if not final_ingredients:57    return58 59  assist_prompt1 = [{"role": "user",    "content": f"請用三句話說明料理中的{flavor}風味,列出{flavor}風味常使用的香料及調味料,列舉即可不須詳細說明"}]60  assist_prompt2 = [{"role": "user",    "content": f"列出三樣以{final_ingredients}裡的食材烹調出適合當{meal}的{flavor}風味料理,列舉即可不須詳細說明"}]61 62  prompt = [63        {"role": "system",   "content": "你是一個烹飪經驗豐富的廚師,擅長使用手邊的食材和簡潔的烹飪步驟來製作平易近人的家庭料理"},64        {"role": "assistant",  "content": assistant(assist_prompt1)},65        {"role": "assistant",  "content": assistant(assist_prompt2)},66        {"role": "user",    "content": f"請在上述料理中選擇一個,並針對此料理給我一份步驟數在{step}步以內的食譜,烹飪方式不要用炒的,食材用量要詳細,\67                                        食譜要包含用到的調味料,烹飪步驟要簡潔;###使用食材:{final_ingredients},料理風味:{flavor},餐點:{meal}\68                                        ###;###輸出格式:料理名稱,使用食材,使用調味料,烹飪步驟,分成三個區塊顯示###"}69        ]70 71  response = openai.ChatCompletion.create(72      model='gpt-3.5-turbo',73      messages=prompt,74      temperature=0.7)75 76  round += 177  history.append(response["choices"][0]["message"]["content"].strip())78  return response["choices"][0]["message"]["content"].strip()79 80def another_recipe(final_ingredients, flavor, meal):81  global step82  global round83  global history84 85  if round == 0 or (not final_ingredients):86    return87 88  step = 989 90  assist_prompt1 = [{"role": "user",    "content": f"請用三句話說明料理中的{flavor}風味,列出{flavor}風味常使用的香料及調味料,列舉即可不須詳細說明"}]91  assist_prompt2 = [{"role": "user",    "content": f"你給我的{history[round-1]}料理名稱與食譜我都不喜歡,\92                                                    請列出其他三樣以{final_ingredients}裡的食材烹調出適合當{meal}的{flavor}風味料理,列舉即可不須詳細說明"}]93 94  prompt = [95        {"role": "system",   "content": "你是一個烹飪經驗豐富的家庭主婦,擅長使用簡潔的烹飪步驟來製作平易近人的料理"},96        {"role": "assistant",  "content": assistant(assist_prompt1)},97        {"role": "assistant",  "content": assistant(assist_prompt2)},98        {"role": "user",    "content": f"請在上述料理中給我一份料理名稱不在{history}裡且步驟數在{step}步以內的食譜,烹飪方式不要用炒的, \99                                        食材用量要詳細,食譜要包含用到的調味料,烹飪步驟的描述要簡潔;###使用食材:{final_ingredients},料理風味:{flavor},餐點:{meal}\100                                        ###;###輸出格式:料理名稱,使用食材,使用調味料,烹飪步驟,分成三個區塊顯示###"}101        ]102 103  response = openai.ChatCompletion.create(104      model='gpt-3.5-turbo',105      messages=prompt,106      temperature=0.5)107 108  round += 1109  history.append(response["choices"][0]["message"]["content"].strip())110  return response["choices"][0]["message"]["content"].strip()111 112def simpler_recipe(final_ingredients, flavor, meal):113  global step114  global round115  global history116 117  if round == 0 or (not final_ingredients):118    return119 120  step = step - 2 if step > 5 else step121 122  assist_prompt1 = [{"role": "user",    "content": f"請用三句話說明料理中的{flavor}風味,列出{flavor}風味常使用的香料及調味料,列舉即可不須詳細說明"}]123  assist_prompt2 = [{"role": "user",    "content": f"你給我的{history[round-1]}食譜做法太難了,請列出其他三樣以{final_ingredients}裡的食材,\124                                                      烹調出適合當{meal}的{flavor}風味料理,列舉即可不須詳細說明"}]125 126  prompt = [127        {"role": "system",   "content": "你是一個烹飪技巧不熟練的新手廚師,只能製作出簡單常見的料理"},128        {"role": "assistant",  "content": assistant(assist_prompt1)},129        {"role": "assistant",  "content": assistant(assist_prompt2)},130        {"role": "user",    "content": f"請給我一份料理名稱不在{history}裡且烹飪步驟在{step}步以內的食譜,先用一句話說明你對{history[round-1]}食譜做了哪些調整,烹飪方式不要用炒的,\131                                        食材用量要詳細,最多只能使用三種調味料,烹飪步驟要簡潔;###使用食材:{final_ingredients},料理風味:{flavor},餐點:{meal}\132                                        ###;###輸出格式:料理名稱,使用食材,使用調味料,烹飪步驟,分成三個區塊顯示###"}133        ]134 135  response = openai.ChatCompletion.create(136  model='gpt-3.5-turbo',137  messages=prompt,138  temperature=0.7)139 140  round += 1141  history.append(response["choices"][0]["message"]["content"].strip())142  return response["choices"][0]["message"]["content"].strip()143 144def compatibility_predict(ingredients):145  response = openai.ChatCompletion.create(146      model='gpt-3.5-turbo',147      messages=[{"role": "user", "content": f"請把以下輸入翻譯成英文:{ingredients}"}]148      )149  translated = response['choices'][0]['message']['content'].strip().lower().replace('.', "")150 151  prefix = 'I want to cook, please select the suitable ingredients from the following list: '152  prompt = prefix + translated+ '.'153  input = tokenizer('<BOS>' + prompt, return_tensors='tf')154  encoded_outputs = model.generate(input['input_ids'], max_length=128, num_beams=3, num_return_sequences=1, early_stopping=True)155 156  mid = 'The best combinations are: '157  suffix = '. Enjoy your dish!'158  res = []159  for output in encoded_outputs:160    ans = tokenizer.decode(output, skip_special_tokens=True)161    ans = ans.replace(prompt, "").strip()162    ans = ans.replace(mid, "").strip()163    ans = ans.replace(suffix, "").strip()164    ans = set(ans.split(', '))165    res.append(list(ans))166 167  response = openai.ChatCompletion.create(168    model='gpt-3.5-turbo',169    messages=[{"role": "user", "content": f"請把以下輸入翻譯成繁體中文,翻譯時請以台灣(Taiwan)的習慣用詞為準:{', '.join(ans)}"}]170    )171  return response["choices"][0]["message"]["content"].strip()172 173with gr.Blocks(css="footer{display: none !important;}", theme=gr.themes.Soft(primary_hue="zinc", neutral_hue="sky")) as demo1:174  gr.Markdown(""" # 今晚我想來點 """)175  with gr.Row():176    with gr.Column():177      ingredients = gr.Textbox(label='手邊有哪些其他食材呢?')178      #meal = gr.Textbox(label='現在要吃的是早餐,午餐,點心,晚餐,還是宵夜?')179      meal = gr.Radio(["早餐", "午餐", "晚餐", "點心", "宵夜"], label="你現在要烹煮的是哪一餐?")180      submit_bnt = gr.Button('請推薦食材組合給我')181      proper_set = gr.Textbox(label='推薦的食材組合')182 183    with gr.Column():184      final_ingredients = gr.Textbox(label="最後想使用的食材有哪些?", info="預設帶入原本輸入的食材,可再自行增減")185      flavor = gr.Dropdown(['中式','日式','美式','韓式','義式','泰式','都可以'],label='你希望成品帶有哪些風味?', info="請從選單中任選一個")186      submit_bnt1 = gr.Button('產生食譜吧!')187      recipe = gr.Textbox(label='食譜')188      with gr.Row():189        simpler_btn = gr.Button('太難了')190        another_btn = gr.Button('不喜歡')191 192    submit_bnt.click(fn=compatibility_predict, inputs=[ingredients], outputs=[proper_set])  # 這邊把原本的proper_ingredient換成我們model的API, 其他按鈕都沒改193    submit_bnt.click(fn=get_ingre, inputs=[ingredients], outputs=[final_ingredients])194    submit_bnt1.click(fn=gen_recipe, inputs=[final_ingredients, flavor, meal], outputs=[recipe])195    simpler_btn.click(fn=simpler_recipe, inputs=[final_ingredients, flavor, meal], outputs=[recipe])196    another_btn.click(fn=another_recipe, inputs=[final_ingredients, flavor, meal], outputs=[recipe])197 198demo1.launch()199