Spaces:
Running
Running
| import streamlit as st | |
| import torch | |
| from transformers import pipeline | |
| # 1. 網頁標題與外觀設定 | |
| st.set_page_config(page_title="AI Python 代碼助手", page_icon="🤖") | |
| st.title("專屬 AI 程式碼自動補全助手") | |
| st.markdown("輸入你的 Python 註解或變數,AI 將自動幫你寫完後續的程式碼!") | |
| # 2. 載入模型的快取機制 (避免每次輸入都重新載入 500MB 的模型) | |
| def load_model(): | |
| device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") | |
| pipe = pipeline("text-generation", model="huggingface-course/codeparrot-ds", device=device) | |
| return pipe | |
| pipe = load_model() | |
| # 3. 建立使用者輸入區 | |
| user_input = st.text_area("請輸入程式碼註解 (例如:# create a scatter plot):", height=150) | |
| # 4. 建立生成按鈕與輸出邏輯 | |
| if st.button("✨ 讓 AI 幫我寫程式"): | |
| if user_input: | |
| with st.spinner("AI 正在思考中..."): | |
| # 執行推論 | |
| result = pipe(user_input, max_new_tokens=50, num_return_sequences=1)[0]["generated_text"] | |
| st.success("生成成功!") | |
| st.subheader("💡 生成結果:") | |
| # 用漂亮的程式碼區塊顯示結果 | |
| st.code(result, language="python") | |
| else: | |
| st.warning("請先輸入一些註解或代碼喔!") | |