Ayeeee45 commited on
Commit
e6d663c
·
verified ·
1 Parent(s): e025826

Create App.py

Browse files
Files changed (1) hide show
  1. App.py +247 -0
App.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import subprocess
4
+ import importlib
5
+ import warnings
6
+ from pathlib import Path
7
+
8
+ # Suppress warnings
9
+ warnings.filterwarnings("ignore")
10
+
11
+ # Set environment variables
12
+ os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
13
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
14
+ os.environ["PYTHONWARNINGS"] = "ignore"
15
+
16
+ # Monkey patch HfFolder before any imports
17
+ class MockHfFolder:
18
+ @staticmethod
19
+ def get_token():
20
+ return os.environ.get("HF_TOKEN", "")
21
+ @staticmethod
22
+ def save_token(token):
23
+ os.environ["HF_TOKEN"] = token
24
+
25
+ # Patch it into sys.modules BEFORE importing anything
26
+ sys.modules['huggingface_hub'] = type(sys)('huggingface_hub')
27
+ sys.modules['huggingface_hub'].HfFolder = MockHfFolder
28
+
29
+ print("Starting Advanced Live Portrait setup...")
30
+
31
+ # Change to /tmp for workspace
32
+ workspace = Path("/tmp/AdvancedLivePortrait")
33
+ workspace.mkdir(exist_ok=True)
34
+ os.chdir(workspace)
35
+
36
+ # Clone repository if not exists
37
+ if not (workspace / ".git").exists():
38
+ print("Cloning repository...")
39
+ subprocess.run(["git", "clone", "https://github.com/Ayeeee45/AdvancedLivePortrait-WebUI.git", "."],
40
+ check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
41
+ else:
42
+ print("Repository already exists, pulling updates...")
43
+ subprocess.run(["git", "pull"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
44
+
45
+ print("Installing dependencies...")
46
+
47
+ # Install base dependencies first
48
+ base_packages = [
49
+ "gradio==3.41.1",
50
+ "huggingface-hub==0.19.4",
51
+ "numpy==1.24.4",
52
+ "pillow==10.1.0",
53
+ "opencv-python-headless==4.8.1.78",
54
+ "ffmpeg-python==0.2.0",
55
+ "moviepy==1.0.3",
56
+ "tqdm==4.66.1",
57
+ ]
58
+
59
+ for package in base_packages:
60
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q", package],
61
+ check=False)
62
+
63
+ # Check for CUDA and install appropriate torch
64
+ try:
65
+ import torch
66
+ print(f"Torch already installed: {torch.__version__}")
67
+ if torch.cuda.is_available():
68
+ print(f"CUDA available: {torch.version.cuda}")
69
+ except:
70
+ print("Installing PyTorch...")
71
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q",
72
+ "torch==2.1.0", "torchvision==0.16.0", "torchaudio==2.1.0",
73
+ "--index-url", "https://download.pytorch.org/whl/cu118"],
74
+ check=False)
75
+
76
+ # Install from requirements.txt if exists
77
+ if os.path.exists("requirements.txt"):
78
+ print("Installing from requirements.txt...")
79
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q", "-r", "requirements.txt"],
80
+ check=False)
81
+
82
+ # Install additional commonly needed packages
83
+ additional_packages = [
84
+ "scipy==1.11.4",
85
+ "scikit-image==0.22.0",
86
+ "pyyaml==6.0.1",
87
+ "insightface==0.7.3",
88
+ "gfpgan==1.3.8",
89
+ "realesrgan==0.3.0",
90
+ "basicsr==1.4.2",
91
+ "facexlib==0.3.0",
92
+ "einops==0.7.0",
93
+ ]
94
+
95
+ for package in additional_packages:
96
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q", package],
97
+ check=False)
98
+
99
+ print("Setup complete!")
100
+
101
+ # Now create the interface
102
+ import gradio as gr
103
+ import cv2
104
+ import numpy as np
105
+ from PIL import Image
106
+ import tempfile
107
+ import time
108
+
109
+ def create_demo_interface():
110
+ """Create a demo interface for the Space"""
111
+
112
+ def process_demo(image, audio=None):
113
+ """Demo processing function"""
114
+ if image is None:
115
+ return None, "Please upload an image"
116
+
117
+ # Convert to numpy
118
+ img_array = np.array(image)
119
+
120
+ # Create a simple "processing" effect (just flip image for demo)
121
+ processed = cv2.flip(img_array, 1)
122
+
123
+ # Save as video placeholder
124
+ height, width = processed.shape[:2]
125
+ fps = 30
126
+ seconds = 3
127
+
128
+ # Create temp video file
129
+ temp_video = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False).name
130
+
131
+ # Create video writer
132
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
133
+ out = cv2.VideoWriter(temp_video, fourcc, fps, (width, height))
134
+
135
+ # Write frames
136
+ for i in range(fps * seconds):
137
+ # Create slight variation for each frame
138
+ frame = processed.copy()
139
+ if i % 10 == 0:
140
+ frame = cv2.flip(frame, 0)
141
+ out.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
142
+
143
+ out.release()
144
+
145
+ return temp_video, "Demo complete! For full functionality, run locally."
146
+
147
+ # Create interface
148
+ with gr.Blocks(title="Advanced Live Portrait", theme=gr.themes.Soft()) as demo:
149
+ gr.Markdown("""
150
+ # 🎬 Advanced Live Portrait WebUI
151
+
152
+ **Create animated portraits from images and audio**
153
+
154
+ *Note: This is a demo version. Full functionality requires local installation due to model size constraints.*
155
+ """)
156
+
157
+ with gr.Row():
158
+ with gr.Column(scale=1):
159
+ gr.Markdown("### 📤 Input")
160
+ image_input = gr.Image(
161
+ label="Source Face Image",
162
+ type="pil",
163
+ height=300
164
+ )
165
+ audio_input = gr.Audio(
166
+ label="Driving Audio (Optional)",
167
+ type="filepath",
168
+ visible=False # Hide for demo
169
+ )
170
+
171
+ with gr.Row():
172
+ generate_btn = gr.Button("🚀 Generate Demo", variant="primary")
173
+ clear_btn = gr.Button("🗑️ Clear")
174
+
175
+ gr.Markdown("""
176
+ ### 💡 Tips for Best Results:
177
+ - Use clear frontal face photos
178
+ - Good lighting works best
179
+ - Neutral expression recommended
180
+ """)
181
+
182
+ with gr.Column(scale=2):
183
+ gr.Markdown("### 📤 Output")
184
+ output_video = gr.Video(
185
+ label="Animated Result",
186
+ height=400
187
+ )
188
+ status = gr.Textbox(
189
+ label="Status",
190
+ value="Ready to generate demo...",
191
+ interactive=False
192
+ )
193
+
194
+ gr.Markdown("""
195
+ ### 📚 Full Installation Instructions:
196
+ ```bash
197
+ # 1. Clone repository
198
+ git clone https://github.com/Ayeeee45/AdvancedLivePortrait-WebUI.git
199
+ cd AdvancedLivePortrait-WebUI
200
+
201
+ # 2. Install dependencies
202
+ pip install -r requirements.txt
203
+
204
+ # 3. Download models (see GitHub for links)
205
+ # 4. Run the application
206
+ python webui.py
207
+ ```
208
+ """)
209
+
210
+ # Button actions
211
+ generate_btn.click(
212
+ fn=process_demo,
213
+ inputs=[image_input],
214
+ outputs=[output_video, status]
215
+ )
216
+
217
+ clear_btn.click(
218
+ fn=lambda: [None, None, "Cleared"],
219
+ outputs=[image_input, output_video, status]
220
+ )
221
+
222
+ # Example images
223
+ gr.Markdown("### 📸 Example Images")
224
+ gr.Examples(
225
+ examples=[
226
+ ["https://images.unsplash.com/photo-1494790108755-2616b786d4b9?w=300&h=300&fit=crop"],
227
+ ["https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=300&h=300&fit=crop"],
228
+ ["https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300&h=300&fit=crop"],
229
+ ],
230
+ inputs=[image_input],
231
+ outputs=[output_video, status],
232
+ fn=process_demo,
233
+ cache_examples=True
234
+ )
235
+
236
+ return demo
237
+
238
+ # Launch the interface
239
+ if __name__ == "__main__":
240
+ print("Launching Gradio interface...")
241
+ demo = create_demo_interface()
242
+ demo.launch(
243
+ server_name="0.0.0.0",
244
+ server_port=7860,
245
+ share=False,
246
+ debug=False
247
+ )