前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python实现的食谱生成器

Python实现的食谱生成器

原创
作者头像
mariolu
修改2024-03-18 01:50:18
13100
代码可运行
修改2024-03-18 01:50:18
举报
运行总次数:0
代码可运行

在本文中,使用Python教你如何获取美味食物配方,并讨论其好处和替代实现。

想象一下:你正在超市或者菜市场寻找晚餐灵感,但想到昨天餐馆点的好吃的菜,但并不知道那个配方。

本文让你准备好放弃外卖。通过Python代码得到详细配方,并可以用腾讯云AI的文生图服务生成菜品效果图。

一、拉取食谱

拉取食谱的配方我们使用了edamam网站提供的开发者api,因为免费版本的api提供的免费次数都已经够用了。所以在这里链接

https://developer.edamam.com/edamam-recipe-api获取到application id和key。

通过API拉取的JSON结构如下:

这里我们把food字段提取出来。得到的配方就是:pork belly,wine,ginger,scallions,oil,brown rock sugar,water,light soy sauce,scallion,也就是五花肉、酒、姜、葱、油、红冰糖、水、生抽、葱。

二、生成美味图片

这里我们使用腾讯云的大模型图像创作引擎->文生图模型来生成红烧肉以及配料图片。

大模型文生图的API入口在这里:https://console.cloud.tencent.com/api/explorer?Product=aiart&Version=2022-12-29&Action=TextToImage

这里使用官方提供的Python API指引。然后在这里申请https://console.cloud.tencent.com/cam/capi,得到APP key和密钥。

三、完整的代码

红烧肉菜品图片生成

代码语言:python
代码运行次数:0
复制
import sys
import json
import matplotlib
import matplotlib.pyplot as plt
import base64
import matplotlib.image as mpimg
import io

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.aiart.v20221229 import aiart_client, models


#拉取recipes
import requests
import urllib

#这里需要填充edamam注册的app_id和app_key
app_id=""
app_key=""

cook="红烧肉" #填你想做的菜
url=f'https://api.edamam.com/api/recipes/v2?type=public&q={cook.encode("utf-8")}&app_id={app_id}&app_key={app_key}'
url=urllib.parse.quote(url)


# 这里为了保证在线运行结果,我把我拉取的食谱直接放在这个快照链接里
url = "https://raw.githubusercontent.com/lumanyu/ai_app/main/data/recipe/braised_pork.json"

# A GET request to the API
response = requests.get(url)

# 获取到食谱的组成成份
response_json = response.json()
ingredients = response_json['hits'][0]['recipe']['ingredients']

i_arr=[]
for ingredient in ingredients:
    #print(ingredient['food'])
    i_arr.append(str(ingredient['food']))
print(','.join(i_arr))


matplotlib.use('Agg')

'''
try:
    # 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
    # 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:/document/product/1278/85305
    # 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
    cred = credential.Credential("", "")
    # 实例化一个http选项,可选的,没有特殊需求可以跳过
    httpProfile = HttpProfile()
    httpProfile.endpoint = "aiart.tencentcloudapi.com"

    # 实例化一个client选项,可选的,没有特殊需求可以跳过
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    # 实例化要请求产品的client对象,clientProfile是可选的
    client = aiart_client.AiartClient(cred, "ap-guangzhou", clientProfile)

    # 实例化一个请求对象,每个接口都会对应一个request对象
    req = models.TextToImageRequest()
    params = {
        "Prompt": "红烧肉"
    }
    req.from_json_string(json.dumps(params))

    # 返回的resp是一个TextToImageResponse的实例,与请求对象对应
    resp = client.TextToImage(req)
    # 输出json格式的字符串回包
    image_data = json.loads(resp.to_json_string())
    global img_data
    img_data=image_data['ResultImage']
    fig = plt.figure()

    fp = io.BytesIO(base64.b64decode(str(img_data)))
    with fp:
        img = mpimg.imread(fp, format='jpeg')
    plt.imshow(img)
    fig.savefig('plot.png', dpi=80)

except TencentCloudSDKException as err:
    print(err)    
'''

#因为这里生成红烧肉图片要填上secret id和key,所以需要你自己注册,代码是可用的。这里我直接拉取之前拉取过的图片做展示
url="https://raw.githubusercontent.com/lumanyu/ai_app/main/data/recipe/braised_pork.mini.png"
response = requests.get(url)
fp = io.BytesIO(response.content)
fig = plt.figure()

with fp:
    img = mpimg.imread(fp, format='')
plt.imshow(img)
fig.savefig('plot2.png', dpi=80)

配料生成

代码语言:python
代码运行次数:0
复制
import sys
import json
import matplotlib
import matplotlib.pyplot as plt
import base64
import matplotlib.image as mpimg
import io

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.aiart.v20221229 import aiart_client, models


#拉取recipes
import requests
import urllib

#这里需要填充edamam注册的app_id和app_key
app_id=""
app_key=""

cook="红烧肉" #填你想做的菜
url=f'https://api.edamam.com/api/recipes/v2?type=public&q={cook.encode("utf-8")}&app_id={app_id}&app_key={app_key}'
url=urllib.parse.quote(url)


# 这里为了保证在线运行结果,我把我拉取的食谱直接放在这个快照链接里
url = "https://raw.githubusercontent.com/lumanyu/ai_app/main/data/recipe/braised_pork.json"

# A GET request to the API
response = requests.get(url)

# 获取到食谱的组成成份
response_json = response.json()
ingredients = response_json['hits'][0]['recipe']['ingredients']

i_arr=[]
for ingredient in ingredients:
    #print(ingredient['food'])
    i_arr.append(str(ingredient['food']))
print(','.join(i_arr))


matplotlib.use('Agg')

'''
try:
    # 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
    # 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:/document/product/1278/85305
    # 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
    cred = credential.Credential("", "")
    # 实例化一个http选项,可选的,没有特殊需求可以跳过
    httpProfile = HttpProfile()
    httpProfile.endpoint = "aiart.tencentcloudapi.com"

    # 实例化一个client选项,可选的,没有特殊需求可以跳过
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    # 实例化要请求产品的client对象,clientProfile是可选的
    client = aiart_client.AiartClient(cred, "ap-guangzhou", clientProfile)

    # 实例化一个请求对象,每个接口都会对应一个request对象
    req = models.TextToImageRequest()
    params = {
        "Prompt": ','.join(i_arr)
    }
    req.from_json_string(json.dumps(params))

    # 返回的resp是一个TextToImageResponse的实例,与请求对象对应
    resp = client.TextToImage(req)
    # 输出json格式的字符串回包
    image_data = json.loads(resp.to_json_string())
    global img_data
    img_data=image_data['ResultImage']
    fig = plt.figure()

    fp = io.BytesIO(base64.b64decode(str(img_data)))
    with fp:
        img = mpimg.imread(fp, format='jpeg')
    plt.imshow(img)
    fig.savefig('plot.png', dpi=80)

except TencentCloudSDKException as err:
    print(err)    
'''

#因为这里生成红烧肉图片要填上secret id和key,所以需要你自己注册,代码是可用的。这里我直接拉取之前拉取过的图片做展示
url="https://raw.githubusercontent.com/lumanyu/ai_app/main/data/recipe/braised_pork_recipe.mini.png"
response = requests.get(url)
fp = io.BytesIO(response.content)
fig = plt.figure()

with fp:
    img = mpimg.imread(fp, format='')
plt.imshow(img)
fig.savefig('plot2.png', dpi=80)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、拉取食谱
  • 二、生成美味图片
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com