| import gradio as gr | |
| # 模擬食譜數據庫 | |
| # 這裡的鍵是食譜名稱,值是食材列表 | |
| recipes = { | |
| "番茄炒蛋": ["番茄", "雞蛋"], | |
| "宮保雞丁": ["雞肉", "花生", "辣椒"], | |
| "麻婆豆腐": ["豆腐", "絞肉", "花椒"], | |
| "清蒸魚": ["魚", "蔥", "薑"], | |
| "簡單沙拉": ["生菜", "小黃瓜", "番茄"], | |
| } | |
| def recommend_recipes(ingredients_str): | |
| """ | |
| 根據使用者輸入的食材,推薦相關食譜。 | |
| """ | |
| # 將輸入的字串分割成個別食材列表,並移除空白 | |
| ingredients = [i.strip() for i in ingredients_str.split(',')] | |
| # 儲存找到的食譜 | |
| found_recipes = [] | |
| # 遍歷所有食譜,檢查是否包含至少一個使用者提供的食材 | |
| for recipe_name, recipe_ingredients in recipes.items(): | |
| # 檢查兩個列表是否有交集 | |
| if set(ingredients) & set(recipe_ingredients): | |
| found_recipes.append(recipe_name) | |
| # 格式化輸出 | |
| if found_recipes: | |
| return "根據您的食材,我們推薦以下食譜:\n" + "\n".join(found_recipes) | |
| else: | |
| return "很抱歉,沒有找到符合您食材的食譜。請嘗試輸入不同的食材。" | |
| # 建立 Gradio 介面 | |
| # inputs: 使用者輸入的文字框 | |
| # outputs: 顯示結果的文字框 | |
| # title: 應用程式的標題 | |
| # description: 應用程式的說明 | |
| gr.Interface( | |
| fn=recommend_recipes, | |
| inputs=gr.Textbox(lines=2, placeholder="請輸入您擁有的食材,例如:番茄, 雞蛋, 雞肉"), | |
| outputs="text", | |
| title="🍲 食材食譜推薦", | |
| description="輸入您擁有的食材清單(用逗號分隔),我會為您推薦相關食譜!" | |
| ).launch() |