Spaces:
Sleeping
Sleeping
import gradio as gr | |
import numpy as np | |
import random | |
import logging | |
import sys | |
import os | |
from PIL import Image as PILImage | |
# 设置日志记录 | |
logging.basicConfig(level=logging.INFO, | |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
stream=sys.stdout) | |
logger = logging.getLogger(__name__) | |
# 修复 Gradio JSON Schema 错误 | |
try: | |
import gradio_client.utils | |
# 保存原始函数 | |
original_get_type = gradio_client.utils.get_type | |
# 创建新的 get_type 函数,处理布尔值 | |
def patched_get_type(schema): | |
if schema is True or schema is False or schema is None: | |
return "any" | |
if not isinstance(schema, dict): | |
return "any" | |
return original_get_type(schema) | |
# 替换原始函数 | |
gradio_client.utils.get_type = patched_get_type | |
logger.info("Successfully patched gradio_client.utils.get_type") | |
# 同样修补 _json_schema_to_python_type 函数 | |
original_json_schema_to_python_type = gradio_client.utils._json_schema_to_python_type | |
def patched_json_schema_to_python_type(schema, defs=None): | |
if schema is True or schema is False: | |
return "bool" | |
if schema is None: | |
return "None" | |
if not isinstance(schema, dict): | |
return "any" | |
try: | |
return original_json_schema_to_python_type(schema, defs) | |
except Exception as e: | |
logger.warning(f"Error in json_schema_to_python_type: {e}") | |
return "any" | |
gradio_client.utils._json_schema_to_python_type = patched_json_schema_to_python_type | |
logger.info("Successfully patched gradio_client.utils._json_schema_to_python_type") | |
except Exception as e: | |
logger.error(f"Failed to patch Gradio utils: {e}") | |
# 创建一个简单的示例图像 | |
def create_dummy_image(): | |
logger.info("Creating dummy image") | |
img = PILImage.new('RGB', (256, 256), color = (255, 100, 100)) | |
return img | |
# 创建一个模拟图像生成器 | |
def create_mock_image(prompt): | |
"""当模型加载不成功时,创建一个带有提示词的简单图像""" | |
logger.info(f"创建简单图像: {prompt}") | |
# 创建一个基础图像 | |
img = PILImage.new('RGB', (512, 512), color=(240, 240, 250)) | |
# 在图像上写文字 | |
try: | |
from PIL import ImageDraw, ImageFont | |
draw = ImageDraw.Draw(img) | |
# 尝试找一个合适的字体 | |
try: | |
font = ImageFont.truetype("arial.ttf", 20) | |
except: | |
try: | |
font = ImageFont.truetype("DejaVuSans.ttf", 20) | |
except: | |
font = ImageFont.load_default() | |
# 添加提示文本 | |
text = f"提示词: {prompt}" | |
draw.text((20, 20), text, fill=(0, 0, 0), font=font) | |
draw.text((20, 60), "模型加载失败,显示占位图像", fill=(255, 0, 0), font=font) | |
except Exception as e: | |
logger.error(f"创建文字图像失败: {e}") | |
return img | |
# 使用简单的文本生成器 | |
def text_to_image(prompt): | |
"""一个非常简单的基于规则的文本到图像生成器""" | |
logger.info(f"使用简单规则生成图像: {prompt}") | |
# 创建基础图像 | |
img = PILImage.new('RGB', (512, 512), color=(240, 240, 250)) | |
# 尝试分析提示词内容 | |
color = (100, 100, 200) # 默认蓝色 | |
# 简单的颜色匹配 | |
color_words = { | |
'red': (200, 50, 50), | |
'blue': (50, 50, 200), | |
'green': (50, 200, 50), | |
'yellow': (200, 200, 50), | |
'purple': (150, 50, 150), | |
'orange': (220, 140, 20), | |
'pink': (255, 150, 200), | |
'black': (30, 30, 30), | |
'white': (240, 240, 240), | |
'gray': (128, 128, 128), | |
} | |
# 检查提示词中是否包含颜色 | |
prompt_lower = prompt.lower() | |
for color_word, rgb in color_words.items(): | |
if color_word in prompt_lower: | |
color = rgb | |
break | |
# 创建一个简单的图形 | |
from PIL import ImageDraw | |
draw = ImageDraw.Draw(img) | |
# 根据提示词选择不同的绘制方式 | |
if any(animal in prompt_lower for animal in ['cat', 'kitty', 'kitten']): | |
# 画一个简单的猫 | |
draw.ellipse((156, 156, 356, 306), fill=color) # 头 | |
draw.ellipse((196, 176, 246, 226), fill=(255, 255, 255)) # 左眼 | |
draw.ellipse((266, 176, 316, 226), fill=(255, 255, 255)) # 右眼 | |
draw.ellipse((211, 191, 231, 211), fill=(0, 0, 0)) # 左眼球 | |
draw.ellipse((281, 191, 301, 211), fill=(0, 0, 0)) # 右眼球 | |
draw.polygon([(256, 256), (236, 246), (276, 246)], fill=(255, 100, 150)) # 鼻子 | |
draw.line([(256, 256), (256, 286)], fill=(0, 0, 0), width=2) # 鼻线 | |
draw.arc((206, 256, 306, 336), 0, 180, fill=(0, 0, 0), width=2) # 嘴 | |
# 猫耳朵 | |
draw.polygon([(206, 156), (156, 76), (246, 126)], fill=color) | |
draw.polygon([(306, 156), (356, 76), (266, 126)], fill=color) | |
elif any(landscape in prompt_lower for landscape in ['landscape', 'mountain', 'sunset', 'nature']): | |
# 画一个简单的风景 | |
# 天空 | |
sky_color = (100, 150, 250) | |
if 'sunset' in prompt_lower: | |
sky_color = (250, 150, 100) | |
draw.rectangle([(0, 0), (512, 300)], fill=sky_color) | |
# 太阳/月亮 | |
if 'sunset' in prompt_lower or 'sun' in prompt_lower: | |
draw.ellipse((400, 50, 480, 130), fill=(255, 200, 50)) | |
elif 'night' in prompt_lower or 'moon' in prompt_lower: | |
draw.ellipse((400, 50, 480, 130), fill=(240, 240, 240)) | |
# 山 | |
draw.polygon([(0, 300), (200, 100), (400, 300)], fill=(100, 100, 100)) | |
draw.polygon([(100, 300), (300, 50), (500, 300)], fill=(80, 80, 80)) | |
# 地面 | |
ground_color = (100, 200, 100) | |
if 'desert' in prompt_lower: | |
ground_color = (240, 220, 180) | |
elif 'snow' in prompt_lower or 'winter' in prompt_lower: | |
ground_color = (240, 240, 250) | |
draw.rectangle([(0, 300), (512, 512)], fill=ground_color) | |
else: | |
# 默认绘制一些简单的几何图形 | |
draw.rectangle([(106, 106), (406, 406)], outline=(0, 0, 0), width=2) | |
draw.ellipse((156, 156, 356, 356), fill=color) | |
draw.polygon([(256, 106), (406, 406), (106, 406)], fill=(color[0]//2, color[1]//2, color[2]//2)) | |
# 添加提示词文本 | |
try: | |
font = ImageFont.load_default() | |
draw.text((10, 10), f"提示词: {prompt}", fill=(0, 0, 0), font=font) | |
draw.text((10, 30), "由简单规则生成", fill=(100, 100, 100), font=font) | |
except Exception as e: | |
logger.error(f"添加文字失败: {e}") | |
return img | |
# 生成图像函数 | |
def generate_image(prompt): | |
# 如果提示为空,使用默认提示 | |
if not prompt or prompt.strip() == "": | |
prompt = "a beautiful landscape" | |
logger.info(f"输入为空,使用默认提示词: {prompt}") | |
logger.info(f"收到提示词: {prompt}") | |
# 不再尝试加载AI模型,直接使用规则生成器 | |
logger.info("使用规则生成器代替AI模型") | |
return text_to_image(prompt) | |
# 创建Gradio界面 | |
def create_demo(): | |
# 创建界面 | |
demo = gr.Interface( | |
fn=generate_image, | |
inputs=gr.Textbox(label="输入提示词(例如:猫、风景、日落)"), | |
outputs=gr.Image(type="pil", label="生成的图像"), | |
title="简易文本到图像生成器", | |
description="输入文本描述,生成相应的图像(使用规则生成器,不依赖AI模型)", | |
examples=["a cute cat", "beautiful sunset", "mountain landscape", "red circle"], | |
cache_examples=False, | |
flagging_mode=None | |
) | |
return demo | |
# 创建演示界面 | |
demo = create_demo() | |
# 启动应用 | |
if __name__ == "__main__": | |
try: | |
logger.info("启动Gradio界面...") | |
# 使用最小配置 | |
demo.launch( | |
server_name="0.0.0.0", | |
show_api=False, # 禁用API | |
share=False, # 不创建公共链接 | |
debug=False, # 禁用调试模式 | |
quiet=True # 减少日志输出 | |
) | |
except Exception as e: | |
logger.error(f"启动失败: {e}") | |