Spaces:
Sleeping
Sleeping
Update app.py
Browse files1233456789101112131415161718192021222324252627282930456789101112131415161718323334351920372122232425262728293031323334353940414243444546474849505152533637383940555657585960614142436364656667686970717273747576777879808182838485868788899091929394959697989910010110210310444454647484950515253545556575859606162106107108109110111636411465661161176768import osimport gradio as gr
# 創建 Gradio 介面def create_interface(): with gr.Blocks() as demo: gr.HTML(""" <!DOCTYPE html> <html> <head> <title>成語對對碰</title> <script src="https://unpkg.com/react@17/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> </head> <body> <div id="root"></div> <script type="text/babel"> // React 組件 const idiomDatabase = [ { mainIdiom: '急如星火', synonyms: ['迫在眉睫', '刻不容緩'], meaning: '形容事情非常緊急' }, { mainIdiom: '一葉知秋', synonyms: ['見微知著', '月暈而風'], meaning: '從小徵兆可以預見未來的發展' }, { mainIdiom: '一丘之貉', synonyms: ['沆瀣一氣', '狐群狗黨'], meaning: '形容品性相同的壞人' }, { mainIdiom: '一蹴可幾', synonyms: ['一步登天', '唾手可得'], meaning: '一下子就能達到目的' }, { mainIdiom: '一暴十寒', synonyms: ['兩天打魚,三天曬網', '虎頭蛇尾'], meaning: '形容學習或做事不能持之以恆' }, { mainIdiom: '環堵蕭然', synonyms: ['一貧如洗', '家徒四壁'], meaning: '形容生活很貧困' }, { mainIdiom: '一字千金', synonyms: ['字字珠璣', '文不加點'], meaning: '形容文章寫得好,文字珍貴' }, { mainIdiom: '一擲千金', synonyms: ['揮金如土', '揮霍無度'], meaning: '形容揮霍錢財' }, { mainIdiom: '生靈塗炭', synonyms: ['民不聊生', '民生凋敝'], meaning: '形容人民生活困苦' }, { mainIdiom: '瓜熟蒂落', synonyms: ['水到渠成', '順理成章'], meaning: '形容事情自然成功' }];# 確保 groq 已安裝try: from groq import Groqexcept ImportError: os.system('pip install groq') from groq import Groq
# 初始化 Groq 客戶端client = Groq()
# 獲取 API 密鑰api_key = os.getenv('groq_key')if not api_key: raise ValueError("API key 'groq_key' 未設定於環境變數中!")
function ChineseIdiomGame() { const [questionIndex, setQuestionIndex] = React.useState(0); const [score, setScore] = React.useState(0); const [selectedAnswers, setSelectedAnswers] = React.useState([]);client.api_key = api_key
const currentQuestion = idiomDatabase[questionIndex];def chat_with_groq(user_message): """與 Groq 模型進行互動""" try: completion = client.chat.completions.create( model="llama-3.1-70b-versatile", messages=[ {"role": "system", "content": "你是一個國中國文老師,會出成語遊戲讓學生玩"}, {"role": "user", "content": user_message} ], temperature=1, max_tokens=1024, top_p=1, stream=False )
const handleSelect = (answer) => { if (selectedAnswers.includes(answer)) return; if (currentQuestion.synonyms.includes(answer)) { const newSelected = [...selectedAnswers, answer]; setSelectedAnswers(newSelected); if (newSelected.length === 2) { const newScore = score + 10; setScore(newScore); setTimeout(() => { setQuestionIndex((questionIndex + 1) % idiomDatabase.length); setSelectedAnswers([]); }, 1000); } } }; response = "" for chunk in completion: response += chunk.choices[0].delta.content or "" return response
const options = [ ...currentQuestion.synonyms, '望穿秋水', '守株待兔', '揮金如土', '一暴十寒' ].sort(() => Math.random() - 0.5); except Exception as e: return f"發生錯誤:{e}"
return ( <div style={{ padding: '20px' }}> <h1 style={{ textAlign: 'center', marginBottom: '20px' }}>成語對對碰</h1> <div style={{ backgroundColor: '#f0f0f0', padding: '20px', borderRadius: '8px', marginBottom: '20px' }}> <h2 style={{ textAlign: 'center' }}>{currentQuestion.mainIdiom}</h2> <p style={{ textAlign: 'center' }}>{currentQuestion.meaning}</p> </div> <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '10px' }}> {options.map((option, index) => ( <button key={index} onClick={() => handleSelect(option)} style={{ padding: '10px', backgroundColor: selectedAnswers.includes(option) ? '#4CAF50' : 'white', color: selectedAnswers.includes(option) ? 'white' : 'black', border: '1px solid #ddd', borderRadius: '4px' }} > {option} </button> ))} </div> <div style={{ marginTop: '20px', textAlign: 'center' }}> 分數: {score} </div> </div> ); }# 定義 Gradio 介面def gradio_chatbot(): chatbot = gr.Chatbot()
def respond(message, history): response = chat_with_groq(message) history.append((message, response)) return history, history
with gr.Blocks() as demo: with gr.Row(): gr.Markdown("### 成語遊戲 Chatbot") with gr.Row(): chatbot = gr.Chatbot() with gr.Row(): user_input = gr.Textbox(placeholder="輸入你的訊息...") submit_button = gr.Button("送出") submit_button.click(respond, [user_input, chatbot], [chatbot, chatbot])
ReactDOM.render(<ChineseIdiomGame />, document.getElementById('root')); </script> </body> </html> """) return demo
# 啟動 Gradio 介面# 啟動應用程式if __name__ == "__main__": demo = create_interface() demo.launch() app = gradio_chatbot() app.launch()app.py+57-106