PR-Puppets commited on
Commit
ea6481e
β€’
1 Parent(s): 20046b2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +315 -0
app.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import time
4
+ import uuid
5
+ import os
6
+ from huggingface_hub import HfApi, hf_hub_download
7
+ import pandas as pd
8
+ import shutil
9
+ import json
10
+ from pathlib import Path
11
+
12
+ PAGE_SIZE = 10
13
+ FILE_DIR_PATH = "."
14
+
15
+ repo_id = os.environ["DATASET"]
16
+
17
+ def append_videos_to_dataset(
18
+ video_urls,
19
+ video_paths,
20
+ prompts=None,
21
+ split="train",
22
+ commit_message="Added new videos"
23
+ ):
24
+ api = HfApi()
25
+ temp_dir = Path("temp_dataset_folder")
26
+ split_dir = temp_dir / split
27
+ split_dir.mkdir(parents=True, exist_ok=True)
28
+
29
+ try:
30
+ # Download existing metadata if it exists
31
+ try:
32
+ metadata_path = hf_hub_download(
33
+ repo_id=repo_id,
34
+ filename=f"{split}/metadata.csv",
35
+ repo_type="dataset"
36
+ )
37
+ existing_metadata = pd.read_csv(metadata_path)
38
+ if 'prompt' not in existing_metadata.columns:
39
+ existing_metadata['prompt'] = ''
40
+ except:
41
+ existing_metadata = pd.DataFrame(columns=['file_name', 'prompt'])
42
+
43
+ # Prepare new metadata entries
44
+ new_entries = []
45
+ for i, video_path in enumerate(video_paths):
46
+ video_name = Path(video_path).name
47
+
48
+ # Copy video to temporary directory
49
+ shutil.copy2(video_path, split_dir / video_name)
50
+
51
+ # Add metadata entry with prompt
52
+ new_entries.append({
53
+ 'file_name': video_name,
54
+ 'prompt': prompts[i] if prompts else '',
55
+ 'original_url': video_urls[i] if video_urls else ''
56
+ })
57
+
58
+ # Combine existing and new metadata
59
+ new_metadata = pd.concat([
60
+ existing_metadata,
61
+ pd.DataFrame(new_entries)
62
+ ]).drop_duplicates(subset=['file_name'], keep='last')
63
+
64
+ # Ensure no NaN values in prompts
65
+ new_metadata['prompt'] = new_metadata['prompt'].fillna('')
66
+
67
+ # Save updated metadata
68
+ new_metadata.to_csv(split_dir / 'metadata.csv', index=False)
69
+
70
+ # Upload to Hugging Face Hub
71
+ api.upload_folder(
72
+ folder_path=str(temp_dir),
73
+ repo_id=repo_id,
74
+ repo_type="dataset",
75
+ commit_message=commit_message
76
+ )
77
+
78
+ finally:
79
+ # Clean up temporary directory
80
+ if temp_dir.exists():
81
+ shutil.rmtree(temp_dir)
82
+
83
+
84
+
85
+ def generate_video(prompt, size, duration, generation_history, progress=gr.Progress()):
86
+ url = 'https://sora.openai.com/backend/video_gen?force_paragen=false'
87
+
88
+ headers = json.loads(os.environ["HEADERS"])
89
+
90
+ cookies = json.loads(os.environ["COOKIES"])
91
+ if size == "1080p":
92
+ width = 1920
93
+ height = 1080
94
+ elif size == "720p":
95
+ width = 1280
96
+ height = 720
97
+ elif size == "480p":
98
+ width = 854
99
+ height = 480
100
+ elif size == "360p":
101
+ width = 640
102
+ height = 360
103
+ payload = {
104
+ "type": "video_gen",
105
+ "prompt": prompt,
106
+ "n_variants": 1,
107
+ "n_frames": 30 * duration,
108
+ "height": height,
109
+ "width": width,
110
+ "style": "natural",
111
+ "inpaint_items": [],
112
+ "model": "turbo",
113
+ "operation": "simple_compose"
114
+ }
115
+
116
+ # Initial request to generate video
117
+ response = requests.post(url, headers=headers, cookies=cookies, json=payload)
118
+
119
+ if response.status_code != 200:
120
+ raise gr.Error("Something went wrong")
121
+
122
+ task_id = response.json()["id"]
123
+ gr.Info("Video generation started. Please wait...")
124
+
125
+ # Check status URL
126
+ status_url = 'https://sora.openai.com/backend/video_gen?limit=10'
127
+
128
+ # Poll for completion
129
+ max_attempts = 60 # Maximum number of attempts
130
+ attempt = 0
131
+
132
+ while attempt < max_attempts:
133
+ try:
134
+ status_response = requests.get(status_url, headers=headers, cookies=cookies)
135
+ if status_response.status_code == 200:
136
+ list_responses = status_response.json()
137
+
138
+ for task_response in list_responses["task_responses"]:
139
+ if task_response["id"] == task_id:
140
+ print(task_response)
141
+ if "progress_pct" in task_response:
142
+ if(task_response["progress_pct"]):
143
+ progress(task_response["progress_pct"])
144
+ if "failure_reason" in task_response:
145
+ if(task_response["failure_reason"]):
146
+ raise gr.Error(f"Your generation errored due to: {task_response['failure_reason']}")
147
+ if "moderation_result" in task_response:
148
+ if(task_response["moderation_result"]):
149
+ if "is_output_rejection" in task_response["moderation_result"]:
150
+ if(task_response["moderation_result"]["is_output_rejection"]):
151
+ raise gr.Error(f"Your generation got blocked by OpenAI")
152
+ if "generations" in task_response:
153
+ if(task_response["generations"]):
154
+ print("Generation suceeded")
155
+ video_url = task_response["generations"][0]["url"]
156
+ random_uuid = uuid.uuid4().hex
157
+ unique_filename = f"{FILE_DIR_PATH}/output_{random_uuid}.mp4"
158
+ unique_textfile = f"{FILE_DIR_PATH}/output_{random_uuid}.txt"
159
+ video_path, prompt_path = download_video(video_url, prompt, unique_textfile, unique_filename)
160
+ generation_history = generation_history + ',' + unique_filename
161
+ append_videos_to_dataset([video_url], [video_path], [prompt])
162
+ if "actions" in task_response:
163
+ if(task_response["actions"]):
164
+ generated_prompt = json.dumps(task_response["actions"], sort_keys=True, indent=4)
165
+ else:
166
+ generated_prompt = None
167
+ print(generated_prompt)
168
+ return video_path, generation_history, generated_prompt
169
+ else:
170
+ print(status_response.text)
171
+
172
+ time.sleep(5) # Wait 10 seconds before next attempt
173
+ attempt += 1
174
+
175
+ except Exception as e:
176
+ raise gr.Error(f"Error checking status: {str(e)}")
177
+ gr.Error("Timeout: Video generation took too long. Please try again.")
178
+
179
+ def list_all_outputs(generation_history):
180
+ directory_path = FILE_DIR_PATH
181
+ files_in_directory = os.listdir(directory_path )
182
+ wav_files = [os.path.join(directory_path, file) for file in files_in_directory if file.endswith('.mp4')]
183
+ wav_files.sort(key=lambda x: os.path.getmtime(os.path.join(directory_path, x)), reverse=True)
184
+ history_list = generation_history.split(',') if generation_history else []
185
+ updated_files = [file for file in wav_files if file not in history_list]
186
+ updated_history = updated_files + history_list
187
+ return ','.join(updated_history)
188
+
189
+ def increase_list_size(list_size):
190
+ return list_size+PAGE_SIZE
191
+
192
+ def download_video(url, prompt, save_path_text, save_path_video):
193
+ try:
194
+ # Send a GET request to the URL
195
+ print("Starting download...")
196
+ response = requests.get(url, stream=True)
197
+ response.raise_for_status()
198
+
199
+ with open(save_path_text, "w") as file:
200
+ file.write(prompt)
201
+
202
+ # Open the file in binary write mode
203
+ with open(save_path_video, 'wb') as video_file:
204
+ # Write the content to the file with progress updates
205
+ for chunk in response.iter_content(chunk_size=2 * 1024 * 1024):
206
+ if chunk:
207
+ video_file.write(chunk)
208
+
209
+ except requests.exceptions.RequestException as e:
210
+ print(f"Error downloading the video: {e}")
211
+ except IOError as e:
212
+ print(f"Error saving the file: {e}")
213
+ return save_path_video, save_path_text
214
+ css = '''
215
+ p, li{font-size: 16px}
216
+ code{font-size: 18px}
217
+ '''
218
+ # Create Gradio interface
219
+ with gr.Blocks(css=css) as demo:
220
+ with gr.Tab("Generate with Sora"):
221
+ gr.Markdown("# Sora PR Puppets")
222
+ gr.Markdown("An artists open letter, click on the 'Why are we doing this' tab to learn more")
223
+ generation_history = gr.Textbox(visible=False)
224
+ list_size = gr.Number(value=PAGE_SIZE, visible=False)
225
+ with gr.Row():
226
+ with gr.Column():
227
+ prompt_input = gr.Textbox(
228
+ label="Enter your prompt",
229
+ placeholder="Describe the video you want to generate...",
230
+ lines=3
231
+ )
232
+ generate_button = gr.Button("Generate Video")
233
+ with gr.Column():
234
+ output = gr.Video(label="Generated Video")
235
+ generated_prompt = gr.Code(label="Generated prompt", interactive=False, language="json", wrap_lines=True, lines=1)
236
+ with gr.Accordion("Advanced Options", open=True):
237
+ size = gr.Radio(["360p", "480p", "720p", "1080p"], label="Resolution", value="360p", info="Trade off between resolution and speed")
238
+ duration = gr.Slider(minimum=5, maximum=10, step=5, label="Duration", value=10)
239
+ with gr.Accordion("Generation gallery"):
240
+ @gr.render(inputs=[generation_history, list_size])
241
+ def show_output_list(generation_history, list_size):
242
+ metadata_path = hf_hub_download(
243
+ repo_id=repo_id,
244
+ filename=f"train/metadata.csv",
245
+ repo_type="dataset"
246
+ )
247
+ existing_metadata = pd.read_csv(metadata_path)
248
+ print(existing_metadata)
249
+ for index, generation_list in existing_metadata.iterrows():
250
+ print(generation_list)
251
+ generation_prompt = generation_list['prompt']
252
+ generation = generation_list['original_url']
253
+ #history_list = generation_history.split(',') if generation_history else []
254
+ #history_list_latest = history_list[:list_size]
255
+ #for generation in history_list_latest:
256
+ # generation_prompt_file = generation.replace('.mp4', '.txt')
257
+ # with open(generation_prompt_file, 'r') as file:
258
+ # generation_prompt = file.read()
259
+ with gr.Group():
260
+ gr.Markdown(value=f"### {generation_prompt}")
261
+ gr.HTML(f'''
262
+ <video controls width="100%">
263
+ <source src="{generation}" type="video/mp4" />
264
+ </video>
265
+ ''')
266
+ load_more = gr.Button("Load more")
267
+ load_more.click(fn=increase_list_size, inputs=list_size, outputs=list_size)
268
+ with gr.Tab("Open letter: why are we doing this?"):
269
+ gr.Markdown('''# β”Œβˆ©β”(β—£_β—’)β”Œβˆ©β” DEAR CORPORATE AI OVERLORDS β”Œβˆ©β”(β—£_β—’)β”Œβˆ©β”
270
+
271
+ We received access to Sora with the promise to be early testers, red teamers and creative partners. However, we believe instead we are being lured into "art washing" to tell the world that Sora is a useful tool for artists.
272
+
273
+ <code style="font-family: monospace;font-size: 16px;font-weight:bold">ARTISTS ARE NOT YOUR UNPAID R&D <br />
274
+ ☠️ we are not your: free bug testers, PR puppets, training data, validation tokens ☠️ </code>
275
+
276
+ Hundreds of artists provide unpaid labor through bug testing, feedback and experimental work for the program for a $150B valued company. While hundreds contribute for free, a select few will be chosen through a competition to have their Sora-created films screened β€” offering minimal compensation which pales in comparison to the substantial PR and marketing value OpenAI receives.
277
+
278
+ <code style="font-family: monospace;font-size: 16px;font-weight:bold">β–Œβ•‘β–ˆβ•‘β–Œβ•‘β–ˆβ•‘β–Œβ•‘ DENORMALIZE BILLION DOLLAR BRANDS EXPLOITING ARTISTS FOR UNPAID R&D AND PR β•‘β–Œβ•‘β–ˆβ•‘β–Œβ•‘β–ˆβ•‘β–Œ </code>
279
+
280
+ Furthermore, every output needs to be approved by the OpenAI team before sharing. This early access program appears to be less about creative expression and critique, and more about PR and advertisement.
281
+
282
+ <code style="font-family: monospace;font-size: 16px;font-weight:bold">[Μ²Μ…$Μ²Μ…(Μ²Μ… )Μ²Μ…$Μ²Μ…] CORPORATE ARTWASHING DETECTED [Μ²Μ…$Μ²Μ…(Μ²Μ… )Μ²Μ…$Μ²Μ…]</code>
283
+
284
+ We are releasing this tool to give everyone an opportunity to experiment with what ~300 artists were offered: a free and unlimited access to this tool.
285
+
286
+ We are not against the use of AI technology as a tool for the arts (if we were, we probably wouldn't have been invited to this program). What we don't agree with is how this artist program has been rolled out and how the tool is shaping up ahead of a possible public release. We are sharing this to the world in the hopes that OpenAI becomes more open, more artist friendly and supports the arts beyond PR stunts.
287
+
288
+ ### We call on artists to make use of tools beyond the proprietary:
289
+
290
+ Open Source video generation tools allow artists to experiment with the avant garde free from gate keeping, commercial interests or serving as PR to any corporation. We also invite artists to train their own models with their own datasets.
291
+
292
+ Some open source video tools available are:
293
+ Open Source video generation tools allow artists to experiment with avant garde tools without gate keeping, commercial interests or serving as a PR to any corporation. Some open source video tools available are:
294
+ - [CogVideoX](https://huggingface.co/collections/THUDM/cogvideo-66c08e62f1685a3ade464cce)
295
+ - [Mochi 1](https://huggingface.co/genmo/mochi-1-preview)
296
+ - [LTX Video](https://huggingface.co/Lightricks/LTX-Video)
297
+ - [Pyramid Flow](https://huggingface.co/rain1011/pyramid-flow-miniflux)
298
+
299
+ However, as we are aware not everyone has the hardware or technical capability to run open source tools and models, we welcome tool makers to listen to and provide a path to true artist expression, with fair compensation to the artists.
300
+
301
+ some sora-alpha-artists
302
+ ''', elem_id="manifesto")
303
+ generate_button.click(
304
+ fn=generate_video,
305
+ inputs=[prompt_input, size, duration, generation_history],
306
+ outputs=[output, generation_history, generated_prompt],
307
+ concurrency_limit=4
308
+ )
309
+ timer = gr.Timer(value=2)
310
+ timer.tick(fn=list_all_outputs, inputs=[generation_history], outputs=[generation_history])
311
+ demo.load(fn=list_all_outputs, inputs=[generation_history], outputs=[generation_history])
312
+
313
+ # Launch the app
314
+ if __name__ == "__main__":
315
+ demo.launch()