import gradio as gr import urllib.request import json def handler(): try: url = 'https://api.thecatapi.com/v1/images/search' with urllib.request.urlopen(url) as response: # 使用 urllib 發送請求 data = json.load(response) # 解析回傳的 JSON 資料 return data[0]['url'] # 返回圖片 URL except Exception as e: return None # 若發生錯誤,返回 None(圖片不顯示) # 輸出元件 out1 = gr.Image(type='filepath', label='可愛的貓咪圖片', width=640, height=480) # Gradio 介面 iface = gr.Interface( fn=handler, # 處理函式 inputs=[], outputs=[out1], # 輸出圖片 title='隨機貓咪圖', flagging_mode='never' ) iface.launch()