alo / app.py
ochyai's picture
Update app.py
528421f
raw
history blame
3.15 kB
import gradio as gr
import openai
import requests
import os
import fileinput
from dotenv import load_dotenv
title="Abstract Language Object Generator"
inputs_label="Input Object"
outputs_label="ALOs"
description="""
- ※up to 1000 character it takes 120 sec for generation. Because of API.
"""
article = """
"""
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
MODEL = "gpt-4"
def get_filetext(filename, cache={}):
if filename in cache:
# キャッシュに保存されている場合は、キャッシュからファイル内容を取得する
return cache[filename]
else:
if not os.path.exists(filename):
raise ValueError(f"ファイル '{filename}' が見つかりませんでした")
with open(filename, "r") as f:
text = f.read()
# ファイル内容をキャッシュする
cache[filename] = text
return text
class OpenAI:
@classmethod
def chat_completion(cls, prompt, start_with=""):
constraints = get_filetext(filename = "constraints.md")
template = get_filetext(filename = "template.md")
# ChatCompletion APIに渡すデータを定義する
data = {
"model": "gpt-4",
"messages": [
{"role": "system", "content": constraints}
,{"role": "system", "content": template}
,{"role": "assistant", "content": "Sure!"}
,{"role": "user", "content": prompt}
,{"role": "assistant", "content": start_with}
],
}
# ChatCompletion APIを呼び出す
response = requests.post(
"https://api.openai.com/v1/chat/completions",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {openai.api_key}"
},
json=data
)
# ChatCompletion APIから返された結果を取得する
result = response.json()
print(result)
content = result["choices"][0]["message"]["content"].strip()
return content
class NajiminoAI:
@classmethod
def generate_emo_prompt(cls, user_message):
template = get_filetext(filename="template.md")
prompt = f"""
---
INPUT =
---
{user_message}
---
ALOs(INPUT)
---
{template}
"""
return prompt
@classmethod
def generate_emo(cls, user_message):
prompt = NajiminoAI.generate_emo_prompt(user_message);
start_with = ""
result = OpenAI.chat_completion(prompt=prompt, start_with=start_with)
return result
def main():
iface = gr.Interface(fn=NajiminoAI.generate_emo,
inputs=gr.Textbox(label=inputs_label),
outputs=gr.Textbox(label=outputs_label),
title=title,
description=description,
article=article,
allow_flagging='never'
)
iface.launch()
if __name__ == '__main__':
main()