recipe-cleaner / app.py
mandyvarel's picture
Upload 3 files
ba4f191
raw
history blame
No virus
2.57 kB
import os
import openai
import gradio
import json
from pathlib import Path
from bs4 import BeautifulSoup
openai.api_key = os.getenv("OPENAI_API_KEY")
content_input = "Format the recipe, given the format provided. You must return an HTML:"
html_template = '''
<div itemscope itemtype="https://schema.org/Recipe">
<span itemprop="name">Mom's World Famous Banana Bread</span>
<img itemprop="image" src="https://encrypted-tbn0.gstatic.com/banana.jpg" />
<span itemprop="description">This classic banana bread recipe comes
from my mom.</span>
<span itemprop="recipeIngredient">3 or 4 ripe bananas, smashed</span>
<span itemprop="recipeIngredient">3/4 cup of sugar</span>
<span itemprop="recipeInstructions">
1 - Preheat the oven to 350 degrees.
</span>
<span itemprop="recipeInstructions">
2 - Mix in the ingredients in a bowl.
</span>
</div>
'''
content_input+=html_template
messages = [{"role": "system", "content": content_input}]
# create a static directory to store the static files
static_dir = Path('./static')
static_dir.mkdir(parents=True, exist_ok=True)
def CustomChatGPT(recipe):
messages.append({"role": "user", "content": recipe})
response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages)
ChatGPT_reply = response["choices"][0]["message"]["content"]
file_name = "output.html"
file_path = static_dir / file_name
soup = BeautifulSoup(ChatGPT_reply, 'html.parser')
recipe_name = soup.find(attrs={"itemprop": "name"})
recipe_name_str = recipe_name.text
ingredients_html = soup.find_all(attrs={"itemprop": "recipeIngredient"})
ingredients = [item.text.strip() for item in ingredients_html]
ingredients_str = "\n".join(ingredients)
steps_html = soup.find_all(attrs={"itemprop": "recipeInstructions"})
steps = [item.text.strip() for item in steps_html]
steps_str = "\n".join(steps)
with open(file_path, "w") as file:
file.write(ChatGPT_reply)
return recipe_name_str, ingredients_str, steps_str, "<a href='file=static/output.html'>Import</a>"
demo = gradio.Interface(
fn=CustomChatGPT,
inputs=gradio.Textbox(label="Recipe", lines=2, placeholder="Recipe here..."),
outputs=[gradio.Textbox(label="Recipe Name", lines=1, placeholder="Recipe Name..."), gradio.Textbox(label="Ingredients", lines=2, placeholder="Ingredients..."),gradio.Textbox(label="Preparation Steps", lines=2, placeholder="Steps..."),gradio.HTML()],
title="Recipe Cleaner"
)
# demo.launch()
demo.launch(share=True)