Spaces:
Running
Running
File size: 1,363 Bytes
8daab7a f9a9c12 9fd63d3 f9a9c12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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 的模型)
@st.cache_resource
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("請先輸入一些註解或代碼喔!")
|