Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149import gradio as grimport requestsimport jsonimport timeimport os# --- 配置資訊 ---API_KEY = "d72ef10876b9403a9479c6e31f27a4be"WORKFLOW_ID = "1958842411961233410"# RunningHub API 端點UPLOAD_URL = "https://www.runninghub.cn/api/resource/openapi/upload"CREATE_TASK_URL = "https://www.runninghub.cn/task/openapi/create"GET_TASK_INFO_URL = "https://www.runninghub.cn/task/openapi/getTaskInfo"# 你的工作流中需要修改的節點IDLOAD_IMAGE_NODE_ID = "141"POSITIVE_PROMPT_NODE_ID = "144"SEED_NODE_ID = "132"# --- 核心邏輯函式 ---def process_image_with_runninghub(uploaded_image, positive_prompt, seed):"""處理上傳圖片,調用 RunningHub API 進行圖像生成。"""if uploaded_image is None:return "請先上傳一張圖片!", None# 步驟 1: 上傳圖片到 RunningHubyield "正在上傳圖片...", Nonetry:# 準備 multipart/form-data 的數據files = {'file': open(uploaded_image, 'rb')}data = {'apiKey': API_KEY}# requests 函式庫會自動處理正確的 content-typeupload_response = requests.post(UPLOAD_URL, data=data, files=files)upload_response.raise_for_status()upload_data = upload_response.json()# 除錯:印出上傳 API 的回傳內容print(f"上傳 API 回傳: {upload_data}")if upload_data.get("code") != 0:return f"圖片上傳失敗!訊息: {upload_data.get('msg')}", None# 從回傳結果中取得檔案名稱rh_image_path = upload_data["data"]["fileName"]yield f"圖片上傳成功!路徑: {rh_image_path}", Noneexcept requests.exceptions.RequestException as e:return f"上傳連線錯誤: {e}", None# 步驟 2: 建立 ComfyUI 任務yield "正在建立算圖任務...", Nonenode_info_list = [{"nodeId": LOAD_IMAGE_NODE_ID, "fieldName": "image", "fieldValue": rh_image_path},{"nodeId": POSITIVE_PROMPT_NODE_ID, "fieldName": "ShowText_0", "fieldValue": positive_prompt},{"nodeId": SEED_NODE_ID, "fieldName": "seed", "fieldValue": seed}]payload = {"apiKey": API_KEY,"workflowId": WORKFLOW_ID,"nodeInfoList": node_info_list}headers = {'Content-Type': 'application/json'}try:create_response = requests.post(CREATE_TASK_URL, headers=headers, data=json.dumps(payload))create_response.raise_for_status()create_data = create_response.json()if create_data.get("code") != 0:return f"任務建立失敗!錯誤碼: {create_data.get('code')}, 訊息: {create_data.get('msg')}", Nonetask_id = create_data["data"]["taskId"]yield f"任務已建立!任務ID: {task_id}", Noneexcept requests.exceptions.RequestException as e:return f"任務建立連線錯誤: {e}", None# 步驟 3: 輪詢任務狀態max_retries = 30retry_interval = 5for i in range(max_retries):yield f"正在查詢任務狀態... (第 {i+1} 次)", Nonetime.sleep(retry_interval)status_payload = {"apiKey": API_KEY, "taskId": task_id}try:status_response = requests.post(GET_TASK_INFO_URL, headers=headers, data=json.dumps(status_payload))status_response.raise_for_status()status_data = status_response.json()current_status = status_data["data"]["taskStatus"]if current_status == "SUCCESS":image_url = status_data["data"]["imageInfoList"][0]["fileUrl"]yield f"任務完成!", image_urlreturn f"任務完成!", image_urlelif current_status == "FAILED":error_msg = status_data.get("data", {}).get("errorMsg", "Unknown error")yield f"任務失敗!錯誤訊息: {error_msg}", Nonereturn f"任務失敗!錯誤訊息: {error_msg}", Noneexcept requests.exceptions.RequestException as e:yield f"查詢連線錯誤: {e}", Nonereturn f"查詢連線錯誤: {e}", Noneyield "查詢任務超時,請稍後使用任務ID手動查詢。", Nonereturn "查詢任務超時,請稍後使用任務ID手���查詢。", None# --- Gradio 介面設定 ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# RunningHub - 圖像處理工作流")gr.Markdown("上傳一張圖片,輸入提示詞和種子值,然後啟動遠端圖像處理任務。")with gr.Row():with gr.Column():with gr.Row():image_input = gr.Image(type="filepath", label="上傳圖片")with gr.Column():prompt_input = gr.Textbox(lines=3, label="正向提示詞 (Positive Prompt)", placeholder="輸入你想要生成的內容...")seed_input = gr.Number(label="種子值 (Seed)", value=-1, precision=0)process_button = gr.Button("開始處理圖像", variant="primary")with gr.Column():with gr.Row():image_output = gr.Image(label="生成的圖像")with gr.Row():status_output = gr.Textbox(label="任務狀態", interactive=False)process_button.click(fn=process_image_with_runninghub,inputs=[image_input, prompt_input, seed_input],outputs=[status_output, image_output])if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142import gradio as grimport requests# --- 配置資訊 ---API_KEY = "d72ef10876b9403a9479c6e31f27a4be".strip()UPLOAD_URL = "https://www.runninghub.cn/api/resource/openapi/upload"# --- 核心函式 ---def test_upload_image(image_path):if image_path is None:return "請先上傳圖片!"try:with open(image_path, "rb") as f:files = {"file": f}data = {"apiKey": API_KEY}response = requests.post(UPLOAD_URL, data=data, files=files)response.raise_for_status()result = response.json()print(result) # 除錯用if result.get("code") == 0:return f"上傳成功!路徑: {result['data']['fileName']}"else:return f"上傳失敗!訊息: {result.get('msg')}"except requests.exceptions.RequestException as e:return f"連線錯誤: {e}"# --- Gradio 介面 ---with gr.Blocks() as demo:gr.Markdown("# RunningHub 上傳測試")gr.Markdown("上傳一張圖片,測試 API Key 是否有效。")image_input = gr.Image(type="filepath", label="上傳圖片")status_output = gr.Textbox(label="狀態", interactive=False)upload_button = gr.Button("測試上傳")upload_button.click(fn=test_upload_image, inputs=image_input, outputs=status_output)if __name__ == "__main__":demo.launch(share=True)
app.py+30-137