ExtractIt / app.py
shawntan111's picture
Create app.py
cfbc31f verified
Raw History Blame Contribute Delete
11 kB
import sys
import warnings
# 1. 屏蔽 Python 3.12 垃圾回收事件循环时的无效 traceback 日志
if sys.version_info >= (3, 12):
import asyncio
asyncio.BaseEventLoop.__del__ = lambda self: None
import os
import json
import traceback
import numpy as np
import cv2
import torch
from PIL import Image, ImageEnhance, ImageFilter, ImageDraw, ImageFont
import gradio as gr
import onnxruntime as ort
from transformers import pipeline, AutoModelForImageSegmentation
from spandrel import ModelLoader
import easyocr
# 引入 ZeroGPU 库(如环境无 spaces 则静默回退)
try:
import spaces
except ImportError:
class spaces:
@staticmethod
def GPU(func):
return func
# --- 全局变量与模型缓存 ---
models = {
"birefnet": None,
"ocr_reader": None,
"object_detector": None,
"anime_session": None,
"upscaler": None
}
# 1. 物体识别
@spaces.GPU
def identify_objects(input_img):
global models
if input_img is None:
return None, json.dumps({"error": "请上传图片"}, ensure_ascii=False)
try:
device_id = 0 if torch.cuda.is_available() else -1
if "object_detector" not in models:
models["object_detector"] = pipeline(
"object-detection",
model="hustvl/yolos-tiny",
device=device_id
)
img_pil = input_img.convert("RGB")
results = models["object_detector"](img_pil)
draw = ImageDraw.Draw(img_pil)
detections = []
count = 0
for res in results:
if res["score"] > 0.5:
count += 1
box = res["box"]
label = res["label"]
score = res["score"]
draw.rectangle([box["xmin"], box["ymin"], box["xmax"], box["ymax"]], outline="red", width=4)
detections.append({
"id": count,
"label": label,
"confidence": round(score, 4),
"box": {
"xmin": int(box["xmin"]),
"ymin": int(box["ymin"]),
"xmax": int(box["xmax"]),
"ymax": int(box["ymax"])
}
})
output_json = {
"status": "success",
"count": count,
"detections": detections
}
return img_pil, json.dumps(output_json, ensure_ascii=False, indent=4)
except Exception as e:
error_json = {"status": "error", "message": str(e)}
return input_img, json.dumps(error_json, ensure_ascii=False)
# 2. 抠图 (BiRefNet)
@spaces.GPU
def process_rembg(input_img):
global models
if input_img is None:
return None
device = "cuda" if torch.cuda.is_available() else "cpu"
try:
if models["birefnet"] is None:
model_id = "ZhengPeng7/BiRefNet_lite"
models["birefnet"] = AutoModelForImageSegmentation.from_pretrained(
model_id, trust_remote_code=True
)
if not hasattr(models["birefnet"], "all_tied_weights_keys"):
models["birefnet"].all_tied_weights_keys = []
models["birefnet"].to(device).eval()
img_pil = input_img.convert("RGB")
w, h = img_pil.size
img_resized = img_pil.resize((1024, 1024), Image.BILINEAR)
img_np = np.array(img_resized).astype(np.float32) / 255.0
mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
img_np = (img_np - mean) / std
img_np = img_np.transpose((2, 0, 1))
img_tensor = torch.from_numpy(img_np).unsqueeze(0).float().to(device)
with torch.no_grad():
preds = models["birefnet"](img_tensor)[-1].sigmoid().cpu()
mask = torch.nn.functional.interpolate(
preds, size=(h, w), mode='bilinear', align_corners=False
)[0, 0]
mask_np = (mask.numpy() * 255).astype(np.uint8)
mask_pil = Image.fromarray(mask_np).filter(ImageFilter.GaussianBlur(radius=0.8))
result = img_pil.copy()
result.putalpha(mask_pil)
return result
except Exception as e:
print(traceback.format_exc())
return f"BiRefNet 抠图失败: {str(e)}"
# 3. 文字识别 (OCR)
@spaces.GPU
def process_ocr(input_img):
global models
if input_img is None:
return "未上传图片", "{}"
use_gpu = torch.cuda.is_available()
try:
if models["ocr_reader"] is None:
print("正在初始化 EasyOCR...")
models["ocr_reader"] = easyocr.Reader(['ch_sim', 'en'], gpu=use_gpu)
img_np = np.array(input_img)
results = models["ocr_reader"].readtext(img_np)
full_text = ""
ocr_details = []
for (bbox, text, prob) in results:
if prob > 0.3:
full_text += f"{text}\n"
box_coords = [[int(x), int(y)] for x, y in bbox]
ocr_details.append({
"text": text,
"confidence": round(float(prob), 4),
"bbox": box_coords
})
json_output = json.dumps(ocr_details, ensure_ascii=False, indent=2)
if not full_text:
return "未识别到文字", "{}"
return full_text, json_output
except Exception as e:
return f"OCR 识别出错: {str(e)}", "{}"
# 4. 超分修复 (RealESRGAN)
@spaces.GPU
def process_upscale(input_img):
global models
if input_img is None:
return None
model_path = "RealESRGAN_x2plus.pth"
if not os.path.exists(model_path):
return "错误:缺失 RealESRGAN_x2plus.pth 权重文件,请确认已上传到根目录"
device = "cuda" if torch.cuda.is_available() else "cpu"
try:
if models["upscaler"] is None:
loader = ModelLoader()
ckpt = loader.load_from_file(model_path)
models["upscaler"] = ckpt.model
models["upscaler"].to(device).eval()
img_pil = input_img.convert("RGB")
w, h = img_pil.size
max_input = 1024
if max(w, h) > max_input:
img_pil.thumbnail((max_input, max_input), Image.LANCZOS)
img = np.array(img_pil).astype(np.float32) / 255.0
img_tensor = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0).float().to(device)
with torch.no_grad():
output = models["upscaler"](img_tensor)
output = output.squeeze(0).permute(1, 2, 0).clamp(0, 1).cpu().numpy()
output = (output * 255).astype(np.uint8)
result_pil = Image.fromarray(output)
enhancer = ImageEnhance.Sharpness(result_pil)
result_pil = enhancer.enhance(1.2)
return result_pil
except Exception as e:
print(traceback.format_exc())
return f"2x 超分失败: {str(e)}"
# 5. 动漫化 (AnimeGANv3)
@spaces.GPU
def process_anime(input_img):
global models
if input_img is None:
return None
model_path = "AnimeGANv3_large_Ghibli_c1_e299.onnx"
if not os.path.exists(model_path):
return f"错误:未找到模型文件 {model_path},请确认已上传到根目录"
try:
if models["anime_session"] is None:
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if torch.cuda.is_available() else ['CPUExecutionProvider']
models["anime_session"] = ort.InferenceSession(model_path, providers=providers)
session = models["anime_session"]
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name
img_pil = input_img.convert("RGB")
w, h = img_pil.size
process_size = 1024
scale = process_size / max(w, h) if max(w, h) > process_size else 1.0
target_w, target_h = int((w * scale) // 32) * 32, int((h * scale) // 32) * 32
img_resized = img_pil.resize((target_w, target_h), Image.LANCZOS)
img_np = np.array(img_resized).astype(np.float32)
img_np = (img_np / 127.5) - 1.0
img_np = np.expand_dims(img_np, axis=0)
output = session.run([output_name], {input_name: img_np})[0]
output = np.squeeze(output)
output = (output + 1.0) * 127.5
output = np.clip(output, 0, 255).astype(np.uint8)
result_pil = Image.fromarray(output)
result_pil = ImageEnhance.Sharpness(result_pil).enhance(1.5)
result_pil = ImageEnhance.Contrast(result_pil).enhance(1.1)
return result_pil.resize((w, h), Image.LANCZOS)
except Exception as e:
print(traceback.format_exc())
return f"动漫化失败: {str(e)}"
# --- Gradio UI 设计 ---
with gr.Blocks() as demo:
gr.Markdown("# 🚀 ExtractIt AI 多功能平台")
with gr.Tabs():
with gr.TabItem("物体识别 (Identify Objects)"):
with gr.Row():
input_i = gr.Image(type="pil", label="上传图片")
output_t = gr.Textbox(label="识别详情", lines=10, interactive=False)
output_i = gr.Image(type="pil", label="可视化结果")
btn_i = gr.Button("开始识别", variant="primary")
btn_i.click(fn=identify_objects, inputs=input_i, outputs=[output_i, output_t])
with gr.TabItem("🖼️ 抠图 (RMBG)"):
with gr.Row():
in1 = gr.Image(type="pil", label="上传图片")
out1 = gr.Image(label="去背景结果")
btn1 = gr.Button("开始处理", variant="primary")
btn1.click(process_rembg, inputs=in1, outputs=out1)
with gr.TabItem("🎨 动漫化"):
with gr.Row():
in2 = gr.Image(type="pil", label="输入照片")
out2 = gr.Image(label="二次元化结果")
btn2 = gr.Button("风格转换", variant="primary")
btn2.click(process_anime, inputs=in2, outputs=out2)
with gr.TabItem("🔍 4x 高清修复"):
with gr.Row():
in3 = gr.Image(type="pil", label="低清图")
out3 = gr.Image(label="超分结果")
btn3 = gr.Button("开始增强", variant="primary")
btn3.click(process_upscale, inputs=in3, outputs=out3)
with gr.TabItem("📝 文字识别 (OCR)"):
with gr.Row():
with gr.Column():
input_img = gr.Image(type="pil", label="上传图片")
btn_ocr = gr.Button("开始识别文字", variant="primary")
with gr.Column():
output_text = gr.Textbox(label="识别出的文字", lines=8)
output_json = gr.Code(label="文字区块坐标 (JSON)", language="json")
btn_ocr.click(fn=process_ocr, inputs=input_img, outputs=[output_text, output_json])
# 启动队列与启动入口
demo.queue().launch(theme=gr.themes.Default())