fix(photo-ai): build weights in an isolated stage and stop blocking app deploys

Prefetch moved to a separate python:3.10-slim stage that only sees weights.py/fetch-weights.py, so editing app.py or vendor/ no longer invalidates the 360 MB weights layer. Weight catalog and download helpers extracted to photo-ai/weights.py; fetch-weights.py no longer imports app (torch). Cache mount switched to sharing=shared: a canceled build could leave the exclusive lock held and hang the next build forever; downloads now use a pid-unique tmp file, so concurrent builds cannot corrupt it. Docs recommend 'docker compose up -d --build app' for app updates instead of rebuilding photo-ai/face-id.
This commit is contained in:
dev
2026-10-23 10:09:58 +03:00
parent 7a2f8893a6
commit d0a17c5f62
8 changed files with 203 additions and 133 deletions
+16 -101
View File
@@ -10,7 +10,6 @@ import shutil
import sys
import threading
import time
import urllib.request
from collections import OrderedDict
from contextlib import contextmanager
@@ -23,6 +22,9 @@ from fastapi import FastAPI, File, Form, Request, UploadFile
from fastapi.responses import JSONResponse, Response
from realesrgan import RealESRGANer
from weights import (FACE_WEIGHTS as FACE_REGISTRY, FACEXLIB_WEIGHTS, MODEL_WEIGHTS, WeightError,
download_weight, file_ok, link_or_copy)
VENDOR_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vendor')
if os.path.isdir(VENDOR_DIR) and VENDOR_DIR not in sys.path:
sys.path.append(VENDOR_DIR)
@@ -113,76 +115,16 @@ def srvgg(num_conv):
upscale=4, act_type='prelu')
MODEL_REGISTRY = OrderedDict([
('x2plus', {
'scale': 2,
'arch': rrdb_x2,
'file': 'RealESRGAN_x2plus.pth',
'url': 'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth',
'min_bytes': 60_000_000,
'alias': True,
'denoise': False,
'title': 'Универсальный апскейл x2, дефолт',
}),
('general-x4v3', {
'scale': 4,
'arch': srvgg(32),
'file': 'realesr-general-x4v3.pth',
'url': 'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth',
'min_bytes': 2_000_000,
'alias': False,
'denoise': True,
'title': 'Быстрый апскейл x4 с денойзом',
'dni': {
'file': 'realesr-general-wdn-x4v3.pth',
'url': 'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth',
'min_bytes': 2_000_000,
'weight': 0.5,
},
}),
('animevideo-v3', {
'scale': 4,
'arch': srvgg(16),
'file': 'realesr-animevideov3.pth',
'url': 'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth',
'min_bytes': 1_000_000,
'alias': False,
'denoise': False,
'title': 'Быстрый апскейл x4 для скриншотов и иллюстраций',
}),
])
ARCH_BUILDERS = {
'rrdb_x2': rrdb_x2,
'srvgg:16': srvgg(16),
'srvgg:32': srvgg(32),
}
FACE_REGISTRY = OrderedDict([
('gfpgan', {
'module': 'gfpgan',
'file': 'GFPGANv1.4.pth',
'url': 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth',
'min_bytes': 300_000_000,
'arch': 'clean',
'channel_multiplier': 2,
'strength': False,
'title': 'GFPGAN v1.4, восстановление лиц, дефолт',
}),
('codeformer', {
'module': 'codeformer',
'file': 'codeformer.pth',
'url': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth',
'min_bytes': 300_000_000,
'strength': True,
'title': 'CodeFormer, восстановление лиц с регулируемой силой',
}),
])
FACEXLIB_WEIGHTS = OrderedDict([
('detection_Resnet50_Final.pth', {
'url': 'https://github.com/xinntao/facexlib/releases/download/v0.1.0/detection_Resnet50_Final.pth',
'min_bytes': 90_000_000,
}),
('parsing_parsenet.pth', {
'url': 'https://github.com/xinntao/facexlib/releases/download/v0.2.2/parsing_parsenet.pth',
'min_bytes': 70_000_000,
}),
])
MODEL_REGISTRY = OrderedDict(
(name, dict(spec, arch=ARCH_BUILDERS[spec['arch']]))
for name, spec in MODEL_WEIGHTS.items()
)
def cuda_ready():
@@ -286,36 +228,6 @@ def tile_ladder(base):
return ladder or [base]
def file_ok(path, min_bytes):
return os.path.isfile(path) and os.path.getsize(path) >= min_bytes
def link_or_copy(src, dst):
os.makedirs(os.path.dirname(dst), exist_ok=True)
try:
os.link(src, dst)
except OSError:
shutil.copyfile(src, dst)
def download_weight(url, target, min_bytes):
os.makedirs(os.path.dirname(target), exist_ok=True)
tmp = target + '.tmp'
log.info('качаю веса %s -> %s', url, target)
try:
urllib.request.urlretrieve(url, tmp)
except Exception as err:
if os.path.exists(tmp):
os.unlink(tmp)
raise EnhanceError('не удалось скачать веса %s: %s' % (os.path.basename(target), err), 500) from err
size = os.path.getsize(tmp) if os.path.isfile(tmp) else 0
if size < min_bytes:
os.unlink(tmp)
raise EnhanceError('веса %s повреждены: %d байт, минимум %d'
% (os.path.basename(target), size, min_bytes), 500)
os.replace(tmp, target)
def ensure_weight(name, spec, alias=''):
target = os.path.join(WEIGHTS_DIR, name)
if file_ok(target, spec['min_bytes']):
@@ -332,7 +244,10 @@ def ensure_weight(name, spec, alias=''):
link_or_copy(seed, target)
log.info('веса %s взяты из слоя образа %s', name, seed)
return target
download_weight(spec['url'], target, spec['min_bytes'])
try:
download_weight(spec['url'], target, spec['min_bytes'])
except WeightError as err:
raise EnhanceError(str(err), 500) from err
return target