import httpcore setattr(httpcore, 'SyncHTTPTransport', 'AsyncHTTPProxy') # Beta3.1.1: 加入了自訂義方塊,有分享功能,png import gradio as gr from googletrans import Translator from huggingface_hub import InferenceClient from PIL import Image import time # 定義模型名稱列表 models = [ "Yntec/NostalgicLife", "Yntec/Genuine", "Yntec/Abased", "Yntec/CuteFurry", "Yntec/GOLDFish", "Yntec/Isabelia", "Yntec/incha_re_zoro", "Yntec/InsaneM3U", "digiplay/2K", "digiplay/2K-VAE", "digiplay/ya3_VAE", "digiplay/ya3p_VAE", "digiplay/pan04", "digiplay/AM-mix1", "digiplay/MRMD_0505", ] # 初始化 Google 翻譯器 translator = Translator() # 定義翻譯函數 def translate_to_english(prompt): try: translated_prompt = translator.translate(prompt, src='auto', dest='en').text return translated_prompt except Exception as e: return str(e) # 修改 respond_with_timestamp 函數,使其返回三個圖片對象 def respond_with_timestamp(prompt, model_name, custom_model_name): if custom_model_name: # 檢查是否提供了自訂模型名稱 client = InferenceClient(model=custom_model_name) else: # 如果沒有提供自訂模型名稱,就使用下拉選的模型 client = InferenceClient(model=model_name) # 將提示詞翻譯成英文 translated_prompt = translate_to_english(prompt) # 使用時間戳記加在提示語後面 prompt_with_timestamps = [f"{translated_prompt} {time.time() + i}" for i in range(3)] # 生成三張圖片 try: images = [client.text_to_image(text) for text in prompt_with_timestamps] except Exception as e: return [f"Error generating images: {str(e)}"] * 3 # 返回錯誤訊息而非圖片 # 返回三個圖片對象 return images # 建立和啟動 Gradio 介面 demo = gr.Interface( fn=respond_with_timestamp, inputs=[ gr.Textbox(label="請輸入提示語 Please input a prompt"), gr.Dropdown(label="選擇模型 Choose a model", choices=models), gr.Textbox(label="自訂模型名稱 Or type Any model you like") # 讓自訂模型名稱變成選擇性 ], outputs=[gr.Image(type="pil", format="PNG", label=f"img-{i+1}", show_share_button=True) for i in range(3)], # 顯示三張圖片 title="Text-to-Image with Auto Translation" ) if __name__ == "__main__": demo.launch()