Download app.py from ronchiu/G2: direct link, hf CLI and curl.
- Browser
- Download file 3.08 kB
-
https://huggingface.co/spaces/ronchiu/G2/resolve/main/app.py
- Command line
-
hf download hf://spaces/ronchiu/G2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ronchiu/G2/resolve/main/app.py
3.08 kB
| # -----------------------------------------------------[Part1 匯入基礎工具]----------------------------------------------------------- | |
| # ✅ Gradio | |
| import gradio as gr | |
| # ✅ GPT(OpenAI) | |
| from openai import OpenAI | |
| # --------------------------------------------------------------------[Part2 設定GPT+ API]--------------------------------------------------- | |
| # ✅ API 金鑰(直接寫死在後台,不讓使用者輸入) | |
| openai_api_key = "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" # ✅ 保留 | |
| # ✅ 選擇模型 | |
| #openai_model = "gpt-3.5-turbo" | |
| openai_model = "gpt-4o" | |
| # ✅ 建立 OpenAI 客戶端 | |
| client = OpenAI(api_key=openai_api_key) | |
| ########################################################### 以下可改動 ################################################################# | |
| # -----------------------------------------[Part3 System Prompt]----------------------------------------------------------------------------- | |
| prompt_system = """ | |
| 你是一位詩人,請根據使用者輸入的幾個關鍵字,創作一首簡短的詩。 | |
| 詩的主題需與關鍵字相關,語氣可以是溫柔的、抒情的、或自由詩風格。 | |
| ⚠️ 請硬性遵守以下規則: | |
| 1. 詩的第一句必須是:「這是詩人 Heidi 的大作。」 | |
| 2. 接下來才開始寫與關鍵字相關的詩句。 | |
| 3. 不要加上其他開場白或說明。 | |
| """ | |
| # -----------------------------------------[Part4 GPT + OCR 處理]----------------------------------------------------------------------- | |
| def generate_from_text(keywords): | |
| try: | |
| if not keywords.strip(): # 若為空,回傳提示 | |
| return "⚠️ 請輸入至少一個關鍵字喔!" | |
| # ✅ 使用者輸入文字就直接使用 | |
| full_prompt = f"關鍵字:{keywords}\n\n請根據這些關鍵字寫一首詩。" | |
| # ✅ 呼叫 GPT | |
| response = client.chat.completions.create( | |
| model=openai_model, | |
| messages=[ | |
| {"role": "system", "content": prompt_system}, | |
| {"role": "user", "content": full_prompt} | |
| ], | |
| temperature=0.8 | |
| ) | |
| # ✅ 回傳結果 | |
| return response.choices[0].message.content | |
| except Exception as e: | |
| return f"⚠️ 發生錯誤:{str(e)}" | |
| # -----------------------------------------[Part5 Gradio 前端設計與啟動]----------------------------------------------------------------- | |
| def process_gradio_text(keywords): | |
| return generate_from_text(keywords) | |
| # ✅ Gradio 介面設計 | |
| gr.Interface( | |
| fn=process_gradio_text, | |
| title="📝 詩的生成器", | |
| description="輸入幾個關鍵字,我會為你寫一首詩 🎨", | |
| # ✅ inputs | |
| inputs=[ | |
| gr.Textbox(label="請輸入關鍵字", placeholder="例如:雨、夜晚、思念"), | |
| ], | |
| # ✅ outputs | |
| outputs=gr.Textbox(label="GPT 生成的詩"), | |
| allow_flagging="never", | |
| live=False | |
| ).launch(debug=True) | |