Spaces:
Sleeping
Sleeping
File size: 8,398 Bytes
82df48f 407a5fa 8718399 65762c4 407a5fa 7a3e379 3b80791 65762c4 3b80791 a0be010 65762c4 5f71263 4564834 5f71263 4564834 5f71263 4564834 5f71263 4564834 5f71263 4564834 5f71263 4564834 5f71263 4564834 7a3e379 4564834 5f71263 4564834 5f71263 7a3e379 4564834 5f71263 4564834 5f71263 4564834 5f71263 7a3e379 82df48f 4564834 e2bc0a8 82df48f 407a5fa 4564834 7a3e379 4564834 407a5fa 4564834 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
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}")
|