44step44 commited on
Commit
8d85246
·
verified ·
1 Parent(s): abcdeb1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -34
app.py CHANGED
@@ -1,46 +1,74 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
- from PIL import Image
4
- import io
5
- import uuid
 
 
 
 
6
 
7
- # Это API само делает и замену, и улучшение качества (как Remaker)
8
- client = InferenceClient("ghoskno/Face_Substitution")
 
 
 
 
9
 
10
- def process_faces(source_img, target_img):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  if source_img is None or target_img is None:
12
  return None
13
 
14
- try:
15
- # Отправляем на сервер, где всё уже настроено
16
- raw_output = client.face_swapping(target_img, source_img)
17
-
18
- # Делаем из этого реальное фото
19
- image = Image.open(io.BytesIO(raw_output))
 
 
 
 
20
 
21
- # Сохраняем файл на диск, чтобы он был доступен для скачивания
22
- file_name = f"result_{uuid.uuid4().hex}.jpg"
23
- image.save(file_name)
 
24
 
25
- return file_name
26
- except Exception as e:
27
- print(f"Ошибка: {e}")
28
- return None
29
-
30
- # Твой привычный интерфейс, который работал
31
- with gr.Blocks() as demo:
32
- gr.Markdown("# 🎭 Мой Face Swap HD")
33
 
34
- with gr.Row():
35
- with gr.Column():
36
- source = gr.Image(type="filepath", label="Твое лицо")
37
- target = gr.Image(type="filepath", label="Куда вставляем")
38
- btn = gr.Button("🚀 ЗАМЕНИТЬ И УЛУЧШИТЬ", variant="primary")
39
-
40
- with gr.Column():
41
- # filepath — это ключ к тому, чтобы файл можно было скачать
42
- output = gr.Image(label="Результат", type="filepath")
43
 
44
- btn.click(fn=process_faces, inputs=[source, target], outputs=output)
 
 
 
 
 
45
 
46
  demo.launch()
 
1
  import gradio as gr
2
+ import cv2
3
+ import insightface
4
+ from insightface.app import FaceAnalysis
5
+ import PIL.Image
6
+ import numpy as np
7
+ import os
8
+ import requests
9
+ from gfpgan import GFPGANer
10
 
11
+ # Функция для скачивания моделей
12
+ def download_file(url, filename):
13
+ if not os.path.exists(filename):
14
+ response = requests.get(url)
15
+ with open(filename, "wb") as f:
16
+ f.write(response.content)
17
 
18
+ # 1. Инициализация поиска лиц (Твой код)
19
+ try:
20
+ app = FaceAnalysis(name='buffalore_l', providers=['CPUExecutionProvider'])
21
+ app.prepare(ctx_id=0, det_size=(640, 640))
22
+ except:
23
+ app = FaceAnalysis(providers=['CPUExecutionProvider'])
24
+ app.prepare(ctx_id=0, det_size=(640, 640))
25
+
26
+ # 2. Модель замены (Твой код)
27
+ model_url = "https://huggingface.co/ezioruan/inswapper_128.onnx/resolve/main/inswapper_128.onnx"
28
+ model_path = "inswapper_128.onnx"
29
+ download_file(model_url, model_path)
30
+ swapper = insightface.model_zoo.get_model(model_path, download=False)
31
+
32
+ # 3. ДОБАВЛЕНО: Модель улучшения качества (GFPGAN)
33
+ # Она скачается автоматически при первом запуске
34
+ arch = 'clean'
35
+ channel_multiplier = 2
36
+ model_url_gfpgan = 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth'
37
+ restorer = GFPGANer(model_path=model_url_gfpgan, upscale=1, arch=arch, channel_multiplier=channel_multiplier, bg_upsampler=None)
38
+
39
+ def swap(source_img, target_img):
40
  if source_img is None or target_img is None:
41
  return None
42
 
43
+ # Конвертируем для работы (Твой код)
44
+ source_arr = np.array(source_img)
45
+ target_arr = np.array(target_img)
46
+ target_bgr = cv2.cvtColor(target_arr, cv2.COLOR_RGB2BGR)
47
+
48
+ source_faces = app.get(source_arr)
49
+ target_faces = app.get(target_bgr)
50
+
51
+ if not source_faces:
52
+ return target_img
53
 
54
+ # Процесс замены (Твой код)
55
+ result_bgr = target_bgr.copy()
56
+ for face in target_faces:
57
+ result_bgr = swapper.get(result_bgr, face, source_faces[0], paste_back=True)
58
 
59
+ # --- МАГИЯ УЛУЧШЕНИЯ (Новое) ---
60
+ # Прогоняем результат замены через реставратор лиц
61
+ _, _, enhanced_img = restorer.enhance(result_bgr, has_aligned=False, only_center_face=False, paste_back=True)
 
 
 
 
 
62
 
63
+ # Возвращаем результат в формате PIL (Твой код)
64
+ result_rgb = cv2.cvtColor(enhanced_img, cv2.COLOR_BGR2RGB)
65
+ return PIL.Image.fromarray(result_rgb)
 
 
 
 
 
 
66
 
67
+ demo = gr.Interface(
68
+ fn=swap,
69
+ inputs=[gr.Image(type="pil", label="Лицо-донор"), gr.Image(type="pil", label="Целевое фото")],
70
+ outputs=gr.Image(label="Результат в HD"),
71
+ title="🎭 Мой Face Swap + HD Улучшение"
72
+ )
73
 
74
  demo.launch()