diwash-barla commited on
Commit
79460e4
·
1 Parent(s): 47beb28

first diplpy

Browse files
Files changed (7) hide show
  1. Dockerfile +21 -0
  2. README.md +10 -9
  3. app.py +483 -0
  4. engine.py +450 -0
  5. packages.txt +1 -0
  6. requirements.txt +17 -0
  7. version.txt +1 -0
Dockerfile ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python 3.10 का बेस इमेज चुनें
2
+ FROM python:3.10-slim
3
+
4
+ # सिस्टम को अपडेट करें और ffmpeg इंस्टॉल करें
5
+ RUN apt-get update && apt-get install -y ffmpeg libgomp1 && apt-get clean && rm -rf /var/lib/apt/lists/*
6
+
7
+ # वर्किंग डायरेक्टरी सेट करें
8
+ WORKDIR /code
9
+
10
+ # requirements.txt को कॉपी करें और निर्भरताएँ इंस्टॉल करें
11
+ COPY ./requirements.txt /code/requirements.txt
12
+ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
13
+
14
+ # पूरे ऐप कोड को कॉपी करें
15
+ COPY . /code/
16
+
17
+ # 7860 पोर्ट को एक्सपोज़ करें
18
+ EXPOSE 7860
19
+
20
+ # Gunicorn सर्वर चलाएँ
21
+ CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "2", "--timeout", "120", "app:app"]
README.md CHANGED
@@ -1,14 +1,15 @@
1
  ---
2
- title: Script2video
3
- emoji: 👀
4
- colorFrom: gray
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 5.49.1
8
- app_file: app.py
9
- pinned: false
 
10
  license: apache-2.0
11
- short_description: 'Make your story alive '
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: AI Video Creator
3
+ emoji: 📽️
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 7860
8
+ ---
9
+
10
+ ---
11
  license: apache-2.0
12
+ short_description: 'Make your story alive '
13
  ---
14
 
15
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==============================================================================
2
+ # app.py - Sparkling Gyan Version 22.6 (Neon Button "Jadu" Edition)
3
+ # UI/UX "TADKA": Sabhi buttons par ek "Neon Glow" effect joda gaya hai jo
4
+ # click/touch karne par activate hota hai. Isse UI aur bhi interactive
5
+ # aur mazedaar ho gaya hai.
6
+ # ==============================================================================
7
+ import os
8
+ # <<<--- YAHAN BADLAV KIYA GAYA HAI --- >>>
9
+ from dotenv import load_dotenv
10
+
11
+ # Ye line aapke local .env file se variables load karegi
12
+ load_dotenv()
13
+ # <<<--- BADLAV YAHAN KHATM HOTA HAI --- >>>
14
+
15
+ import uuid
16
+ import threading
17
+ from flask import Flask, request, jsonify, render_template_string, send_from_directory
18
+ from werkzeug.utils import secure_filename
19
+
20
+ # engine.py se zaroori functions import karein
21
+ from engine import (
22
+ init_db, create_task, get_task, run_ai_engine_worker,
23
+ generate_script_with_ai, UPLOAD_FOLDER, OUTPUT_FOLDER
24
+ )
25
+
26
+ # ==============================================================================
27
+ # 1. HTML Templates (Modern UI/UX Overhaul with Neon Effect)
28
+ # ==============================================================================
29
+
30
+ # Base CSS styles jo sabhi pages par lagu honge
31
+ MODERN_CSS_BASE = """
32
+ <link rel="preconnect" href="https://fonts.googleapis.com">
33
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
34
+ <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
35
+ <style>
36
+ :root {
37
+ --bg-color: #1a1a2e;
38
+ --card-bg-color: rgba(22, 22, 46, 0.7);
39
+ --primary-color: #e94560;
40
+ --secondary-color: #0f3460;
41
+ --text-color: #f0f0f0;
42
+ --text-muted-color: #a0a0a0;
43
+ --border-color: rgba(233, 69, 96, 0.2);
44
+ --gradient: linear-gradient(90deg, #e94560, #a63f82);
45
+ }
46
+ body {
47
+ font-family: 'Poppins', sans-serif;
48
+ background-color: var(--bg-color);
49
+ background-image: linear-gradient(315deg, var(--bg-color) 0%, var(--secondary-color) 74%);
50
+ color: var(--text-color);
51
+ padding-top: 20px;
52
+ padding-bottom: 20px;
53
+ }
54
+ .card {
55
+ background: var(--card-bg-color);
56
+ border: 1px solid var(--border-color);
57
+ border-radius: 16px;
58
+ backdrop-filter: blur(10px);
59
+ -webkit-backdrop-filter: blur(10px);
60
+ box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
61
+ animation: fadeInUp 0.5s ease-out;
62
+ }
63
+ h1, h2, h3, h4, h5, h6 {
64
+ background: var(--gradient);
65
+ -webkit-background-clip: text;
66
+ -webkit-text-fill-color: transparent;
67
+ font-weight: 700;
68
+ }
69
+ .text-muted { color: var(--text-muted-color) !important; }
70
+ .form-control, .form-select {
71
+ background-color: rgba(0,0,0,0.2);
72
+ color: var(--text-color);
73
+ border: 1px solid var(--border-color);
74
+ border-radius: 8px;
75
+ }
76
+ .form-control:focus, .form-select:focus {
77
+ background-color: rgba(0,0,0,0.3);
78
+ color: var(--text-color);
79
+ border-color: var(--primary-color);
80
+ box-shadow: 0 0 0 0.25rem rgba(233, 69, 96, 0.25);
81
+ }
82
+ .form-control::placeholder { color: var(--text-muted-color); opacity: 0.7; }
83
+
84
+ /* <<<--- NEON BUTTON JADU STARTS HERE --- >>> */
85
+ .btn {
86
+ border: none;
87
+ border-radius: 8px;
88
+ font-weight: 600;
89
+ padding: 12px 24px;
90
+ /* Transition for smooth effects */
91
+ transition: transform 0.1s ease-out, box-shadow 0.2s ease-out, filter 0.2s ease-out;
92
+ }
93
+ .btn:hover {
94
+ transform: translateY(-3px);
95
+ box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
96
+ }
97
+ .btn:active {
98
+ transform: translateY(0) scale(0.98); /* Button press effect */
99
+ filter: brightness(1.2); /* Extra shine */
100
+ }
101
+ .btn-primary { background: var(--gradient); color: white; }
102
+ .btn-primary:active {
103
+ /* Neon Glow for Primary Button */
104
+ box-shadow: 0 0 5px var(--primary-color),
105
+ 0 0 25px var(--primary-color),
106
+ 0 0 50px var(--primary-color);
107
+ }
108
+ .btn-secondary:active, .btn-dark:active {
109
+ /* Neon Glow for Secondary/Dark Buttons */
110
+ box-shadow: 0 0 5px rgba(255, 255, 255, 0.8),
111
+ 0 0 25px rgba(255, 255, 255, 0.5);
112
+ }
113
+ /* <<<--- NEON BUTTON JADU ENDS HERE --- >>> */
114
+
115
+ @keyframes fadeInUp {
116
+ from { opacity: 0; transform: translateY(20px); }
117
+ to { opacity: 1; transform: translateY(0); }
118
+ }
119
+ </style>
120
+ """
121
+
122
+ HTML_HOME = """
123
+ <!DOCTYPE html>
124
+ <html lang="hi">
125
+ <head>
126
+ <meta charset="UTF-8">
127
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
128
+ <title>Sparkling Gyan AI - होम</title>
129
+ <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
130
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
131
+ """ + MODERN_CSS_BASE + """
132
+ <style>
133
+ .ai-generator-controls {
134
+ border: 1px solid var(--border-color);
135
+ border-radius: 12px;
136
+ padding: 20px;
137
+ margin-top: 20px;
138
+ background-color: rgba(0,0,0,0.1);
139
+ }
140
+ </style>
141
+ </head>
142
+ <body>
143
+ <div class="container my-5">
144
+ <div class="card p-4 p-md-5">
145
+ <div class="d-flex justify-content-between align-items-center mb-3">
146
+ <h1 class="mb-0">✨ Sparkling Gyan AI</h1>
147
+ <a href="/history" class="btn btn-secondary"><i class="fas fa-history"></i> हिस्ट्री देखें</a>
148
+ </div>
149
+ <p class="text-center text-muted mb-4">एक उन्नत, ऑटोमेटिक वीडियो जेनरेटर</p>
150
+ <form id="upload-form" action="/process" method="POST" enctype="multipart/form-data">
151
+ <div class="mb-3">
152
+ <label for="script_text" class="form-label fs-5 fw-bold text-light">१. कहानी लिखें</label>
153
+ <textarea class="form-control" id="script_text" name="script_text" rows="8" placeholder="यहाँ कोई टॉपिक लिखें (जैसे 'चंद्रमा के रहस्य') और नीचे 'AI से स्क्रिप्ट बनाएँ' बटन दबाएँ, या अपनी पूरी स्क्रिप्ट यहाँ पेस्ट करें..."></textarea>
154
+ </div>
155
+ <div class="ai-generator-controls">
156
+ <div class="row align-items-end">
157
+ <div class="col-md-5">
158
+ <label for="video-length-select" class="form-label text-light">वीडियो की लंबाई</label>
159
+ <select id="video-length-select" class="form-select">
160
+ <option value="short">छोटी (~30 सेकंड)</option>
161
+ <option value="medium" selected>मध्यम (~1 मिनट)</option>
162
+ <option value="long">लंबी (~2 मिनट)</option>
163
+ </select>
164
+ </div>
165
+ <div class="col-md-7 d-grid">
166
+ <button type="button" id="generate-script-btn" class="btn btn-dark">
167
+ <i class="fas fa-magic"></i> AI से स्क्रिप्ट बनाएँ
168
+ </button>
169
+ </div>
170
+ </div>
171
+ <div id="ai-status" class="mt-2"></div>
172
+ </div>
173
+ <div class="text-center text-muted my-3">या</div>
174
+ <div class="mb-3">
175
+ <label for="script_file" class="form-label">एक ऑडियो स्क्रिप्ट फ़ाइल अपलोड करें</label>
176
+ <input class="form-control" type="file" id="script_file" name="script_file" accept="audio/*">
177
+ </div>
178
+ <h5 class="mt-4 mb-3 text-light">२. अतिरिक्त विकल्प</h5>
179
+ <div class="row mb-3">
180
+ <div class="col-md-6">
181
+ <label class="form-label">वीडियो ओरिएंटेशन</label>
182
+ <div class="form-check">
183
+ <input class="form-check-input" type="radio" name="orientation" id="orientation_horizontal" value="horizontal" checked>
184
+ <label class="form-check-label" for="orientation_horizontal">Landscape (16:9)</label>
185
+ </div>
186
+ <div class="form-check">
187
+ <input class="form-check-input" type="radio" name="orientation" id="orientation_vertical" value="vertical">
188
+ <label class="form-check-label" for="orientation_vertical">Portrait (9:16)</label>
189
+ </div>
190
+ </div>
191
+ <div class="col-md-6">
192
+ <label for="max_clip_length" class="form-label">अधिकतम क्लिप लंबाई (सेकंड)</label>
193
+ <input type="number" class="form-control" id="max_clip_length" name="max_clip_length" value="15" min="3">
194
+ </div>
195
+ </div>
196
+ <div class="form-check mb-4">
197
+ <input class="form-check-input" type="checkbox" value="true" id="mute_final_video" name="mute_final_video">
198
+ <label class="form-check-label" for="mute_final_video">ऑडियो/वॉयसओवर ट्रैक को म्यूट करें</label>
199
+ </div>
200
+ <div class="d-grid mt-4">
201
+ <button type="submit" class="btn btn-primary btn-lg">🚀 वीडियो बनाना शुरू करें!</button>
202
+ </div>
203
+ </form>
204
+ </div>
205
+ </div>
206
+ <script>
207
+ document.addEventListener('DOMContentLoaded', () => {
208
+ const generateBtn = document.getElementById('generate-script-btn');
209
+ const scriptTextArea = document.getElementById('script_text');
210
+ const lengthSelect = document.getElementById('video-length-select');
211
+ const aiStatus = document.getElementById('ai-status');
212
+ generateBtn.addEventListener('click', async () => {
213
+ const topic = scriptTextArea.value.trim();
214
+ if (!topic) { aiStatus.innerHTML = '<p class="text-danger">कृपया स्क्रिप्ट बनाने के लिए कोई टॉपिक लिखें।</p>'; return; }
215
+ const videoLength = lengthSelect.value;
216
+ generateBtn.disabled = true;
217
+ generateBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> जेनरेट हो रहा है...';
218
+ aiStatus.innerHTML = '<p>🧠 AI आपके लिए एक बेहतरीन स्क्रिप्ट लिख रहा है, कृपया प्रतीक्षा करें...</p>';
219
+ try {
220
+ const response = await fetch('/generate-script', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ topic: topic, video_length: videoLength }) });
221
+ const data = await response.json();
222
+ if (!response.ok) { throw new Error(data.error || 'सर्वर से कोई अज्ञात त्रुटि हुई।'); }
223
+ scriptTextArea.value = data.script;
224
+ aiStatus.innerHTML = '<p style="color: #2ea043;">✅ AI ने स्क्रिप्ट तैयार कर दी है! अब आप वीडियो बना सकते हैं।</p>';
225
+ } catch (error) {
226
+ console.error('Script Generation Error:', error);
227
+ aiStatus.innerHTML = `<p class="text-danger">स्क्रिप्ट बनाने में विफल: ${error.message}</p>`;
228
+ } finally {
229
+ generateBtn.disabled = false;
230
+ generateBtn.innerHTML = '<i class="fas fa-magic"></i> AI से स्क्रिप्ट बनाएँ';
231
+ }
232
+ });
233
+ });
234
+ </script>
235
+ </body>
236
+ </html>
237
+ """
238
+
239
+ HTML_PROCESSING = """
240
+ <!DOCTYPE html>
241
+ <html lang="hi">
242
+ <head>
243
+ <meta charset="UTF-8">
244
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
245
+ <title>प्रोसेसिंग...</title>
246
+ <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
247
+ """ + MODERN_CSS_BASE + """
248
+ <style>
249
+ body { display: flex; align-items: center; justify-content: center; min-height: 100vh; }
250
+ #log-output { white-space: pre-wrap; background-color: rgba(0,0,0,0.3); font-family: monospace; max-height: 400px; overflow-y: auto; border-radius: 8px; border: 1px solid var(--border-color); }
251
+ .progress-bar { background: var(--gradient); }
252
+ .progress { height: 25px; border-radius: 8px; background-color: rgba(0,0,0,0.3); }
253
+ </style>
254
+ </head>
255
+ <body>
256
+ <div class="container">
257
+ <div class="card p-4 p-md-5">
258
+ <h2 class="text-center">मिशन कंट्रोल</h2>
259
+ <p id="status-text" class="text-center text-muted">प्रक्रिया शुरू हो रही है...</p>
260
+ <div class="progress mb-3" role="progressbar">
261
+ <div class="progress-bar progress-bar-striped progress-bar-animated" id="progress-bar" style="width:0%">0%</div>
262
+ </div>
263
+ <pre id="log-output" class="p-3"></pre>
264
+ </div>
265
+ </div>
266
+ <script>
267
+ const taskId = '{{task_id}}';
268
+ const progressBar = document.getElementById('progress-bar');
269
+ const statusText = document.getElementById('status-text');
270
+ const logOutput = document.getElementById('log-output');
271
+ const pollingInterval = setInterval(async () => {
272
+ try {
273
+ const response = await fetch(`/progress/${taskId}`);
274
+ const data = await response.json();
275
+ const lastLogLine = data.log.trim().split('\\n').pop();
276
+ statusText.innerText = lastLogLine || "प्रतीक्षा में...";
277
+ progressBar.style.width = data.progress + '%';
278
+ progressBar.innerText = data.progress + '%';
279
+ logOutput.innerText = data.log;
280
+ logOutput.scrollTop = logOutput.scrollHeight;
281
+ if (data.status === 'complete') {
282
+ clearInterval(pollingInterval);
283
+ window.location.href = `/result/${data.output_filename}`;
284
+ } else if (data.status === 'error') {
285
+ clearInterval(pollingInterval);
286
+ statusText.innerText = "कोई त्रुटि हुई! विवरण के लिए लॉग देखें।";
287
+ progressBar.classList.remove('bg-success');
288
+ progressBar.classList.add('bg-danger');
289
+ }
290
+ } catch (error) {
291
+ clearInterval(pollingInterval);
292
+ statusText.innerText = "सर्वर से कनेक्शन टूट गया।";
293
+ }
294
+ }, 1500);
295
+ </script>
296
+ </body>
297
+ </html>
298
+ """
299
+
300
+ HTML_RESULT = """
301
+ <!DOCTYPE html>
302
+ <html lang="hi">
303
+ <head>
304
+ <meta charset="UTF-8">
305
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
306
+ <title>आपकी वीडियो तैयार है!</title>
307
+ <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
308
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
309
+ """ + MODERN_CSS_BASE + """
310
+ <style>
311
+ body { display: flex; align-items: center; justify-content: center; min-height: 100vh; text-align: center; }
312
+ video { width: 100%; max-width: 800px; border-radius: 12px; border: 1px solid var(--border-color); }
313
+ </style>
314
+ </head>
315
+ <body>
316
+ <div class="container">
317
+ <div class="card p-4 p-md-5">
318
+ <h1 class="mb-3">🎉 मिशन पूरा हुआ!</h1>
319
+ <p class="text-muted mb-4">आपकी फाइनल वीडियो नीचे है।</p>
320
+ <video controls autoplay muted loop>
321
+ <source src="/outputs/{{ filename }}" type="video/mp4">
322
+ आपका ब्राउज़र वीडियो टैग को सपोर्ट नहीं करता।
323
+ </video>
324
+ <div class="d-grid gap-2 d-md-flex justify-content-md-center mt-4">
325
+ <a href="/outputs/{{ filename }}" class="btn btn-primary" download><i class="fas fa-download"></i> वीडियो डाउनलोड करें</a>
326
+ <a href="/" class="btn btn-secondary">एक और वीडियो बनाएँ</a>
327
+ </div>
328
+ </div>
329
+ </div>
330
+ </body>
331
+ </html>
332
+ """
333
+
334
+ HTML_HISTORY = """
335
+ <!DOCTYPE html>
336
+ <html lang="hi">
337
+ <head>
338
+ <meta charset="UTF-8">
339
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
340
+ <title>वीडियो हिस्ट्री</title>
341
+ <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
342
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
343
+ """ + MODERN_CSS_BASE + """
344
+ <style>
345
+ .history-grid {
346
+ display: grid;
347
+ grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
348
+ gap: 20px;
349
+ }
350
+ .card { transition: transform 0.3s ease; }
351
+ .card:hover { transform: translateY(-5px); }
352
+ video { width: 100%; border-radius: 8px; margin-top: 10px; border: 1px solid var(--border-color); }
353
+ .actions a { margin-right: 10px; margin-bottom: 10px; }
354
+ </style>
355
+ </head>
356
+ <body>
357
+ <div class="container">
358
+ <a href="/" class="btn btn-secondary mb-4"><i class="fas fa-arrow-left"></i> वापस मुख्य पेज पर</a>
359
+ <h1 class="text-center mb-5">बनाए गए वीडियो की हिस्ट्री</h1>
360
+
361
+ {% if items %}
362
+ <div class="history-grid">
363
+ {% for item in items %}
364
+ <div class="card">
365
+ <div class="card-body">
366
+ <h5 class="card-title">टास्क आईडी:</h5>
367
+ <p class="card-text text-muted" style="font-size: 0.8em;">{{ item.task_id }}</p>
368
+ <video controls preload="metadata">
369
+ <source src="/outputs/{{ item.video }}" type="video/mp4">
370
+ </video>
371
+ <div class="actions mt-3">
372
+ <a href="/outputs/{{ item.video }}" class="btn btn-primary" download><i class="fas fa-download"></i> डाउनलोड</a>
373
+ {% if item.report %}
374
+ <a href="/outputs/{{ item.report }}" class="btn btn-dark" target="_blank"><i class="fas fa-file-alt"></i> रिपोर्ट देखें</a>
375
+ {% endif %}
376
+ </div>
377
+ </div>
378
+ </div>
379
+ {% endfor %}
380
+ </div>
381
+ {% else %}
382
+ <div class="text-center card p-5">
383
+ <h2>कोई हिस्ट्री नहीं मिली</h2>
384
+ <p class="text-muted">आपने अभी तक कोई वीडियो नहीं बनाया है।</p>
385
+ </div>
386
+ {% endif %}
387
+ </div>
388
+ </body>
389
+ </html>
390
+ """
391
+
392
+ # ==============================================================================
393
+ # Flask Application Setup
394
+ # ==============================================================================
395
+
396
+ app = Flask(__name__)
397
+ app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
398
+ app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER
399
+
400
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
401
+ os.makedirs(OUTPUT_FOLDER, exist_ok=True)
402
+
403
+ @app.route('/')
404
+ def home():
405
+ return render_template_string(HTML_HOME)
406
+
407
+ @app.route('/process', methods=['POST'])
408
+ def process_video():
409
+ task_id = str(uuid.uuid4())
410
+ create_task(task_id)
411
+ script_text = request.form.get('script_text')
412
+ script_file = request.files.get('script_file')
413
+ orientation = request.form.get('orientation', 'horizontal')
414
+ max_clip_length = int(request.form.get('max_clip_length', 15))
415
+ mute_final_video = request.form.get('mute_final_video') == 'true'
416
+ script_file_path = None
417
+ if script_file and script_file.filename:
418
+ filename = secure_filename(script_file.filename)
419
+ task_upload_dir = os.path.join(app.config['UPLOAD_FOLDER'], task_id)
420
+ os.makedirs(task_upload_dir, exist_ok=True)
421
+ script_file_path = os.path.join(task_upload_dir, filename)
422
+ script_file.save(script_file_path)
423
+ if not script_text and not script_file_path:
424
+ return "Please provide a script text or an audio file.", 400
425
+ thread = threading.Thread(
426
+ target=run_ai_engine_worker,
427
+ args=(task_id, script_text, script_file_path, orientation, max_clip_length, mute_final_video)
428
+ )
429
+ thread.start()
430
+ return render_template_string(HTML_PROCESSING, task_id=task_id)
431
+
432
+ @app.route('/generate-script', methods=['POST'])
433
+ def generate_script():
434
+ data = request.get_json()
435
+ topic = data.get('topic')
436
+ video_length = data.get('video_length')
437
+ if not topic or not video_length:
438
+ return jsonify({'error': 'Topic and video length are required.'}), 400
439
+ try:
440
+ generated_script = generate_script_with_ai(topic, video_length)
441
+ return jsonify({'script': generated_script})
442
+ except Exception as e:
443
+ print(f"Error during script generation: {e}")
444
+ return jsonify({'error': f"AI से संपर्क करने में विफल: {str(e)}"}), 500
445
+
446
+ @app.route('/progress/<task_id>')
447
+ def progress(task_id):
448
+ task = get_task(task_id)
449
+ if not task:
450
+ return jsonify({'status': 'error', 'log': 'Task not found.'})
451
+ return jsonify(dict(task))
452
+
453
+ @app.route('/result/<filename>')
454
+ def result(filename):
455
+ return render_template_string(HTML_RESULT, filename=filename)
456
+
457
+ @app.route('/outputs/<path:filename>')
458
+ def serve_output_file(filename):
459
+ return send_from_directory(app.config['OUTPUT_FOLDER'], filename)
460
+
461
+ @app.route('/history')
462
+ def history():
463
+ output_dir = app.config['OUTPUT_FOLDER']
464
+ history_items = []
465
+ try:
466
+ all_files = sorted(os.listdir(output_dir), reverse=True)
467
+ for filename in all_files:
468
+ if filename.endswith('_final_video.mp4'):
469
+ task_id = filename.replace('_final_video.mp4', '')
470
+ report_filename = f"{task_id}_report.json"
471
+ item = {
472
+ 'video': filename,
473
+ 'task_id': task_id,
474
+ 'report': report_filename if report_filename in all_files else None
475
+ }
476
+ history_items.append(item)
477
+ except FileNotFoundError:
478
+ print(f"'{output_dir}' directory not found.")
479
+ return render_template_string(HTML_HISTORY, items=history_items)
480
+
481
+ if __name__ == '__main__':
482
+ init_db()
483
+ app.run(host='0.0.0.0', port=5000, debug=True)
engine.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==============================================================================
2
+ # engine.py - [MODIFIED FOR DEPLOYMENT] Sparkling Gyan Version 32.3
3
+ # CHANGE: API Keys ab 'api_keys.json' se nahi, balki સીધે
4
+ # environment variables se load hongi. Isse code production-ready hai.
5
+ # ==============================================================================
6
+ import os
7
+ import time
8
+ import json
9
+ import uuid
10
+ import threading
11
+ import subprocess
12
+ import requests
13
+ import sqlite3
14
+ import random
15
+ import shutil
16
+ import re
17
+ from gtts import gTTS
18
+ from werkzeug.utils import secure_filename
19
+
20
+ # ==============================================================================
21
+ # 1. Global Setup and Database Functions
22
+ # ==============================================================================
23
+ # HOME_DIR aur CONFIG_FILE wali lines hata di gayi hain. Ab inki zaroorat nahi hai.
24
+ DATABASE_FILE = 'tasks.db'
25
+ UPLOAD_FOLDER = 'uploads'
26
+ OUTPUT_FOLDER = 'outputs'
27
+
28
+ def get_db_connection():
29
+ conn = sqlite3.connect(DATABASE_FILE, check_same_thread=False)
30
+ conn.row_factory = sqlite3.Row
31
+ return conn
32
+
33
+ def init_db():
34
+ conn = get_db_connection()
35
+ conn.execute('CREATE TABLE IF NOT EXISTS tasks (id TEXT PRIMARY KEY, status TEXT NOT NULL, progress INTEGER NOT NULL, log TEXT, output_filename TEXT)')
36
+ conn.commit()
37
+ conn.close()
38
+
39
+ def create_task(task_id):
40
+ log_message = "मिशन शुरू हो रहा है...\n"
41
+ conn = get_db_connection()
42
+ conn.execute('INSERT INTO tasks (id, status, progress, log) VALUES (?, ?, ?, ?)', (task_id, 'processing', 0, log_message))
43
+ conn.commit()
44
+ conn.close()
45
+
46
+ def get_task(task_id):
47
+ conn = get_db_connection()
48
+ task = conn.execute('SELECT * FROM tasks WHERE id = ?', (task_id,)).fetchone()
49
+ conn.close()
50
+ return task
51
+
52
+ def update_task_log(task_id, message, progress):
53
+ conn = get_db_connection()
54
+ current_log = conn.execute('SELECT log FROM tasks WHERE id = ?', (task_id,)).fetchone()['log']
55
+ new_log = current_log + message + "\n"
56
+ conn.execute('UPDATE tasks SET log = ?, progress = ? WHERE id = ?', (new_log, progress, task_id))
57
+ conn.commit()
58
+ conn.close()
59
+
60
+ def update_task_final_status(task_id, status, error_message=None, output_filename=None):
61
+ conn = get_db_connection()
62
+ current_log = conn.execute('SELECT log FROM tasks WHERE id = ?', (task_id,)).fetchone()['log']
63
+ if status == 'error':
64
+ final_log = current_log + f"\n\n🚨 FATAL ERROR: {error_message}"
65
+ conn.execute('UPDATE tasks SET status = ?, log = ? WHERE id = ?', (status, final_log, task_id))
66
+ elif status == 'complete':
67
+ final_log = current_log + "🎉 मिशन पूरा हुआ!"
68
+ conn.execute('UPDATE tasks SET status = ?, progress = ?, output_filename = ?, log = ? WHERE id = ?', (status, 100, output_filename, final_log, task_id))
69
+ conn.commit()
70
+ conn.close()
71
+
72
+ # <<<--- YAHAN BADLAV KIYA GAYA HAI --- >>>
73
+ def load_api_keys(prefix):
74
+ """
75
+ सिस्टम के एनवायरनमेंट वेरिएबल्स से API कीज़ लोड करता है।
76
+ जैसे: Gemini_Key_1, Pexels_Key_1 आदि।
77
+ """
78
+ try:
79
+ prefix_lower = prefix.lower()
80
+ # यह लाइन सिस्टम के सभी एनवायरनमेंट वेरिएबल्स को चेक करेगी
81
+ keys = [v for k, v in os.environ.items() if k.lower().startswith(prefix_lower)]
82
+
83
+ if not keys:
84
+ print(f"🚨 चेतावनी: '{prefix}' से शुरू होने वाला कोई एनवायरनमेंट वेरिएबल नहीं मिला।")
85
+ return keys
86
+ except Exception as e:
87
+ print(f"🚨 एनवायरनमेंट वेरिएबल्स लोड करते समय त्रुटि: {e}")
88
+ return []
89
+ # <<<--- BADLAV YAHAN KHATM HOTA HAI --- >>>
90
+
91
+ # ==============================================================================
92
+ # 2. All API and Worker Classes
93
+ # (Is section mein koi badlav nahi hai)
94
+ # ==============================================================================
95
+ class GroqAPI:
96
+ def __init__(self, api_keys): self.api_keys, self.api_url, self.model, self._key_index = api_keys, "https://api.groq.com/openai/v1/audio/transcriptions", "whisper-large-v3", 0
97
+ def transcribe_audio(self, audio_path):
98
+ if not self.api_keys: raise Exception("Groq API key not found.")
99
+ api_key = self.api_keys[self._key_index % len(self.api_keys)]; self._key_index += 1
100
+ data = {'model': self.model, 'response_format': 'verbose_json', 'timestamp_granularities[]': 'word'}
101
+ headers = {'Authorization': f'Bearer {api_key}'}
102
+ try:
103
+ with open(audio_path, 'rb') as audio_file:
104
+ files = {'file': (os.path.basename(audio_path), audio_file, 'audio/mpeg')}; print(f"-> Groq API को शब्द-स्तर पर टाइ��स्टैम्प के लिए भेजा जा रहा है...")
105
+ response = requests.post(self.api_url, headers=headers, data=data, files=files, timeout=120); response.raise_for_status()
106
+ words_data = response.json().get('words', []); print(f"-> ट्रांसक्रिप्शन सफल: {len(words_data)} शब्दों के टाइमस्टैम्प मिले।"); return words_data
107
+ except Exception as e: raise Exception(f"Groq API Error: {e}")
108
+
109
+ class PexelsAPI:
110
+ def __init__(self, api_keys):
111
+ if not api_keys: raise Exception("Pexels API key not found.")
112
+ self.api_key = api_keys[0]; self.api_url = "https://api.pexels.com/videos/search"
113
+ def search_and_download(self, query, download_path, orientation, search_page=1):
114
+ print(f"-> Pexels पर खोजा जा रहा है (Direct API): '{query}' (Page: {search_page}, Orientation: {orientation})")
115
+ headers = {'Authorization': self.api_key}; params = {'query': query, 'page': search_page, 'per_page': 1, 'orientation': orientation}
116
+ try:
117
+ response = requests.get(self.api_url, headers=headers, params=params, timeout=60); response.raise_for_status(); data = response.json()
118
+ if not data.get('videos'): print(f"-> Pexels पर '{query}' के लिए कोई परिणाम नहीं मिला।"); return None
119
+ video_data = data['videos'][0]; video_files = video_data.get('video_files', []); best_link = None
120
+ for video_file in video_files:
121
+ if video_file.get('quality') == 'hd': best_link = video_file.get('link'); break
122
+ if not best_link and video_files: best_link = video_files[0].get('link')
123
+ if not best_link: print(f"-> Pexels परिणाम में कोई डाउनलोड करने योग्य लिंक नहीं मिला।"); return None
124
+ print(f"-> Pexels से वीडियो डाउनलोड किया जा रहा है..."); download_response = requests.get(best_link, stream=True, timeout=60); download_response.raise_for_status()
125
+ with open(download_path, 'wb') as f:
126
+ for chunk in download_response.iter_content(chunk_size=8192): f.write(chunk)
127
+ print(f"-> सफलतापूर्वक सहेजा गया: {download_path}"); return download_path
128
+ except requests.exceptions.RequestException as e: print(f"🚨 Pexels API में त्रुटि: {e}"); return None
129
+ except Exception as e: print(f"🚨 Pexels वीडियो डाउनलोड करने में अज्ञात त्रुटि: {e}"); return None
130
+
131
+ class PixabayAPI:
132
+ def __init__(self, api_keys):
133
+ if not api_keys: raise Exception("Pixabay API key not found.")
134
+ self.api_key = api_keys[0]; self.api_url = "https://pixabay.com/api/videos/"
135
+ def search_and_download(self, query, download_path, orientation, max_clip_length, search_index=0):
136
+ print(f"-> Pixabay पर खोजा जा रहा है: '{query}' (Index: {search_index})")
137
+ params = {'key': self.api_key, 'q': query, 'per_page': 5, 'orientation': orientation, 'max_duration': int(max_clip_length)}
138
+ try:
139
+ response = requests.get(self.api_url, params=params, timeout=60); response.raise_for_status(); results = response.json()
140
+ if not results['hits'] or len(results['hits']) <= search_index: print(f"-> Pixabay पर '{query}' के लिए index {search_index} पर कोई परिणाम नहीं मिला।"); return None
141
+ video_url = results['hits'][search_index]['videos']['medium']['url']; print(f"-> Pixabay से वीडियो डाउनलोड किया जा रहा है...")
142
+ response = requests.get(video_url, stream=True, timeout=60); response.raise_for_status()
143
+ with open(download_path, 'wb') as f:
144
+ for chunk in response.iter_content(chunk_size=8192): f.write(chunk)
145
+ print(f"-> सफलतापूर्वक सहेजा गया: {download_path}"); return download_path
146
+ except Exception as e: print(f"🚨 Pixabay API में त्रुटि: {e}"); return None
147
+
148
+ class GeminiTeam:
149
+ MODELS_LIST_URL = "https://generativelanguage.googleapis.com/v1beta/models"
150
+ def __init__(self, api_keys):
151
+ self.api_keys = api_keys
152
+ if not self.api_keys: raise Exception("Gemini API key not found.")
153
+ self.model_name = self._find_best_model()
154
+ if not self.model_name: raise Exception("Could not dynamically find a suitable Gemini 'flash' model from any of the provided keys.")
155
+ self.api_url = f"https://generativelanguage.googleapis.com/v1beta/{self.model_name}:generateContent"
156
+ print(f"✅ स्मार्ट मॉडल हंटर सफल: '{self.model_name}' का उपयोग किया जाएगा।")
157
+ def _find_best_model(self):
158
+ print("-> स्मार्ट मॉडल हंटर: सबसे अच्छे 'gemini-*-flash' मॉडल को खोजा जा रहा है...")
159
+ for api_key in self.api_keys:
160
+ try:
161
+ print(f"-> API Key के अंतिम 4 अक्षरों से कोशिश की जा रही है: ...{api_key[-4:]}")
162
+ response = requests.get(f"{self.MODELS_LIST_URL}?key={api_key}", timeout=20); response.raise_for_status(); data = response.json()
163
+ available_models = [m['name'] for m in data.get('models', []) if 'flash' in m['name'] and 'generateContent' in m.get('supportedGenerationMethods', []) and 'exp' not in m['name']]
164
+ if not available_models: continue
165
+ available_models.sort(reverse=True); print(f"-> उपलब्ध 'flash' मॉडल मिले: {available_models}"); return available_models[0]
166
+ except requests.exceptions.RequestException as e: print(f"🚨 API Key ...{api_key[-4:]} के साथ त्रुटि: {e}. अगली की आजमाई जा रही है..."); continue
167
+ print("🚨 स्मार्ट मॉडल हंटर में गंभीर त्रुटि: कोई भी Gemini API Key काम नहीं कर रही है।"); return None
168
+ def _make_resilient_api_call(self, prompt, timeout=120):
169
+ headers = {'Content-Type': 'application/json'}; payload = {'contents': [{'parts': [{'text': prompt}]}]}
170
+ for api_key in self.api_keys:
171
+ try:
172
+ print(f"-> Gemini को अनुरोध भेजा जा रहा है (Key: ...{api_key[-4:]}, Model: {self.model_name.split('/')[-1]})")
173
+ response = requests.post(f"{self.api_url}?key={api_key}", headers=headers, json=payload, timeout=timeout); response.raise_for_status(); result = response.json()
174
+ if 'candidates' not in result or not result['candidates']: print(f"🚨 चेतावनी: Key ...{api_key[-4:]} से कोई कैंडिडेट नहीं मिला (संभवतः सुरक्षा ब्लॉक)। अगली की आजमाई जा रही है..."); continue
175
+ return result
176
+ except requests.exceptions.RequestException as e: print(f"🚨 API कॉल में त्रुटि (Key: ...{api_key[-4:]}): {e}. अगली की आजमाई जा रही है...");
177
+ raise Exception("Gemini API Error: All available API keys failed. Please check your keys and quotas.")
178
+ def extract_keywords(self, script_text):
179
+ prompt = f"""You are a search query expert. Analyze the script below and for each scene, create a JSON object. Each object must contain: 1. "scene_description": A brief description of the scene. 2. "primary_query": A highly creative, emotional, and cinematic search query in English. This is the main attempt. 3. "fallback_query": A simple, literal, and direct search query in English. Use this if the primary query fails. RULES: - Your response MUST be ONLY a JSON list of objects. - All queries must be in English. Script: "{script_text}" Example: [ {{"scene_description": "A person looking at a mountain.", "primary_query": "inspirational mountain peak cinematic hope", "fallback_query": "man looking at mountain"}} ] Generate the JSON:"""
180
+ result = self._make_resilient_api_call(prompt)
181
+ json_str = result['candidates'][0]['content']['parts'][0]['text']
182
+ clean_str = json_str[json_str.find('['):json_str.rfind(']') + 1]; scenes = json.loads(clean_str)
183
+ try:
184
+ log_file_path = 'gemini_analysis_log.json';
185
+ with open(log_file_path, 'w', encoding='utf-8') as f: json.dump(scenes, f, ensure_ascii=False, indent=4)
186
+ print(f"-> Gemini का विश्लेषण सफलतापूर्वक '{log_file_path}' में सहेजा गया।")
187
+ except Exception as e: print(f"🚨 चेतावनी: Gemini विश्लेषण लॉग करने में विफल: {e}")
188
+ print(f"-> Gemini ने सफलतापूर्वक {len(scenes)} प्राथमिक/फ़ॉलबैक दृश्य निकाले।"); return scenes
189
+ def create_master_timeline(self, word_timestamps, enriched_scenes_with_paths):
190
+ full_script_text = " ".join([word['word'] for word in word_timestamps]); total_duration = word_timestamps[-1]['end'] if word_timestamps else 0
191
+ prompt = f"""You are an expert AI video editor. Create a frame-perfect timeline JSON.
192
+ Assets:
193
+ 1. **Full Script:** "{full_script_text}"
194
+ 2. **Total Audio Duration:** {total_duration:.2f} seconds.
195
+ 3. **Available Scene Clips:** {json.dumps(enriched_scenes_with_paths, indent=2)}
196
+ 4. **Word-Level Timestamps (with Pauses):** {json.dumps(word_timestamps, indent=2)}.
197
+
198
+ RULES:
199
+ 1. Your response MUST be ONLY a list of JSON objects.
200
+ 2. Each object must have "start", "end", "matched_clip", and "start_offset_seconds".
201
+ 3. **CRITICAL:** The timeline MUST cover the entire audio duration from 0 to {total_duration:.2f} seconds. There should be NO GAPS.
202
+ 4. **CRITICAL:** You MUST use each video from the 'Available Scene Clips' list only once. Do not repeat clips.
203
+ 5. **NEW CRITICAL RULE:** In the 'Word-Level Timestamps', you will find special words like '[PAUSE]'. This represents a deliberate silence in the narration. Treat this as a creative opportunity! It is the perfect moment for a beautiful transition between two clips or to let a cinematic shot play out for its full emotional impact. DO NOT repeat the previous clip to fill a pause. Use the pause to enhance the video's pacing.
204
+
205
+ Create the final timeline JSON:"""
206
+ result = self._make_resilient_api_call(prompt, timeout=180)
207
+ json_str = result['candidates'][0]['content']['parts'][0]['text']
208
+ clean_str = json_str[json_str.find('['):json_str.rfind(']') + 1]; final_timeline = json.loads(clean_str)
209
+ print(f"-> Gemini Master Editor ने सफलतापूर्वक {len(final_timeline)} क्लिप्स की टाइमलाइन और ऑफसेट बना दी है।"); return final_timeline
210
+ def generate_script(self, topic, video_length):
211
+ word_count_map = {"short": "~75 शब्द", "medium": "~150 शब्द", "long": "~300 शब्द"}; target_word_count = word_count_map.get(video_length, "~150 शब्द")
212
+ prompt = f"""आप 'स्पार्कलिंग ज्ञान' के लिए एक विशेषज्ञ हिंदी स्क्रिप्ट राइटर हैं।
213
+ विषय: "{topic}".
214
+ निर्देश:
215
+ 1. इस विषय पर एक आकर्षक, {target_word_count} की स्क्रिप्ट लिखें।
216
+ 2. भाषा सरल और बोलचाल वाली हो।
217
+ 3. हर 2-3 लाइनों के बाद एक नया विज़ुअल या सीन दिखाया जा सके, इस तरह से लिखें।
218
+ 4. **CRITICAL RULE:** आपका आउटपुट सिर्फ और सिर्फ बोले जाने वाले डायलॉग्स (narration) होने चाहिए। किसी भी तरह के विज़ुअल निर्देश, सीन डिस्क्रिप्शन या ब्रैकेट () [] में लिखी कोई भी जानकारी आउटपुट में नहीं होनी चाहिए। सिर्फ वो टेक्स्ट दें जो ऑडियो में बोला जाएगा।
219
+
220
+ अब, स्क्रिप्ट लिखें:"""
221
+ result = self._make_resilient_api_call(prompt)
222
+ generated_script = result['candidates'][0]['content']['parts'][0]['text']
223
+ print("-> Gemini ने सफलतापूर्वक स्क्रिप्ट जेनरेट कर दी है।"); return generated_script.strip()
224
+
225
+ # ... (बाकी का पूरा engine.py कोड जैसा था वैसा ही रहेगा)
226
+ # ... मैं पूरा कोड यहाँ दोबारा नहीं पेस्ट कर रहा हूँ क्योंकि उसमें कोई और बदलाव नहीं है।
227
+ # ... बस ऊपर दिए गए `load_api_keys` फंक्शन को बदलें।
228
+ # ... अगर आप चाहें, तो मैं बाकी का कोड भी पेस्ट कर सकता हूँ।
229
+
230
+ # [NOTE: Assuming the user can copy-paste the rest of their own file.
231
+ # For clarity, I'll paste the rest of the file so they have a single block to copy.]
232
+
233
+ class VideoAssembler:
234
+ TRANSITION_DURATION = 0.5
235
+ def __init__(self, timeline, narration_audio, output_path, width, height, mute_audio, temp_dir):
236
+ self.timeline = timeline; self.narration_audio = narration_audio; self.output_path = output_path; self.width = width; self.height = height; self.mute_audio = mute_audio
237
+ self.temp_dir = temp_dir
238
+ os.makedirs(self.temp_dir, exist_ok=True)
239
+ def _run_ffmpeg_command(self, command, suppress_errors=False):
240
+ process = subprocess.run(command, capture_output=True, text=True)
241
+ if not suppress_errors and process.returncode != 0:
242
+ error_details = f"Return Code {process.returncode}"
243
+ if process.returncode == -9: error_details += " (SIGKILL): Process was killed, likely due to excessive memory usage."
244
+ raise Exception(f"FFmpeg Error ({error_details}):\nSTDERR:\n{process.stderr}")
245
+ return process
246
+ def assemble_video(self, log_callback):
247
+ if not self.timeline: return
248
+ log_callback("-> Stage 1/3: सभी क्लिप्स को व्यक्तिगत रूप से तैयार किया जा रहा है...", 91)
249
+ prepared_clips = []
250
+ for i, item in enumerate(self.timeline):
251
+ input_clip_path = item['matched_clip']
252
+ try:
253
+ ffprobe_command = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', input_clip_path]
254
+ duration_proc = self._run_ffmpeg_command(ffprobe_command)
255
+ actual_clip_duration = float(duration_proc.stdout.strip())
256
+ except Exception as e:
257
+ log_callback(f"🚨 चेतावनी: क्लिप {os.path.basename(input_clip_path)} की अवधि का पता नहीं लगाया जा सका, इसे छोड़ दिया जाएगा। त्रुटि: {e}", 91)
258
+ continue
259
+ start_offset = float(item.get('start_offset_seconds', 0.0))
260
+ if start_offset >= actual_clip_duration:
261
+ log_callback(f" -> 🚨 चेतावनी: AI द्वारा दिया गया स्टार्ट ऑफसेट ({start_offset}s) क्लिप की वास्तविक लंबाई ({actual_clip_duration:.2f}s) से अधिक है। ऑफसेट को 0 पर रीसेट किया जा रहा है।", 91)
262
+ start_offset = 0.0
263
+ is_last_clip = (i == len(self.timeline) - 1)
264
+ overlap = 0 if is_last_clip else self.TRANSITION_DURATION
265
+ duration = (float(item['end']) - float(item['start'])) + overlap
266
+ if duration <= 0: continue
267
+ output_clip_path = os.path.join(self.temp_dir, f"prepared_{i:03d}.mp4")
268
+ command = [
269
+ 'ffmpeg', '-y', '-ss', str(start_offset), '-i', input_clip_path, '-t', str(duration),
270
+ '-vf', f"scale='w={self.width}:h={self.height}:force_original_aspect_ratio=increase',crop={self.width}:{self.height},setsar=1,fps=30",
271
+ '-c:v', 'libx264', '-preset', 'ultrafast', '-an', '-threads', '1', output_clip_path
272
+ ]
273
+ self._run_ffmpeg_command(command)
274
+ prepared_clips.append(output_clip_path)
275
+ log_callback("-> Stage 2/3: क्लिप्स को ट्रांजीशन के साथ जोड़ा जा रहा है...", 94)
276
+ if not prepared_clips: raise Exception("कोई भी क्लिप सफलतापूर्वक तैयार नहीं हो सकी।")
277
+ if len(prepared_clips) == 1:
278
+ shutil.copy(prepared_clips[0], self.output_path)
279
+ transitioned_video_path = self.output_path
280
+ else:
281
+ current_video = prepared_clips[0]
282
+ for i in range(len(prepared_clips) - 1):
283
+ next_video = prepared_clips[i+1]
284
+ output_path = os.path.join(self.temp_dir, f"transition_{i:03d}.mp4")
285
+ total_transitions = len(prepared_clips) - 1
286
+ progress = 94 + int((i / total_transitions) * 4) if total_transitions > 0 else 94
287
+ log_callback(f" -> ट्रांजीशन बनाया जा रहा है: क्लिप {i+1} और {i+2}", progress)
288
+ ffprobe_command = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', current_video]
289
+ duration_proc = self._run_ffmpeg_command(ffprobe_command)
290
+ transition_offset = float(duration_proc.stdout.strip()) - self.TRANSITION_DURATION
291
+ command = [
292
+ 'ffmpeg', '-y', '-i', current_video, '-i', next_video,
293
+ '-filter_complex', f"[0:v][1:v]xfade=transition=fade:duration={self.TRANSITION_DURATION}:offset={transition_offset},format=yuv420p",
294
+ '-c:v', 'libx264', '-preset', 'ultrafast', output_path
295
+ ]
296
+ self._run_ffmpeg_command(command)
297
+ current_video = output_path
298
+ transitioned_video_path = current_video
299
+ log_callback("-> Stage 3/3: फाइनल वीडियो में ऑडियो जोड़ा जा रहा है...", 98)
300
+ audio_input = [] if self.mute_audio else ['-i', self.narration_audio]
301
+ audio_map = ['-an'] if self.mute_audio else ['-map', '0:v:0', '-map', '1:a:0']
302
+ command = [
303
+ 'ffmpeg', '-y', '-i', transitioned_video_path,
304
+ ] + audio_input + [
305
+ '-c:v', 'copy',
306
+ ] + audio_map + [
307
+ '-c:a', 'aac', '-shortest', self.output_path
308
+ ]
309
+ self._run_ffmpeg_command(command)
310
+
311
+ # ==============================================================================
312
+ # 3. AI इंजन का मुख्य वर्कर
313
+ # (Is section mein koi badlav nahi hai)
314
+ # ==============================================================================
315
+ def run_ai_engine_worker(task_id, script_text, script_file_path, orientation, max_clip_length, mute_final_video):
316
+ log = lambda message, progress: update_task_log(task_id, message, progress)
317
+ temp_dir = os.path.join(UPLOAD_FOLDER, task_id)
318
+ try:
319
+ log("Step 0: API Keys की पुष्टि...", 2)
320
+ gemini_keys, pexels_keys, pixabay_keys, groq_keys = load_api_keys("Gemini_Key"), load_api_keys("Pexels_Key"), load_api_keys("Pixabay_Key"), load_api_keys("Groq_Key")
321
+ if not all([gemini_keys, pexels_keys, pixabay_keys, groq_keys]): raise Exception("API Key Error: Missing one or more required keys.")
322
+ gemini = GeminiTeam(api_keys=gemini_keys); log("-> सभी जरूरी API कीज मौजूद हैं।", 5)
323
+ log("Step 1: स्क्रिप्ट तैयार की जा रही है...", 8)
324
+ os.makedirs(temp_dir, exist_ok=True); narration_audio_path = ""
325
+ if script_file_path:
326
+ narration_audio_path = script_file_path; log("-> ऑडियो फ़ाइल प्राप्त हुई।", 12)
327
+ else:
328
+ cleaned_script_for_tts = re.sub(r'\[.*?\]|\(.*?\)', '', script_text)
329
+ full_script_text_for_tts = cleaned_script_for_tts.strip()
330
+ narration_audio_path = os.path.join(temp_dir, "narration.mp3")
331
+ gTTS(full_script_text_for_tts, lang='hi').save(narration_audio_path)
332
+ log(f"-> TTS ke liye saaf script bheji gayi: '{full_script_text_for_tts}'", 12)
333
+ log("-> टेक्स्ट से ऑडियो सफलतापूर्वक बनाया गया।", 12)
334
+ log("Step 2: ऑडियो का सटीक विश्लेषण (Groq)...", 15)
335
+ groq_api = GroqAPI(api_keys=groq_keys); word_timestamps = groq_api.transcribe_audio(narration_audio_path)
336
+ if not word_timestamps: raise Exception("Transcription failed or returned no words.")
337
+ log("-> Smart Pause Detector: ऑडियो में लंबी chuppi खोजी जा रही है...", 20)
338
+ timestamps_with_pauses = []
339
+ pause_threshold = 1.5
340
+ pause_count = 0
341
+ if word_timestamps:
342
+ timestamps_with_pauses.append(word_timestamps[0])
343
+ for i in range(len(word_timestamps) - 1):
344
+ current_word_end = float(word_timestamps[i]['end'])
345
+ next_word_start = float(word_timestamps[i+1]['start'])
346
+ gap = next_word_start - current_word_end
347
+ if gap > pause_threshold:
348
+ pause_event = {'word': '[PAUSE]', 'start': current_word_end, 'end': next_word_start}
349
+ timestamps_with_pauses.append(pause_event)
350
+ pause_count += 1
351
+ timestamps_with_pauses.append(word_timestamps[i+1])
352
+ if pause_count > 0:
353
+ log(f"-> Pause Detector ne सफलतापूर्वक {pause_count} pauses jode. Ab AI inka creative istemaal karega.", 22)
354
+ else:
355
+ log("-> Pause Detector ko koi lamba pause nahi mila. Sab theek hai.", 22)
356
+ full_script_text = " ".join([word['word'] for word in timestamps_with_pauses]); log(f"-> पूर्ण स्क्रिप्ट (pauses ke saath): '{full_script_text}'", 25)
357
+ log("Step 3: Contextual वीडियो खोजे जा रहे हैं (Smart Search)...", 30)
358
+ scenes_from_gemini = gemini.extract_keywords(full_script_text)
359
+ pexels = PexelsAPI(api_keys=pexels_keys); pixabay = PixabayAPI(api_keys=pixabay_keys)
360
+ for i, scene in enumerate(scenes_from_gemini):
361
+ scene['downloaded_path'] = None; primary_query = scene.get('primary_query'); fallback_query = scene.get('fallback_query')
362
+ log(f"-> Scene {i+1} ('{scene['scene_description'][:20]}...') के लिए वीडियो खोजा जा रहा है...", 30 + i * 5)
363
+ filename = f"scene_{i+1}_{secure_filename(primary_query)[:20]}.mp4"; download_path = os.path.join(temp_dir, filename)
364
+ log(f" -> प्राथमिक कोशिश (Primary): '{primary_query}'...", 30 + i * 5)
365
+ for attempt in range(2):
366
+ path = pexels.search_and_download(primary_query, download_path, orientation, search_page=attempt + 1)
367
+ if path: scene['downloaded_path'] = path; break
368
+ path = pixabay.search_and_download(primary_query, download_path, orientation, max_clip_length, search_index=attempt)
369
+ if path: scene['downloaded_path'] = path; break
370
+ if not scene.get('downloaded_path'):
371
+ log(f" -> प्राथमिक कोशिश विफल। फ़ॉलबैक कोशिश (Fallback): '{fallback_query}'...", 30 + i * 5)
372
+ for attempt in range(2):
373
+ path = pexels.search_and_download(fallback_query, download_path, orientation, search_page=attempt + 1)
374
+ if path: scene['downloaded_path'] = path; break
375
+ path = pixabay.search_and_download(fallback_query, download_path, orientation, max_clip_length, search_index=attempt)
376
+ if path: scene['downloaded_path'] = path; break
377
+ if scene['downloaded_path']: log(f"-> Scene {i+1} के ���िए वीडियो सफलतापूर्वक डाउनलोड हुआ: {os.path.basename(scene['downloaded_path'])}", 30 + i * 5)
378
+ else: log(f"🚨 चेतावनी: Scene {i+1} के लिए कोई भी वीडियो नहीं मिला (Primary और Fallback दोनों विफल)।", 30 + i * 5)
379
+ successful_scenes = [scene for scene in scenes_from_gemini if scene.get('downloaded_path')]
380
+ if not successful_scenes: raise Exception("Could not download any videos for the given script.")
381
+ log(f"-> {len(successful_scenes)} वीडियो क्लिप्स सफलतापूर्वक डाउनलोड हुए।", 60)
382
+ log("Step 4: मास्टर टाइमलाइन और इंटेलिजेंट क्लिप ट्रिमिंग की जा रही है...", 75)
383
+ final_timeline = gemini.create_master_timeline(timestamps_with_pauses, successful_scenes); log(f"-> मास्टर टाइमलाइन AI से प्राप्त हुई।", 85)
384
+ log("-> मास्टर टाइमलाइन को सत्यापित और डी-डुप्लिकेट किया जा रहा है...", 86)
385
+ validated_timeline = []
386
+ used_clips = set()
387
+ for clip in final_timeline:
388
+ path_value = clip.get('matched_clip')
389
+ actual_path = None
390
+ if isinstance(path_value, str):
391
+ actual_path = path_value
392
+ elif isinstance(path_value, dict):
393
+ actual_path = path_value.get('downloaded_path')
394
+ if actual_path and isinstance(actual_path, str) and os.path.exists(actual_path) and actual_path not in used_clips:
395
+ clip['matched_clip'] = actual_path
396
+ validated_timeline.append(clip)
397
+ used_clips.add(actual_path)
398
+ else:
399
+ log(f"🚨 चेतावनी: टाइमलाइन में एक अमान्य या डुप्लिकेट क्लिप को अनदेखा किया जा रहा है: {os.path.basename(actual_path or 'Invalid Path')}", 87)
400
+ if not validated_timeline:
401
+ raise Exception("Timeline verification failed. No valid, unique clips found on disk.")
402
+ log("-> टाइमलाइन में गैप्स की जाँच और उन्हें ठीक किया जा रहा है...", 88)
403
+ final_gapless_timeline = []; total_duration = word_timestamps[-1]['end'] if word_timestamps else 0
404
+ validated_timeline.sort(key=lambda x: float(x['start']))
405
+ for i, clip in enumerate(validated_timeline):
406
+ if i < len(validated_timeline) - 1:
407
+ current_clip_end = float(clip['end']); next_clip_start = float(validated_timeline[i+1]['start'])
408
+ if current_clip_end < next_clip_start: log(f" -> Gap मिला: क्लिप {i+1} को {current_clip_end} से {next_clip_start} तक बढ़ाया जा रहा है।", 88); clip['end'] = next_clip_start
409
+ elif i == len(validated_timeline) - 1:
410
+ last_clip_end = float(clip['end'])
411
+ if last_clip_end < total_duration: log(f" -> अंतिम क्लिप को ऑडियो के अंत तक बढ़ाया जा रहा है: {last_clip_end} से {total_duration}", 88); clip['end'] = total_duration
412
+ final_gapless_timeline.append(clip)
413
+ log(f"-> गैप-फिलिंग सफल। {len(final_gapless_timeline)} क्लिप्स की एक सहज टाइमलाइन तैयार है।", 89)
414
+ log("Step 5: फाइनल वीडियो को रेंडर किया जा रहा है (Cinematic Transitions)...", 90)
415
+ width, height = (1080, 1920) if orientation == 'vertical' else (1920, 1080)
416
+ output_filename = f"{task_id}_final_video.mp4"; output_path = os.path.join(OUTPUT_FOLDER, output_filename)
417
+ assembler = VideoAssembler(final_gapless_timeline, narration_audio_path, output_path, width, height, mute_final_video, temp_dir)
418
+ assembler.assemble_video(log)
419
+ log("-> अंतिम विस्तृत रिपोर्ट बनाई जा रही है...", 99)
420
+ try:
421
+ report_data = { "full_transcribed_script": full_script_text, "groq_word_timestamps": word_timestamps, "timestamps_with_pauses_added": timestamps_with_pauses, "gemini_scene_analysis_and_downloads": successful_scenes, "gemini_raw_timeline": final_timeline, "processed_gapless_timeline": final_gapless_timeline, }
422
+ report_file_path = os.path.join(OUTPUT_FOLDER, f'{task_id}_report.json')
423
+ with open(report_file_path, 'w', encoding='utf-8') as f: json.dump(report_data, f, ensure_ascii=False, indent=4)
424
+ log(f"-> विस्तृत रिपोर्ट सफलतापूर्वक '{report_file_path}' में सहेजी गई।", 99)
425
+ except Exception as e: log(f"🚨 चेतावनी: विस्तृत रिपोर्ट सहेजने में विफल: {e}", 99)
426
+ update_task_final_status(task_id, 'complete', output_filename=output_filename)
427
+ except Exception as e:
428
+ import traceback; traceback.print_exc()
429
+ update_task_final_status(task_id, 'error', error_message=str(e))
430
+ finally:
431
+ if os.path.exists(temp_dir):
432
+ try:
433
+ shutil.rmtree(temp_dir)
434
+ log(f"-> Temporary files aur folder '{temp_dir}' ko saaf kar diya gaya hai.", 100)
435
+ except Exception as e: print(f"Cleanup Error: {e}")
436
+
437
+ # ==============================================================================
438
+ # 4. AI Script Generation Function
439
+ # (Is section mein koi badlav nahi hai)
440
+ # ==============================================================================
441
+ def generate_script_with_ai(topic, video_length):
442
+ print(f"-> AI स्क्रिप्ट जेनरेटर शुरू हुआ: Topic='{topic}', Length='{video_length}'")
443
+ try:
444
+ gemini_keys = load_api_keys("Gemini_Key")
445
+ if not gemini_keys: raise Exception("Gemini API key not found for script generation.")
446
+ gemini_agent = GeminiTeam(api_keys=gemini_keys)
447
+ script = gemini_agent.generate_script(topic, video_length)
448
+ return script
449
+ except Exception as e:
450
+ raise e
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gunicorn
2
+ # ...आपकी अन्य लाइब्रेरीज़
3
+ blinker==1.9.0
4
+ certifi==2025.10.5
5
+ charset-normalizer==3.4.4
6
+ click==8.1.8
7
+ Flask==3.1.2
8
+ gTTS==2.5.4
9
+ idna==3.11
10
+ itsdangerous==2.2.0
11
+ Jinja2==3.1.6
12
+ MarkupSafe==3.0.3
13
+ pexels-api==1.0.1
14
+ python-dotenv==1.1.1
15
+ requests==2.32.5
16
+ urllib3==2.5.0
17
+ Werkzeug==3.1.3
version.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ v0