nazib61 commited on
Commit
4887e95
·
verified ·
1 Parent(s): 770641d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -49
app.py CHANGED
@@ -1,57 +1,28 @@
1
  import gradio as gr
2
  import subprocess
3
  import os
 
4
 
5
- # --- Force Install Node Modules ---
6
  def initialize_env():
7
- print("Checking Node.js environment...")
8
-
9
- # বর্তমান ডিরেক্টরি চেক করা
10
- current_dir = os.getcwd()
11
- print(f"Current Directory: {current_dir}")
12
-
13
- # package.json আছে কিনা চেক করা
14
- if not os.path.exists("package.json"):
15
- print("❌ ERROR: package.json not found! Creating one...")
16
- with open("package.json", "w") as f:
17
- f.write('{"dependencies": {"puppeteer-core": "^21.0.0"}}')
18
-
19
- # node_modules না থাকলে install করা
20
  if not os.path.exists("node_modules"):
21
- print("Installing node_modules... this may take a minute.")
22
- try:
23
- # --no-audit এবং --no-fund দিলে ইন্সটলেশন দ্রুত হয়
24
- subprocess.run(["npm", "install", "--no-audit", "--no-fund"], check=True)
25
- print("✅ node_modules installed successfully.")
26
- except Exception as e:
27
- print(f"❌ NPM Install Failed: {e}")
28
 
29
- # অ্যাপ শুরু হওয়ার আগেই এনভায়রনমেন্ট রেডি করা
30
  initialize_env()
31
 
32
- def search_pinterest(query):
33
  if not query:
34
  return None, "⚠️ Please enter a keyword."
35
 
 
36
  search_query = query if "video" in query.lower() else f"{query} video"
37
-
38
  try:
39
- # Scraper চালানো
40
  result = subprocess.run(
41
  ["node", "scraper.js", search_query],
42
- capture_output=True,
43
- text=True,
44
- timeout=90
45
  )
46
 
47
  stdout = result.stdout.strip()
48
- stderr = result.stderr.strip()
49
-
50
- # ডিবাগিং এর জন্য লগ দেখা
51
- if stderr:
52
- print(f"Node Debug: {stderr}")
53
-
54
- # URL খুঁজে বের করা
55
  lines = stdout.split('\n')
56
  video_url = None
57
  for line in lines:
@@ -59,27 +30,68 @@ def search_pinterest(query):
59
  video_url = line.strip()
60
  break
61
 
62
- if video_url:
63
- return video_url, f" Found video for: {query}"
64
- else:
65
- return None, f"❌ No video URL found. Logs: {stderr[:100]}"
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  except Exception as e:
68
  return None, f"❌ System Error: {str(e)}"
69
 
70
- # Gradio Interface
71
- with gr.Blocks() as demo:
72
- gr.Markdown("# 📌 Pinterest Video Downloader")
73
 
74
  with gr.Row():
75
- inp = gr.Textbox(label="Query", placeholder="e.g. Funny cat")
76
- btn = gr.Button("Search", variant="primary")
77
-
78
- out_video = gr.Video(label="Result")
79
- out_log = gr.Textbox(label="Status")
 
 
 
 
 
80
 
81
- btn.click(search_pinterest, inputs=inp, outputs=[out_video, out_log])
82
- inp.submit(search_pinterest, inputs=inp, outputs=[out_video, out_log])
 
 
 
83
 
84
  if __name__ == "__main__":
85
  demo.launch()
 
1
  import gradio as gr
2
  import subprocess
3
  import os
4
+ import uuid
5
 
 
6
  def initialize_env():
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  if not os.path.exists("node_modules"):
8
+ print("Installing node_modules...")
9
+ subprocess.run(["npm", "install"], check=True)
 
 
 
 
 
10
 
 
11
  initialize_env()
12
 
13
+ def process_video(query, start_time, end_time):
14
  if not query:
15
  return None, "⚠️ Please enter a keyword."
16
 
17
+ # 1. Scrape the URL using Node.js
18
  search_query = query if "video" in query.lower() else f"{query} video"
 
19
  try:
 
20
  result = subprocess.run(
21
  ["node", "scraper.js", search_query],
22
+ capture_output=True, text=True, timeout=90
 
 
23
  )
24
 
25
  stdout = result.stdout.strip()
 
 
 
 
 
 
 
26
  lines = stdout.split('\n')
27
  video_url = None
28
  for line in lines:
 
30
  video_url = line.strip()
31
  break
32
 
33
+ if not video_url:
34
+ return None, f" No video found. Logs: {result.stderr[:100]}"
 
 
35
 
36
+ # 2. Trim the video using FFmpeg
37
+ # We create a unique filename for the trimmed video
38
+ output_filename = f"trimmed_{uuid.uuid4().hex[:8]}.mp4"
39
+
40
+ print(f"Trimming video: {start_time}s to {end_time}s")
41
+
42
+ # FFmpeg Command Explanation:
43
+ # -ss: Start time
44
+ # -to: End time
45
+ # -i: Input URL (FFmpeg can stream directly from the URL)
46
+ # -c:v libx264: Re-encode to ensure precision for decimals like 3.79
47
+
48
+ ffmpeg_cmd = [
49
+ "ffmpeg",
50
+ "-ss", str(start_time),
51
+ "-to", str(end_time),
52
+ "-i", video_url,
53
+ "-c:v", "libx264",
54
+ "-c:a", "aac",
55
+ "-strict", "experimental",
56
+ "-y", # Overwrite if exists
57
+ output_filename
58
+ ]
59
+
60
+ # If end_time is 0, we assume the user wants the whole video from the start_time
61
+ if end_time <= 0:
62
+ ffmpeg_cmd.pop(3) # Remove "-to"
63
+ ffmpeg_cmd.pop(3) # Remove the end_time value
64
+
65
+ subprocess.run(ffmpeg_cmd, check=True)
66
+
67
+ return output_filename, f"✅ Success! Trimmed from {start_time}s to {end_time}s"
68
+
69
+ except subprocess.CalledProcessError as e:
70
+ return None, f"❌ FFmpeg Error: Maybe the start/end time is longer than the video?"
71
  except Exception as e:
72
  return None, f"❌ System Error: {str(e)}"
73
 
74
+ # --- Gradio UI ---
75
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
76
+ gr.Markdown("# 📌 Pinterest Video Search & Trim")
77
 
78
  with gr.Row():
79
+ with gr.Column():
80
+ query_input = gr.Textbox(label="Search Query", placeholder="e.g. Minecraft Gameplay")
81
+ with gr.Row():
82
+ start_input = gr.Number(label="Start Second (e.g. 1.5)", value=0)
83
+ end_input = gr.Number(label="End Second (0 = Full video)", value=0)
84
+ btn = gr.Button("🚀 Search & Trim", variant="primary")
85
+
86
+ with gr.Column():
87
+ video_output = gr.Video(label="Trimmed Result")
88
+ status_output = gr.Textbox(label="Status")
89
 
90
+ btn.click(
91
+ fn=process_video,
92
+ inputs=[query_input, start_input, end_input],
93
+ outputs=[video_output, status_output]
94
+ )
95
 
96
  if __name__ == "__main__":
97
  demo.launch()