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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -87
app.py CHANGED
@@ -1,108 +1,109 @@
1
- import gradio as gr
2
- import cv2
3
- import numpy as np
4
- from PIL import Image
5
  import subprocess
6
  import sys
7
 
8
- def install_dependencies():
9
  try:
10
- # Install OpenCV
11
- subprocess.check_call([sys.executable, "-m", "pip", "install", "opencv-python"])
12
- # Install facemorpher
13
- subprocess.check_call([sys.executable, "-m", "pip", "install", "facemorpher"])
14
- # Install Pillow if needed
15
- subprocess.check_call([sys.executable, "-m", "pip", "install", "Pillow"])
16
- print("All dependencies installed successfully!")
 
 
 
 
 
 
 
 
 
17
  except subprocess.CalledProcessError as e:
18
- print(f"Error occurred while installing dependencies: {e}")
19
 
20
- # Call the function to install dependencies
21
- install_dependencies()
 
 
 
 
22
 
23
- # Now you can import facemorpher and proceed with your code
24
- from facemorpher import FaceMorpher
 
 
 
 
 
25
 
26
- # Your face morphing code goes here...
 
 
27
 
 
 
28
 
 
 
29
 
30
- # Load images function
31
- def load_image(path):
32
- return cv2.imread(path)
 
 
 
 
 
 
 
33
 
34
- # Generate lipsync frame based on interpolation slider
35
- def generate_lipsync_frame(mm_image, target_image, morph_strength):
36
- # Convert BGR to RGB (since OpenCV uses BGR, PIL uses RGB)
37
- mm_image_rgb = cv2.cvtColor(mm_image, cv2.COLOR_BGR2RGB)
38
- target_image_rgb = cv2.cvtColor(target_image, cv2.COLOR_BGR2RGB)
39
 
40
- # Apply face morphing using facemorpher
41
- # Morph between MM image and the target phoneme image based on the morph strength
42
- frames = facemorpher.morph_images(mm_image_rgb, target_image_rgb, num_frames=20)
43
 
44
- # Get the frame corresponding to morph_strength in the range [0.0 to 1.0]
45
- frame_index = int(morph_strength * (len(frames) - 1))
46
- return Image.fromarray(frames[frame_index])
47
 
48
- # Function for the full lipsync process using sliders for each phoneme
49
- def lipsync_interface(mm_image, aa_image, ee_image, oo_image, ww_image, na_image, slider_aa, slider_oo, slider_ee, slider_ww, slider_na):
50
- # List of phoneme images
51
- phoneme_images = {
52
- "AA": aa_image,
53
- "EE": ee_image,
54
- "OO": oo_image,
55
- "WW": ww_image,
56
- "NA": na_image
57
- }
58
-
59
- # Load MM (Neutral) image
60
- mm_image = load_image(mm_image.name) # Load the image file
61
 
62
- # Start with MM image and interpolate to other phonemes
63
- result_image = mm_image
64
 
65
- if slider_aa > 0.0:
66
- aa_image = load_image(phoneme_images["AA"].name)
67
- result_image = generate_lipsync_frame(mm_image, aa_image, slider_aa)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- if slider_oo > 0.0:
70
- oo_image = load_image(phoneme_images["OO"].name)
71
- result_image = generate_lipsync_frame(result_image, oo_image, slider_oo)
72
-
73
- if slider_ee > 0.0:
74
- ee_image = load_image(phoneme_images["EE"].name)
75
- result_image = generate_lipsync_frame(result_image, ee_image, slider_ee)
76
-
77
- if slider_ww > 0.0:
78
- ww_image = load_image(phoneme_images["WW"].name)
79
- result_image = generate_lipsync_frame(result_image, ww_image, slider_ww)
80
-
81
- if slider_na > 0.0:
82
- na_image = load_image(phoneme_images["NA"].name)
83
- result_image = generate_lipsync_frame(result_image, na_image, slider_na)
84
 
85
- return result_image
 
86
 
87
- # Gradio interface setup
88
- iface = gr.Interface(
89
- fn=lipsync_interface,
90
- inputs=[
91
- gr.inputs.Image(label="MM Image (Neutral)", type="file"),
92
- gr.inputs.Image(label="AA Image", type="file"),
93
- gr.inputs.Image(label="EE Image", type="file"),
94
- gr.inputs.Image(label="OO Image", type="file"),
95
- gr.inputs.Image(label="WW Image", type="file"),
96
- gr.inputs.Image(label="NA Image", type="file"),
97
-
98
- gr.inputs.Slider(minimum=0.0, maximum=1.0, step=0.05, label="Morph Strength AA"),
99
- gr.inputs.Slider(minimum=0.0, maximum=1.0, step=0.05, label="Morph Strength OO"),
100
- gr.inputs.Slider(minimum=0.0, maximum=1.0, step=0.05, label="Morph Strength EE"),
101
- gr.inputs.Slider(minimum=0.0, maximum=1.0, step=0.05, label="Morph Strength WW"),
102
- gr.inputs.Slider(minimum=0.0, maximum=1.0, step=0.05, label="Morph Strength NA"),
103
- ],
104
- outputs=gr.outputs.Image(label="Interpolated Lip-sync Frame"),
105
- live=True
106
- )
107
 
108
- iface.launch()
 
 
 
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()