65
2

AIとPythonで毎週新しいレシピのアイデアをもらえます

Last updated at Posted at 2023-11-22

ケビンの開発冒険:自動的に新しいおすすめレシピをもらえる

注意:日本語は私の母語ではありません、またAIは私の専門ではありません。

最近、毎週新しいレシピのアイデアを探すことが大変です。。。
私はパートナーに怒られます。。このままでは怒られ続けてしまうので新しいアイデアが必要です!
もし毎週プログラムが新しい料理をおすすめしてくれたらいいのではないでしょうか。
ChatGPTはとてもいいと思いますが、毎週ChatGPTに質問をしたくはないので、自分のプログラムを作ろうと思います。
また、私はAIの経験が無いのでいい冒険です!
AIとPythonでやってみましょう!

コンテンツ

AIの使い方を学びながら、プログラムを作りましょう!

章:

  • 色々な方法
  • AIのモデルとは
  • Pythonのインストール
  • gpt4free
  • lm-studio
  • llama-cpp
  • API
  • まとめ

色々な方法

ちょっと調べてみると、私の理解できた中にも色々なやり方があります:

  • gpt4free
  • lm-studio
  • llama-cpp-python
  • など。。(早くやってみたいでしょう、奥さんは待っていますよ)

それぞれ違うやり方をテストしてみながらAIの使い方を学んでみましょう。

gpt4freeを使うことは一番簡単です。
LLM studio は難しくないがProviderよりもっとセットアップが必要です。
llama-cpp-pythonは簡単ですがモデルを探すことや最適化はちょっと難しくなります。

ノート:今回はOpenAIを使いませんでした。OpenAIは初めは無料ですが後でお金が必要です。

AIとモデルは何だって

「人工知能とは何か』という問いに対する答えは,単純ではない.人工知能の専門家の間でも,大きな議論があり,それだけで1 冊の本となってしまうほど,見解の異なるものである.
そのような中で,共通する部分を引き出して,一言でまとめると,『人間と同じ知的作業をする機械を工学的に実現する技術』といえるだろう」-
Wikipedia

他人はAIとMachine Learningは違うことです。Machine Learningは本当にAIではありませんです。
Machine Learningはプログラムが練習をよくして、後でその特別な練習したものをよく分かりますが他のものだったら何もができませんです。

Machine Learningの中にモデルは
「人間の介入なしに特定のパターンを認識したり、特定の決定を下したりするために、一連のデータに基づいてトレーニングされたプログラム。」 - IBM

Pythonのインストール

Pythonのホームページ

もしマックを使うのであれば「Homebrew」でインストールすることが私のおすすめです。

Homebrewのインストール:

 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Homebrewでpythonのインストール:

brew install python3

Gpt4free

Gpt4freeは一番目の方法です。
Gpt4freeはprovidersを使います。
Providersは何か?AIは違うサーバにあるそうです。そのサーバに質問をすることで、答えをもらえます。
ChatGPTのようにプログラムの中にあります。

pip install -U g4f
import g4f

g4f.debug.logging = True  # Enable logging
g4f.check_version = False  # Disable automatic version checking
print(g4f.version)  # Check version
print(g4f.Provider.Ails.params)  # Supported args

from g4f.Provider import (
    ChatBase
)


# Automatic selection of provider

# Streamed completion
response = g4f.ChatCompletion.create(
    model="gpt-3.5-turbo",
    provider=g4f.Provider.ChatBase,
    messages=[{"role": "user", "content": "Give me in japanese an easy recipe for tonight"}],
    stream=True,
)

for message in response:
    print(message, flush=True, end='')

レシピはできました!

python proto_jarvis.py
0.1.8.2
g4f.provider.Ails supports: (model: str, messages: list[dict[str, str]], stream: bool, temperature: float)
Using ChatBase provider
Sure, here's a simple recipe in Japanese for tonight:

料理名: 卵焼き

材料:
- 卵 2個
- 醤油 小さじ1
- 砂糖 小さじ1/2
- 塩 ひとつまみ
- サラダ油 適量

手順:
1. ボウルに卵を割り入れ、醤油、砂糖、塩を加えてよく混ぜます。
2. フライパンにサラダ油を熱し、卵液を流し入れます。
3. 中火で卵を焼きながら、箸やフライ返しでかき混ぜます。
4. 卵が固まってきたら、巻き寿司のように丸めながら焼きます。
5. 全体的にしっかりと焼き色がついたら完成です。

お楽しみください!(Please note that I am an AI language model and cannot guarantee the accuracy or taste of the recipe. Enjoy!)

面白い!もう一回やりましょう!また同じレシピです:「料理名: 卵焼き」。。。
メッセージを変化させましょう。
「"Give me in japanese an easy recipe for tonight"」→ 「"Give me randomely in japanese an easy recipe for tonight"」. 
私は次の結果が出ました:
「Hmm, I am not sure. Email support@chatbase.co for more info.」。

皆さんはどんなメッセージが出ましたか?
その結果は便利ではありませんね。多分、もっとパラメーターが必要かな。。。違う方法をテストしましょう。

Lm-studio

lm-studioのホームページ
LLM studioはAI発見ためにのソフトです。 AI(モデル)のリストがあるし、ダウンロードはできるし使い方のおすすめがあるし、サーバもあります、など。。。
いちばんはlm-studioのホームページをインストール。
それで、Lm-studioの中に「Mistral-7B-Instruct-v0.1-GGUF」を探して、ダウンロードしてください。
Screenshot 2023-11-15 at 17.59.58.png

ダウンロードが終わったらモデルのセットアップをしてください。それからサーバを実行してください。
Screenshot 2023-11-15 at 18.05.59.png

コードは:

# Example: reuse your existing OpenAI setup
import os
import openai

openai.api_base = "http://localhost:1234/v1" # point to the local server
openai.api_key = "" # no need for an API key

completion = openai.ChatCompletion.create(
  model="local-model", # this field is currently unused
  messages=[
    {"role": "user", "content": "Give me in japanese a recipe for this week."}
  ]
)

print(completion.choices[0].message)

終わりました!
結果は

{
  "role": "assistant",
  "content": " I apologize, but I'm not able to provide recipes in Japanese at the moment. However, you can find many delicious Japanese recipes on websites such as JustOneBite and Japanese Cooking 101. These websites offer step-by-step instructions with photos and videos for easy preparation."
}

もしAIに英語で答えを聞いてみたら

{
  "role": "assistant",
  "content": " Here's a simple and delicious recipe for Chicken Parmesan that serves 4 people:\nIngredients:\n- 4 boneless, skinless chicken breasts\n- 2 cups all-purpose flour\n- 2 eggs\n- 2 teaspoons garlic powder\n- 1/2 teaspoon salt\n- 1/4 teaspoon pepper\n- 1 cup panko bread crumbs\n- 1/2 cup grated Parmesan cheese\n- 2 cups marinara sauce\n- 2 cups shredded mozzarella cheese\n- Fresh basil leaves, for garnish\nInstructions:\n1. Preheat oven to 400\u00b0F (200\u00b0C). Grease a baking dish with cooking spray.\n2. In a shallow dish, whisk together flour and garlic powder.\n3. In another shallow dish, whisk together eggs, salt, and pepper.\n4. In a third shallow dish, mix together panko bread crumbs and grated Parmesan cheese.\n5. Dip each chicken breast in the flour mixture, shaking off any excess.\n6. Dip each chicken breast in the egg mixture, then dredge in the panko mixture, pressing the breadcrumbs onto the chicken to coat well.\n7. Place the chicken breasts in the prepared baking dish and bake for 25-30 minutes or until the chicken is cooked through and golden brown.\n8. Pour the marinara sauce over the chicken, then sprinkle with shredded mozzarella cheese.\n9. Return the chicken to the oven and bake for an additional 10-15 minutes or until the cheese is melted and bubbly.\n10. Garnish with fresh basil leaves before serving. Enjoy!"
}

もしランダムに結果を聞いたら次の答えをもらえます:
メッセージ:「Give me a random recipe for this week.」→
答え:

  • 「How about trying out this recipe for Lemon and Garlic Roasted Chicken...」
  • 「Here's a simple and delicious recipe for Lemon Garlic Butter Baked Chicken Breast...」
  • 「Sure, how about this recipe for Lemon Garlic Roasted Chicken...」

私たちのモデルは鶏肉が好きですね。。
だが、LM studio のおかげで色々なモデルの検索ができます。色々なテストができます:grin: !!
もし気になったらそのホームページは色々なモデルがあります。
AIのことを知るためにはいいと思いませんか?

ここで問題は多分パラメーターとかモデルが良くないことです。
もしもっと強いモデルを使いたかったらもっとRAMが必要です。。。

一般的に:
強いモデルは大きいです。大きいモデルがよくRAMを使います。
実はもっとモデルが練習をしたらもっと大きくなります。

Llama-cpp-python

Llama-cpp-pythonはllama-cppを使います。

llama-cpp-pythonのインスタル:

pip install llama-cpp-python

(もしマックを使ったら次のコマンドが必要です)

wget https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh
bash Miniforge3-MacOSX-arm64.sh

モデルをダウンロード
スクリプトと同じフォルダにモデルをおいてください。

# load the large language model file
from llama_cpp import Llama
#LLM = Llama(model_path="./llama.gguf")
LLM = Llama(model_path="./mistral-7b-instruct-v0.1.Q2_K.gguf")

# create a text prompt
prompt = "Q: Gave me a an easy recipe its list of ingredients and  make it. A:"

# generate a response (takes several seconds)
output = LLM(prompt)

# display the response
print(output["choices"][0]["text"])

結果は

llama_print_timings:        load time =  1650.34 ms
llama_print_timings:      sample time =    86.02 ms /   128 runs   (    0.67 ms per token,  1488.06 tokens per second)
llama_print_timings: prompt eval time =  1650.29 ms /    21 tokens (   78.59 ms per token,    12.73 tokens per second)
llama_print_timings:        eval time =  9073.72 ms /   127 runs   (   71.45 ms per token,    14.00 tokens per second)
llama_print_timings:       total time = 10954.56 ms
 I'd love to help you with that! Here is a simple recipe for a Chicken Parmesan that serves four people:
Ingredients:
- 4 boneless skinless chicken breasts
- Salt and pepper, to taste
- 1 cup Italian breadcrumbs
- 1 cup grated Parmesan cheese
- 2 large eggs, beaten
- 2 tablespoons olive oil
- 2 cups marinara sauce
- 2 cups shredded mozzarella cheese

Instructions:

1. Preheat the oven to 

ここは多分トークンの問題です。トークンはモデルの言葉みたいです。もっとトークンがあったらもっと大きい答えができそうです。
その3番目の方法は自分でモデルを使います。サーバがないです。一番面白い方法ではありませんか :yum:

まだ色々なパラメータが必要そうですね。でも、奥さんは待っていますよ。。。:sweat_smile: 便利と早いなソリューションが欲しいです!

API

APIはもっと早いかな。。。

import requests
import json

r = requests.get('https://www.themealdb.com/api/json/v1/1/random.php')
answerJson = json.loads(r.content)

meal            = answerJson["meals"][0]
title           = meal["strMeal"]
instructions    = meal["strInstructions"]
youtube         = meal["strYoutube"]

ingredients     = ""
ingredientsKey  = "strIngredient"
measureKey      = "strMeasure"
for i in range(1,20):
    if meal[ingredientsKey + str(i)] != "":
        ingredients += (meal[ingredientsKey + str(i)] + ":" + meal[measureKey + str(i)] + "\n")

print(title)
print(ingredients)
print(instructions)
print(youtube)

結果は:

Nanaimo Bars
Custard:125g
Caster Sugar:50g
Cocoa:5 tbs
Egg:1 beaten
Digestive Biscuits:200g shredded
Desiccated Coconut:100g 
Almonds:50g
Butter:100g 
Double Cream:4 tbs
Custard Powder:3 tbs
Icing Sugar:250g
Dark Chocolate:150g
Butter:50g

Start by making the biscuit base. In a bowl, over a pan of simmering water, melt the butter with the sugar and cocoa powder, stirring occasionally until smooth. Whisk in the egg for 2 to 3 mins until the mixture has thickened. Remove from heat and mix in the biscuit crumbs, coconut and almonds if using, then press into the base of a lined 20cm square tin. Chill for 10 mins.
For the middle layer, make the custard icing; whisk together the butter, cream and custard powder until light and fluffy, then gradually add the icing sugar until fully incorporated. Spread over the bottom layer and chill in the fridge for at least 10 mins until the custard is no longer soft.
Melt the chocolate and butter together in the microwave, then spread over the chilled bars and put back in the fridge. Leave until the chocolate has fully set (about 2 hrs). Take the mixture out of the tin and slice into squares to serve.
https://www.youtube.com/watch?v=MMrE4I1ZtWo

5-10minでできました。終わりました。。。

まとめ

どう思いますか?もっと一緒にAIの勉強をしたいですか?もし興味を持っていただけたらコメントをください:relaxed:

まとめはAIは面白いです。プログラムでAI(モデル)を使うのことができます!
面白い!
モデルの答えは質問やモデルの大きさやパラムのように変わります。色々なモデルができます

時々モデルは一番便利とか早い答えではありません。(KISS、keep it simple stupid)

65
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
65
2