# 表情生成器:上传人脸 + Prompt 控制表情(轻量版) import gradio as gr import torch from diffusers import StableDiffusionImg2ImgPipeline from PIL import Image # 使用 SD1.5 图像转图像版本 model_id = "runwayml/stable-diffusion-v1-5" pipe = StableDiffusionImg2ImgPipeline.from_pretrained( model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32 ).to("cuda" if torch.cuda.is_available() else "cpu") # 表情 prompt 定义 expression_prompts = { "neutral": "a person with a neutral expression", "happy": "a smiling person", "laughing": "a person laughing joyfully", "funny": "a person making a funny face", "sad": "a person looking sad", "angry": "a person looking angry", "crying": "a person crying", "loving": "a person showing love", "embarrassed": "a person looking embarrassed", "surprised": "a surprised person", "shocked": "a person with a shocked expression", "thinking": "a person thinking deeply", "winking": "a person winking", "cool": "a person with a cool expression wearing sunglasses", "relaxed": "a relaxed person", "delicious": "a person enjoying delicious food", "kissy": "a person making a kissy face", "confident": "a confident person", "sleepy": "a sleepy person", "silly": "a person acting silly", "confused": "a confused person" } @torch.inference_mode() def generate_expression(image, expression): if image.mode != "RGB": image = image.convert("RGB") # Resize to 512x512 for compatibility image = image.resize((512, 512), Image.Resampling.LANCZOS) prompt = expression_prompts[expression] negative_prompt = "blurry, low quality, distorted, bad anatomy" result = pipe( image=image, prompt=prompt, negative_prompt=negative_prompt, strength=0.6, # 稍微低一些以保留原图结构 guidance_scale=7.5, num_inference_steps=30 ) return result.images[0], f"生成了表情:{expression}" expression_list = list(expression_prompts.keys()) with gr.Blocks() as demo: gr.Markdown("# 🎭 AI 表情生成器(上传图片)\n上传你的脸,选择一个表情,AI 会保留人脸并改变表情。") with gr.Row(): with gr.Column(): image_input = gr.Image(type="pil", label="上传人脸图像") expression_input = gr.Radio(expression_list, label="选择一个表情") submit_btn = gr.Button("生成表情图像") with gr.Column(): image_output = gr.Image(label="生成结果") log_output = gr.Textbox(label="状态") submit_btn.click( fn=generate_expression, inputs=[image_input, expression_input], outputs=[image_output, log_output] ) if __name__ == "__main__": demo.launch()