File size: 11,478 Bytes
741bed3
 
 
 
 
 
 
 
c1d21ce
741bed3
468ff2e
741bed3
 
468ff2e
 
741bed3
 
 
 
468ff2e
741bed3
 
 
468ff2e
741bed3
 
 
468ff2e
 
741bed3
 
 
 
 
 
 
 
 
 
468ff2e
741bed3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74bb865
741bed3
 
 
 
 
74bb865
741bed3
 
74bb865
741bed3
 
 
 
74bb865
741bed3
 
 
74bb865
741bed3
 
 
 
74bb865
c1d21ce
741bed3
 
 
74bb865
c1d21ce
741bed3
 
 
 
468ff2e
741bed3
 
 
 
 
 
 
 
 
 
 
 
 
74bb865
468ff2e
741bed3
 
 
 
 
16ae63f
c1d21ce
741bed3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1d21ce
741bed3
 
 
 
 
 
 
 
 
 
 
 
 
 
c1d21ce
741bed3
c1d21ce
741bed3
 
 
 
c1d21ce
741bed3
 
c1d21ce
741bed3
 
c1d21ce
741bed3
 
 
 
c1d21ce
741bed3
 
c1d21ce
741bed3
 
 
 
 
 
c1d21ce
741bed3
 
 
 
 
 
 
 
c1d21ce
741bed3
 
 
c1d21ce
741bed3
 
 
 
c1d21ce
741bed3
 
 
 
 
c1d21ce
741bed3
 
 
 
 
c1d21ce
741bed3
c1d21ce
741bed3
 
 
 
 
 
c1d21ce
741bed3
 
c1d21ce
741bed3
 
 
 
 
 
c1d21ce
741bed3
 
c1d21ce
741bed3
 
 
 
 
 
 
 
 
 
 
c1d21ce
741bed3
 
c1d21ce
741bed3
 
 
 
 
 
 
 
c1d21ce
741bed3
 
 
 
c1d21ce
741bed3
 
c1d21ce
741bed3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1d21ce
741bed3
c1d21ce
741bed3
 
c1d21ce
741bed3
 
 
 
 
 
 
c1d21ce
741bed3
 
 
 
 
 
c1d21ce
741bed3
 
 
 
 
 
 
 
 
 
 
c1d21ce
741bed3
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""
Physics Chapter Video Generator
Creates educational videos by combining title cards with relevant content.
"""

import re, shutil, subprocess, textwrap, os, tempfile
from pathlib import Path
from typing import List, Optional
import gradio as gr
import random

print("CWD:", os.getcwd())
print("cookies.txt exists:", os.path.exists("./cookies/cookies.txt"))


# --- Oxylabs Proxy Configuration ---
PROXY_USERNAME = "ujwal_CmiMZ"
PROXY_PASSWORD = "xJv4DChht5P6y+u"
PROXY_COUNTRY = "US"

# List of proxy endpoints (Oxylabs DC Proxies)
PROXY_PORTS = [8001, 8002, 8003, 8004, 8005]
PROXY_HOST = "dc.oxylabs.io"

def get_random_proxy():
    port = random.choice(PROXY_PORTS)
    return f"http://user-{PROXY_USERNAME}-country-{PROXY_COUNTRY}:{PROXY_PASSWORD}@{PROXY_HOST}:{port}"


# ---------------- CONFIG ----------------
TITLE_DUR         = 3                               # seconds
SIZE              = "1280x720"                      # resolution for cards
FPS               = 30
CRF               = 28                              # Higher CRF for smaller files in HF Spaces
PRESET            = "ultrafast"                     # Fastest encoding for HF Spaces
YT_MAX_RESULTS    = 2                               # Reduced for faster processing
MAX_VIDEO_LENGTH  = 30                              # Max seconds per video clip
MAX_TOPICS        = 8                               # Limit topics for HF Spaces resources
# ----------------------------------------

# ---------- helpers ----------
def run_cmd(cmd: list[str], timeout: int = 120) -> bool:
    """Run command with timeout and proper error handling"""
    try:
        result = subprocess.run(
            cmd, 
            check=True, 
            timeout=timeout,
            capture_output=True,
            text=True
        )
        return True
    except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
        print(f"Command failed:\n{' '.join(cmd)}\nError:\n{e.stderr if hasattr(e, 'stderr') else str(e)}")
        return False

def yt_urls(query: str, max_results: int) -> List[str]:
    """Get YouTube URLs for search query via proxy"""
    try:
        import requests
        from youtube_search import YoutubeSearch

        proxy_url = get_random_proxy()
        proxies = {
            "http": proxy_url,
            "https": proxy_url,
        }

        # Monkey-patch YoutubeSearch to use proxy
        original_get = requests.get

        def proxied_get(*args, **kwargs):
            kwargs["proxies"] = proxies
            kwargs["verify"] = False
            return original_get(*args, **kwargs)

        requests.get = proxied_get
        results = YoutubeSearch(query, max_results=max_results).to_dict()
        requests.get = original_get  # Restore

        return ["https://www.youtube.com" + r["url_suffix"] for r in results]
    except Exception as e:
        print(f"YouTube search failed: {e}")
        return []


def safe_filename(name: str) -> str:
    """Create safe filename"""
    return re.sub(r"[^\w\-\.]", "_", name)[:50]  # Limit length


def dl_video(url: str, out: Path) -> bool:
    """Download video with length limit using rotating proxy"""
    out.parent.mkdir(exist_ok=True)
    proxy = get_random_proxy()

    cmd = [
        "yt-dlp",
        "--match-filter", f"duration<{MAX_VIDEO_LENGTH}",
        "-f", "mp4",
        "--merge-output-format", "mp4",
        "-o", str(out),
        "--no-playlist",
        # "--no-check-certificate",
        "--proxy", proxy,
        "--cookies", "./cookies/cookies.txt",
        url,
    ]
    return run_cmd(cmd, timeout=60)


def make_card(text: str, out: Path, dur: int = TITLE_DUR) -> bool:
    """Create title card with text"""
    # Wrap text for better display
    wrapped = textwrap.wrap(text, width=25)
    safe_text = "\\n".join(w.replace("'", r"\\'") for w in wrapped)

    
    cmd = [
        "ffmpeg",
        "-loglevel", "error",
        "-f", "lavfi", "-i", f"color=c=navy:s={SIZE}:d={dur}",
        "-f", "lavfi", "-i", "anullsrc=r=44100:cl=stereo",
        "-vf", (
            f"drawtext=text='{safe_text}':fontcolor=white:fontsize=60:"
            "x=(w-text_w)/2:y=(h-text_h)/2:fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
        ),
        "-shortest", "-r", str(FPS),
        "-c:v", "libx264", "-preset", PRESET, "-crf", str(CRF),
        "-c:a", "aac", "-b:a", "96k",
        "-movflags", "+faststart",
        "-y", str(out),
    ]
    return run_cmd(cmd)

def extract_topics(text: str) -> List[str]:
    """Extract topics from input text"""
    topics = []
    for line in text.splitlines():
        line = line.strip()
        if not line or len(topics) >= MAX_TOPICS:
            continue
            
        # Match numbered lists
        if re.match(r"^\d+[\.)]\s+.+", line):
            topic = re.sub(r"^\d+[\.)]\s*", "", line)
            topics.append(topic)
        # Match markdown headers
        elif re.match(r"^#+\s+.+", line):
            topic = re.sub(r"^#+\s*", "", line)
            topics.append(topic)
        # Match all caps titles
        elif line.isupper() and 3 <= len(line) <= 50:
            topics.append(line.title())
        # Match regular lines as topics
        elif len(line) > 3 and not line.startswith(('http', 'www')):
            topics.append(line)
    
    return topics[:MAX_TOPICS]

def create_physics_video(chapter_text: str, progress=gr.Progress()) -> Optional[str]:
    """Generate educational physics video from chapter topics"""
    if not chapter_text.strip():
        return None
        
    progress(0, desc="Extracting topics...")
    topics = extract_topics(chapter_text)
    
    if not topics:
        return None
    
    # Create temporary directory
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        concat_paths: List[Path] = []
        
        total_steps = len(topics) * 2 + 3  # topics * (card + video) + opening + closing + concat
        current_step = 0
        
        # Opening card
        progress(current_step/total_steps, desc="Creating opening card...")
        opening = temp_path / "00_opening.mp4"
        if make_card("Physics Chapter Overview", opening):
            concat_paths.append(opening)
        current_step += 1
        
        # Process each topic
        for idx, topic in enumerate(topics, 1):
            # Create title card
            progress(current_step/total_steps, desc=f"Creating card for: {topic[:30]}...")
            card = temp_path / f"title_{idx:02d}.mp4"
            if make_card(topic, card):
                concat_paths.append(card)
            current_step += 1
            
            # Try to download video
            progress(current_step/total_steps, desc=f"Searching video for: {topic[:30]}...")
            video_found = False
            
            for url in yt_urls(f"{topic} physics explanation", YT_MAX_RESULTS):
                vid_id_match = re.search(r"(?:v=|be/|shorts/)([\w\-]{11})", url)
                if not vid_id_match:
                    continue
                    
                vid_path = temp_path / f"{safe_filename(vid_id_match.group(1))}.mp4"
                if dl_video(url, vid_path):
                    concat_paths.append(vid_path)
                    video_found = True
                    break
            
            if not video_found:
                # Create a placeholder card if no video found
                placeholder = temp_path / f"placeholder_{idx:02d}.mp4"
                if make_card(f"Exploring: {topic}", placeholder, dur=5):
                    concat_paths.append(placeholder)
            
            current_step += 1
        
        # Closing card
        progress(current_step/total_steps, desc="Creating closing card...")
        closing = temp_path / "zz_closing.mp4"
        if make_card("Thank you for learning!", closing):
            concat_paths.append(closing)
        current_step += 1
        
        if len(concat_paths) < 2:
            return None
        
        # Create concat file
        list_file = temp_path / "list.txt"
        list_file.write_text(
            "".join(f"file '{p.absolute()}'\n" for p in concat_paths),
            encoding="utf-8"
        )
        
        # Final output path
        output_path = "physics_chapter_video.mp4"
        
        # Concatenate videos
        progress(current_step/total_steps, desc="Creating final video...")
        cmd = [
            "ffmpeg",
            "-loglevel", "error",
            "-f", "concat", "-safe", "0", "-i", str(list_file),
            "-c:v", "libx264", "-preset", PRESET, "-crf", str(CRF),
            "-c:a", "aac", "-b:a", "128k",
            "-movflags", "+faststart",
            "-y", output_path,
        ]
        
        if run_cmd(cmd, timeout=300):
            return output_path
        
    return None

# Gradio Interface
def create_interface():
    """Setup the web interface"""
    with gr.Blocks(title="Physics Video Generator", theme=gr.themes.Soft()) as app:
        gr.Markdown("""
        # Physics Video Generator
        
        Transform your physics topics into engaging educational videos! This tool will:
        - Create professional title slides for each topic
        - Find relevant educational content
        - Combine everything into a complete video
        
        **How to use:** Enter your topics one per line, or use numbered lists, or markdown headers.
        """)
        
        with gr.Row():
            with gr.Column():
                chapter_input = gr.Textbox(
                    label="Chapter Topics",
                    placeholder="""Enter topics like:
1. Newton's Laws of Motion
2. Force and Acceleration  
3. Momentum and Impulse
4. Energy Conservation
5. Circular Motion

Or:
# Kinematics
# Dynamics
# Thermodynamics""",
                    lines=10,
                    max_lines=15
                )
                
                generate_btn = gr.Button("Create Physics Video", variant="primary", size="lg")
            
            with gr.Column():
                video_output = gr.Video(label="Your Physics Video")
                
                gr.Markdown("""
                ### Important Notes:
                - Processing typically takes 2-5 minutes
                - Videos are optimized for educational use
                - Limited to 8 topics per session  
                - Each video segment is capped at 30 seconds
                """)
        
        generate_btn.click(
            fn=create_physics_video,
            inputs=[chapter_input],
            outputs=[video_output],
            show_progress=True
        )
        
        # Examples
        gr.Examples(
            examples=[
                ["1. Newton's First Law\n2. Newton's Second Law\n3. Newton's Third Law\n4. Applications of Newton's Laws"],
                ["# Wave Motion\n# Sound Waves\n# Light Waves\n# Electromagnetic Spectrum"],
                ["THERMODYNAMICS\nHEAT TRANSFER\nENTROPY\nCARNOT CYCLE"],
                ["Quantum Mechanics Basics\nWave-Particle Duality\nHeisenberg Uncertainty Principle\nQuantum Tunneling"]
            ],
            inputs=[chapter_input],
            label="Example Topics"
        )
    
    return app

if __name__ == "__main__":
    app = create_interface()
    app.queue(max_size=3)  # Limit concurrent users for HF Spaces
    app.launch(
        share=False,
        server_name="0.0.0.0",
        server_port=7860
    )