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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -30
app.py CHANGED
@@ -6,69 +6,50 @@ 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()
 
6
  import numpy as np
7
  import os
8
  import requests
 
9
 
10
+ # Функция для скачивания модели, если она не скачалась сама
11
  def download_file(url, filename):
12
  if not os.path.exists(filename):
13
  response = requests.get(url)
14
  with open(filename, "wb") as f:
15
  f.write(response.content)
16
 
17
+ # Инициализация попыткой обхода ошибки загрузки)
18
  try:
19
  app = FaceAnalysis(name='buffalore_l', providers=['CPUExecutionProvider'])
20
  app.prepare(ctx_id=0, det_size=(640, 640))
21
  except:
22
+ # Если база не качается, используем упрощенную инициализацию
23
  app = FaceAnalysis(providers=['CPUExecutionProvider'])
24
  app.prepare(ctx_id=0, det_size=(640, 640))
25
 
26
+ # Ссылка на файл модели (альтернативный источник)
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
  def swap(source_img, target_img):
33
  if source_img is None or target_img is None:
34
  return None
35
 
36
+ source_faces = app.get(np.array(source_img))
37
+ target_faces = app.get(np.array(target_img))
 
 
 
 
 
38
 
39
  if not source_faces:
40
  return target_img
41
 
42
+ result = np.array(target_img)
 
43
  for face in target_faces:
44
+ result = swapper.get(result, face, source_faces[0], paste_back=True)
45
 
46
+ return PIL.Image.fromarray(result)
 
 
 
 
 
 
47
 
48
  demo = gr.Interface(
49
  fn=swap,
50
  inputs=[gr.Image(type="pil", label="Лицо-донор"), gr.Image(type="pil", label="Целевое фото")],
51
+ outputs=gr.Image(label="Результат"),
52
+ title="🎭 Мой Face Swap"
53
  )
54
 
55
  demo.launch()