Spaces:
Runtime error
Runtime error
run
Browse files
app.py
CHANGED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
OPEN_AI_KEY = os.getenv("OPEN_AI_KEY")
|
| 9 |
+
OPEN_AI_CLIENT = OpenAI(api_key=OPEN_AI_KEY)
|
| 10 |
+
|
| 11 |
+
def generate_article(reference_text, seed_words, derivative_words, prompt_text):
|
| 12 |
+
# 結合用戶輸入來形成最終的prompt
|
| 13 |
+
reference_text = f"""
|
| 14 |
+
文章:{reference_text}
|
| 15 |
+
關鍵詞:{seed_words}
|
| 16 |
+
衍生詞:{derivative_words}
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
sys_content = "你是一個擅長中文教學的老師,使用 zh-TW"
|
| 22 |
+
user_content = f"""
|
| 23 |
+
請根據 {reference_text}
|
| 24 |
+
{prompt_text}
|
| 25 |
+
"""
|
| 26 |
+
messages = [
|
| 27 |
+
{"role": "system", "content": sys_content},
|
| 28 |
+
{"role": "user", "content": user_content}
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
request_payload = {
|
| 32 |
+
"model": "gpt-4-1106-preview",
|
| 33 |
+
"messages": messages,
|
| 34 |
+
"max_tokens": 4000,
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
|
| 38 |
+
article = response.choices[0].message.content.strip()
|
| 39 |
+
|
| 40 |
+
# 返回生成的文章
|
| 41 |
+
return article
|
| 42 |
+
|
| 43 |
+
# 定義Gradio介面
|
| 44 |
+
with gr.Blocks() as demo:
|
| 45 |
+
with gr.Row():
|
| 46 |
+
reference_text = gr.Textbox(label="原文參考", placeholder="貼上原文參考...", lines=4)
|
| 47 |
+
seed_words = gr.Textbox(label="文章生字", placeholder="貼上文章生字...", lines=2)
|
| 48 |
+
derivative_words = gr.Textbox(label="衍生生字", placeholder="貼上衍生生字...", lines=2)
|
| 49 |
+
prompt_text = gr.Textbox(label="prompt的文字", placeholder="輸入或修改prompt的文字...")
|
| 50 |
+
generate_article_btn = gr.Button(label="生成文章")
|
| 51 |
+
|
| 52 |
+
with gr.Row():
|
| 53 |
+
new_article = gr.Textbox(label="生成的文章")
|
| 54 |
+
|
| 55 |
+
generate_article_btn.click(
|
| 56 |
+
generate_article,
|
| 57 |
+
inputs =[reference_text, seed_words, derivative_words, prompt_text],
|
| 58 |
+
outputs=new_article
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
demo.launch()
|