NihalGazi commited on
Commit
3036471
·
verified ·
1 Parent(s): f0f3036

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -89
app.py CHANGED
@@ -1,109 +1,85 @@
1
- import os
2
  import subprocess
3
  import sys
4
 
 
5
  def install_requirements():
6
  try:
7
- subprocess.check_call([sys.executable, "-m", "pip", "install", "opencv-python", "numpy", "scipy", "matplotlib"])
8
- print("Successfully installed OpenCV, numpy, scipy, and matplotlib.")
9
-
10
  try:
11
  subprocess.check_call([sys.executable, "-m", "pip", "install", "facemorpher"])
12
- print("Successfully installed facemorpher.")
13
- except subprocess.CalledProcessError as e:
14
- print("Failed to install facemorpher:", e)
15
- print("Attempting fallback: manually installing stasm and docopt.")
16
- try:
17
- subprocess.check_call([sys.executable, "-m", "pip", "install", "stasm", "docopt"])
18
- print("Successfully installed stasm and docopt.")
19
- except subprocess.CalledProcessError as e:
20
- print("Fallback installation failed:", e)
21
- print("Proceeding without facemorpher.")
22
 
23
- except subprocess.CalledProcessError as e:
24
- print("Installation of core dependencies failed:", e)
25
 
26
- def create_and_run_main_py():
27
- main_code = '''
28
- import os
29
  import cv2
30
  import numpy as np
31
- import time
 
32
 
33
- # Fallback implementation for morph_faces if facemorpher is not available
34
- try:
35
- from facemorpher import morpher
36
- use_facemorpher = True
37
- except ImportError:
38
- print("facemorpher not found. Using fallback morphing.")
39
- use_facemorpher = False
40
 
41
- def morph_faces(img1_path, img2_path, alpha=0.5):
42
- img1 = cv2.imread(img1_path)
43
- img2 = cv2.imread(img2_path)
 
44
 
45
- if img1 is None or img2 is None:
46
- raise ValueError("Error reading input images.")
 
47
 
48
- img1 = cv2.resize(img1, (img2.shape[1], img2.shape[0]))
49
- return cv2.addWeighted(img1, alpha, img2, 1 - alpha, 0)
 
 
50
 
51
- def get_phoneme_image(phoneme):
52
- phoneme_dir = "phoneme_images"
53
- phoneme_map = {
54
- "AA": "aa.jpg",
55
- "EE": "ee.jpg",
56
- "OO": "oo.jpg",
57
- "MM": "mm.jpg",
58
- "WW": "ww.jpg",
59
- "NA": "na.jpg"
60
- }
 
 
 
 
 
61
 
62
- filename = phoneme_map.get(phoneme.upper())
63
- if filename is None:
64
- raise ValueError(f"Invalid phoneme: {phoneme}")
65
-
66
- path = os.path.join(phoneme_dir, filename)
67
- if not os.path.exists(path):
68
- raise FileNotFoundError(f"Image for phoneme '{phoneme}' not found at {path}")
69
-
70
- return path
71
 
72
- def interpolate_faces(phoneme1, phoneme2, steps=10):
73
- img1_path = get_phoneme_image(phoneme1)
74
- img2_path = get_phoneme_image(phoneme2)
75
-
76
- output_dir = "morph_output"
77
- os.makedirs(output_dir, exist_ok=True)
78
-
79
- for i in range(steps + 1):
80
- alpha = i / steps
81
- if use_facemorpher:
82
- morpher.morpher(
83
- img1_path, img2_path,
84
- plot=True,
85
- alpha=alpha,
86
- out_folder=output_dir,
87
- out_frames=1,
88
- gif=False
89
- )
90
- else:
91
- result = morph_faces(img1_path, img2_path, alpha)
92
- frame_path = os.path.join(output_dir, f"frame_{i:02d}.jpg")
93
- cv2.imwrite(frame_path, result)
94
- print(f"Saved frame {i} at alpha {alpha:.2f} to {frame_path}")
95
- time.sleep(0.1)
96
 
97
- if __name__ == "__main__":
98
- interpolate_faces("AA", "EE", steps=10)
99
- '''
 
 
 
 
 
 
100
 
101
- with open("main.py", "w") as f:
102
- f.write(main_code)
103
-
104
- print("main.py created. Running the script...")
105
- os.system(f"{sys.executable} main.py")
106
-
107
- if __name__ == "__main__":
108
- install_requirements()
109
- create_and_run_main_py()
 
 
1
  import subprocess
2
  import sys
3
 
4
+ # --- Installation Block ---
5
  def install_requirements():
6
  try:
7
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "opencv-python", "numpy", "scipy", "matplotlib", "gradio", "Pillow"])
 
 
8
  try:
9
  subprocess.check_call([sys.executable, "-m", "pip", "install", "facemorpher"])
10
+ except subprocess.CalledProcessError:
11
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "stasm", "docopt"])
12
+ print("facemorpher not available; fallback dependencies installed.")
13
+ except Exception as e:
14
+ print(f"Installation failed: {e}")
 
 
 
 
 
15
 
16
+ install_requirements()
 
17
 
18
+ # --- Imports ---
19
+ import gradio as gr
 
20
  import cv2
21
  import numpy as np
22
+ from PIL import Image
23
+ import facemorpher
24
 
25
+ # --- Image Loader ---
26
+ def load_image(file):
27
+ img = cv2.imread(file.name)
28
+ if img is None:
29
+ raise ValueError(f"Failed to load image: {file.name}")
30
+ return img
 
31
 
32
+ # --- Morphing Function ---
33
+ def generate_lipsync_frame(img1, img2, morph_strength):
34
+ img1_rgb = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
35
+ img2_rgb = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
36
 
37
+ frames = facemorpher.morpher.morph_images([img1_rgb, img2_rgb], num_frames=20)
38
+ index = int(morph_strength * (len(frames) - 1))
39
+ return Image.fromarray(frames[index])
40
 
41
+ # --- Lipsync Processing ---
42
+ def lipsync_interface(mm, aa, ee, oo, ww, na, s_aa, s_oo, s_ee, s_ww, s_na):
43
+ mm_img = load_image(mm)
44
+ result = mm_img.copy()
45
 
46
+ if s_aa > 0.0:
47
+ aa_img = load_image(aa)
48
+ result = generate_lipsync_frame(result, aa_img, s_aa)
49
+ if s_oo > 0.0:
50
+ oo_img = load_image(oo)
51
+ result = generate_lipsync_frame(result, oo_img, s_oo)
52
+ if s_ee > 0.0:
53
+ ee_img = load_image(ee)
54
+ result = generate_lipsync_frame(result, ee_img, s_ee)
55
+ if s_ww > 0.0:
56
+ ww_img = load_image(ww)
57
+ result = generate_lipsync_frame(result, ww_img, s_ww)
58
+ if s_na > 0.0:
59
+ na_img = load_image(na)
60
+ result = generate_lipsync_frame(result, na_img, s_na)
61
 
62
+ return result
 
 
 
 
 
 
 
 
63
 
64
+ # --- Gradio Interface ---
65
+ iface = gr.Interface(
66
+ fn=lipsync_interface,
67
+ inputs=[
68
+ gr.Image(label="MM Image (Neutral)", type="file"),
69
+ gr.Image(label="AA Image", type="file"),
70
+ gr.Image(label="EE Image", type="file"),
71
+ gr.Image(label="OO Image", type="file"),
72
+ gr.Image(label="WW Image", type="file"),
73
+ gr.Image(label="NA Image", type="file"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
+ gr.Slider(minimum=0.0, maximum=1.0, step=0.05, label="Morph Strength AA"),
76
+ gr.Slider(minimum=0.0, maximum=1.0, step=0.05, label="Morph Strength OO"),
77
+ gr.Slider(minimum=0.0, maximum=1.0, step=0.05, label="Morph Strength EE"),
78
+ gr.Slider(minimum=0.0, maximum=1.0, step=0.05, label="Morph Strength WW"),
79
+ gr.Slider(minimum=0.0, maximum=1.0, step=0.05, label="Morph Strength NA"),
80
+ ],
81
+ outputs=gr.Image(label="Interpolated Lip-sync Frame"),
82
+ live=True
83
+ )
84
 
85
+ iface.launch()