Spaces:
Running
Running
File size: 20,757 Bytes
b87c1b6 d872fa5 bc2cb72 275a10f b78c4e1 10616f8 b87c1b6 d872fa5 b87c1b6 29ea35b 6b2dd9c 29ea35b d872fa5 0a20908 275a10f b87c1b6 275a10f b87c1b6 275a10f 5f47e36 e34f60e 275a10f b87c1b6 275a10f d872fa5 24c348f b87c1b6 d872fa5 b87c1b6 275a10f d872fa5 b87c1b6 29ea35b 24c348f e34f60e b87c1b6 e34f60e b87c1b6 e34f60e b87c1b6 e34f60e b87c1b6 e34f60e b87c1b6 e34f60e b87c1b6 5f47e36 b87c1b6 5f47e36 b87c1b6 e34f60e b87c1b6 e34f60e d872fa5 e34f60e b87c1b6 d872fa5 e34f60e d872fa5 10616f8 8d392f5 10616f8 b78c4e1 10616f8 b87c1b6 8d392f5 10616f8 8d392f5 10616f8 8d392f5 10616f8 8d392f5 6b2dd9c b78c4e1 0a20908 b78c4e1 b87c1b6 32719a5 6b2dd9c b78c4e1 b4b4b69 b78c4e1 8d392f5 10616f8 fea8f7a 6b2dd9c b87c1b6 10616f8 6b2dd9c b87c1b6 10616f8 0a20908 10616f8 0a20908 10616f8 0a20908 b87c1b6 10616f8 ec68f4a 0a20908 10616f8 0a20908 10616f8 0a20908 10616f8 0a20908 10616f8 ec68f4a 10616f8 8d392f5 0a20908 10616f8 2a343c0 10616f8 0a20908 10616f8 ec68f4a 10616f8 b87c1b6 6b2dd9c d872fa5 275a10f b87c1b6 6b2dd9c dc8694f 10616f8 d82f24c 10616f8 |
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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 |
import gradio as gr
import os
import tempfile
import shutil
from typing import Optional, Tuple, Union
from huggingface_hub import InferenceClient
from pathlib import Path
# Initialize Hugging Face Inference Client with fal-ai provider
client = InferenceClient(
provider="fal-ai",
api_key=os.environ.get("HF_TOKEN"),
bill_to="huggingface",
)
# Share button HTML components
community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
<path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
<path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
</svg>"""
loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
style="color: #ffffff;"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
share_js = """async () => {
async function uploadFile(file){
const UPLOAD_URL = 'https://huggingface.co/uploads';
const response = await fetch(UPLOAD_URL, {
method: 'POST',
headers: {
'Content-Type': file.type,
'X-Requested-With': 'XMLHttpRequest',
},
body: file,
});
const url = await response.text();
return url;
}
const gradioEl = document.querySelector('body > gradio-app');
const videoEl = gradioEl.querySelector('#text-to-video video');
const promptTxt = gradioEl.querySelector('#prompt-text-input textarea').value;
const shareBtnEl = gradioEl.querySelector('#share-btn');
const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
if(!videoEl || !videoEl.src){
alert('Please generate a video first!');
return;
}
shareBtnEl.style.pointerEvents = 'none';
shareIconEl.style.display = 'none';
loadingIconEl.style.removeProperty('display');
try {
const res = await fetch(videoEl.src);
const blob = await res.blob();
const videoId = Date.now() % 1000;
const fileName = `sora-2-video-${videoId}.mp4`;
const file = new File([blob], fileName, { type: 'video/mp4' });
const url = await uploadFile(file);
const descriptionMd = `
### Generated Video
<video controls width="640" height="360">
<source src="${url}" type="video/mp4">
</video>
**Prompt:** ${promptTxt}
Generated using Sora-2 model`;
const params = new URLSearchParams({
title: `Sora-2 Video: ${promptTxt.substring(0, 50)}...`,
description: descriptionMd,
});
const paramsStr = params.toString();
window.open(`https://huggingface.co/spaces/akhaliq/sora-2/discussions/new?${paramsStr}`, '_blank');
} catch (error) {
console.error('Error sharing:', error);
alert('Error sharing video. Please try again.');
} finally {
shareBtnEl.style.removeProperty('pointer-events');
shareIconEl.style.removeProperty('display');
loadingIconEl.style.display = 'none';
}
}"""
share_img_js = """async () => {
async function uploadFile(file){
const UPLOAD_URL = 'https://huggingface.co/uploads';
const response = await fetch(UPLOAD_URL, {
method: 'POST',
headers: {
'Content-Type': file.type,
'X-Requested-With': 'XMLHttpRequest',
},
body: file,
});
const url = await response.text();
return url;
}
const gradioEl = document.querySelector('body > gradio-app');
const videoEl = gradioEl.querySelector('#image-to-video video');
const promptTxt = gradioEl.querySelector('#img-prompt-text-input textarea').value;
const shareBtnEl = gradioEl.querySelector('#share-btn-img');
const shareIconEl = gradioEl.querySelector('#share-btn-img-share-icon');
const loadingIconEl = gradioEl.querySelector('#share-btn-img-loading-icon');
if(!videoEl || !videoEl.src){
alert('Please generate a video first!');
return;
}
shareBtnEl.style.pointerEvents = 'none';
shareIconEl.style.display = 'none';
loadingIconEl.style.removeProperty('display');
try {
const res = await fetch(videoEl.src);
const blob = await res.blob();
const videoId = Date.now() % 1000;
const fileName = `sora-2-img-video-${videoId}.mp4`;
const file = new File([blob], fileName, { type: 'video/mp4' });
const url = await uploadFile(file);
const descriptionMd = `
### Generated Video from Image
<video controls width="640" height="360">
<source src="${url}" type="video/mp4">
</video>
**Prompt:** ${promptTxt}
Generated using Sora-2 Image-to-Video model`;
const params = new URLSearchParams({
title: `Sora-2 Image-to-Video: ${promptTxt.substring(0, 50)}...`,
description: descriptionMd,
});
const paramsStr = params.toString();
window.open(`https://huggingface.co/spaces/akhaliq/sora-2/discussions/new?${paramsStr}`, '_blank');
} catch (error) {
console.error('Error sharing:', error);
alert('Error sharing video. Please try again.');
} finally {
shareBtnEl.style.removeProperty('pointer-events');
shareIconEl.style.removeProperty('display');
loadingIconEl.style.display = 'none';
}
}"""
def cleanup_temp_files():
"""Clean up old temporary video files to prevent storage overflow."""
try:
temp_dir = tempfile.gettempdir()
# Clean up old .mp4 files in temp directory
for file_path in Path(temp_dir).glob("*.mp4"):
try:
# Remove files older than 5 minutes
import time
if file_path.stat().st_mtime < (time.time() - 300):
file_path.unlink(missing_ok=True)
except Exception:
pass
except Exception as e:
print(f"Cleanup error: {e}")
def generate_video(
prompt: str,
duration: int = 8,
size: str = "1280x720",
api_key: Optional[str] = None
) -> Tuple[Optional[str], str]:
"""Generate video using Sora-2 through Hugging Face Inference API with fal-ai provider."""
cleanup_temp_files()
try:
if api_key:
temp_client = InferenceClient(
provider="fal-ai",
api_key=api_key,
bill_to="huggingface",
)
else:
temp_client = client
if not os.environ.get("HF_TOKEN") and not api_key:
return None, "β Please set HF_TOKEN environment variable."
video_bytes = temp_client.text_to_video(
prompt,
model="akhaliq/sora-2",
)
temp_file = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
try:
temp_file.write(video_bytes)
temp_file.flush()
video_path = temp_file.name
finally:
temp_file.close()
return video_path, "β
Video generated successfully!"
except Exception as e:
return None, f"β Error generating video: {str(e)}"
def generate_video_from_image(
image: Union[str, bytes],
prompt: str,
api_key: Optional[str] = None
) -> Tuple[Optional[str], str]:
"""Generate a video from a single input image + prompt using Sora-2 image-to-video."""
cleanup_temp_files()
if not prompt or prompt.strip() == "":
return None, "β Please enter a prompt"
try:
if api_key:
temp_client = InferenceClient(
provider="fal-ai",
api_key=api_key,
bill_to="huggingface",
)
else:
temp_client = client
if not os.environ.get("HF_TOKEN") and not api_key:
return None, "β Please set HF_TOKEN environment variable."
if isinstance(image, str):
with open(image, "rb") as f:
input_image = f.read()
elif isinstance(image, (bytes, bytearray)):
input_image = image
else:
return None, "β Invalid image input. Please upload an image."
video_bytes = temp_client.image_to_video(
input_image,
prompt=prompt,
model="akhaliq/sora-2-image-to-video",
)
temp_file = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
try:
temp_file.write(video_bytes)
temp_file.flush()
video_path = temp_file.name
finally:
temp_file.close()
return video_path, "β
Video generated from image successfully!"
except Exception as e:
return None, f"β Error generating video from image: {str(e)}"
def generate_with_auth(
prompt: str,
profile: gr.OAuthProfile | None
) -> Tuple[Optional[str], str]:
"""Wrapper function that checks if user is logged in before generating video."""
if profile is None:
raise gr.Error("Click Sign in with Hugging Face button to use this app for free")
if not prompt or prompt.strip() == "":
return None, "β Please enter a prompt"
return generate_video(
prompt,
duration=8,
size="1280x720",
api_key=None
)
def generate_with_auth_image(
prompt: str,
image_path: Optional[str],
profile: gr.OAuthProfile | None
) -> Tuple[Optional[str], str]:
"""Checks login status then calls image->video generator."""
if profile is None:
raise gr.Error("Click Sign in with Hugging Face button to use this app for free")
if not image_path:
return None, "β Please upload an image"
return generate_video_from_image(image=image_path, prompt=prompt, api_key=None)
def create_ui():
css = '''
.logo-dark{display: none}
.dark .logo-dark{display: block !important}
.dark .logo-light{display: none}
#sub_title{margin-top: -20px !important}
.animate-spin {
animation: spin 1s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
#share-btn-container, #share-btn-container-img {
display: flex;
padding-left: 0.5rem !important;
padding-right: 0.5rem !important;
background-color: #000000;
justify-content: center;
align-items: center;
border-radius: 9999px !important;
width: 13rem;
margin-top: 10px;
margin-left: auto;
margin-right: auto;
}
#share-btn-container .styler, #share-btn-container-img .styler{
background-color: #000000;
}
#share-btn, #share-btn-img {
all: initial;
color: #ffffff;
font-weight: 600;
cursor:pointer;
font-family: 'IBM Plex Sans', sans-serif;
margin-left: 0.5rem !important;
padding-top: 0.25rem !important;
padding-bottom: 0.25rem !important;
right:0;
}
#share-btn *, #share-btn-img * {
all: unset;
}
#share-btn-container div:nth-child(-n+2), #share-btn-container-img div:nth-child(-n+2){
width: auto !important;
min-height: 0px !important;
}
#share-btn-container .wrap, #share-btn-container-img .wrap {
display: none !important;
}
'''
with gr.Blocks(title="Sora-2", theme=gr.themes.Soft(), css=css) as demo:
gr.HTML("""
<div style="text-align: center; max-width: 800px; margin: 0 auto;">
<h1 style="font-size: 2.5em; margin-bottom: 0.5em;">
π¬ Sora-2
</h1>
<p style="font-size: 1.1em; color: #666; margin-bottom: 20px;">Generate stunning videos using OpenAI's Sora-2 model</p>
<p style='color: orange;'>β οΈ You must Sign in with Hugging Face using the button to use this app.</p>
<p style="font-size: 0.9em; color: #999; margin-top: 15px;">
Built with <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #667eea;">anycoder</a>
</p>
</div>
""")
# Add login button - required for OAuth
gr.LoginButton()
# Text -> Video
with gr.Row():
with gr.Column(scale=1):
prompt_input = gr.Textbox(
label="Enter your prompt",
placeholder="Describe the video you want to create...",
lines=4,
elem_id="prompt-text-input"
)
generate_btn = gr.Button("π₯ Generate Video", variant="primary", size="lg")
with gr.Column(scale=1):
video_output = gr.Video(
label="Generated Video",
height=400,
interactive=False,
show_download_button=True,
elem_id="text-to-video"
)
status_output = gr.Textbox(label="Status", interactive=False, visible=True)
# Share button for text-to-video
with gr.Group(elem_id="share-btn-container"):
community_icon = gr.HTML(community_icon_html)
loading_icon = gr.HTML(loading_icon_html)
share_button = gr.Button("Share to community", elem_id="share-btn")
generate_btn.click(
fn=generate_with_auth,
inputs=[prompt_input],
outputs=[video_output, status_output],
)
share_button.click(
None,
[],
[],
js=share_js,
)
# Image -> Video UI
gr.HTML("""
<div style="text-align: center; margin: 40px 0 10px;">
<h3 style="margin-bottom: 8px;">πΌοΈ β π¬ Image β Video (beta)</h3>
<p style="color:#666; margin:0;">Turn a single image into a short video with a guiding prompt.</p>
</div>
""")
with gr.Row():
with gr.Column(scale=1):
img_prompt_input = gr.Textbox(
label="Describe how the scene should evolve",
placeholder="e.g., The cat starts to dance and spins playfully",
lines=3,
elem_id="img-prompt-text-input"
)
image_input = gr.Image(label="Upload an image", type="filepath")
generate_img_btn = gr.Button("π₯ Generate from Image", variant="primary")
with gr.Column(scale=1):
video_output_img = gr.Video(
label="Generated Video (from Image)",
height=400,
interactive=False,
show_download_button=True,
elem_id="image-to-video"
)
status_output_img = gr.Textbox(label="Status", interactive=False, visible=True)
# Share button for image-to-video
with gr.Group(elem_id="share-btn-container-img"):
community_icon_img = gr.HTML(community_icon_html.replace('share-btn-share-icon', 'share-btn-img-share-icon'))
loading_icon_img = gr.HTML(loading_icon_html.replace('share-btn-loading-icon', 'share-btn-img-loading-icon'))
share_button_img = gr.Button("Share to community", elem_id="share-btn-img")
generate_img_btn.click(
fn=generate_with_auth_image,
inputs=[img_prompt_input, image_input],
outputs=[video_output_img, status_output_img],
)
share_button_img.click(
None,
[],
[],
js=share_img_js,
)
# Example usage guidance
gr.Examples(
examples=[
["A majestic golden eagle soaring through a vibrant sunset sky"],
],
inputs=prompt_input,
outputs=video_output,
fn=generate_video,
cache_examples=False,
api_name=False,
show_api=False,
)
return demo
if __name__ == "__main__":
try:
cleanup_temp_files()
if os.path.exists("gradio_cached_examples"):
shutil.rmtree("gradio_cached_examples", ignore_errors=True)
except Exception as e:
print(f"Initial cleanup error: {e}")
app = create_ui()
# Configure queue with optimized settings for OAuth-enabled app
app.queue(
status_update_rate="auto",
api_open=False, # Disable public API access for security
default_concurrency_limit=None # Allow multiple concurrent requests
)
app.launch(
show_api=False,
enable_monitoring=False,
quiet=True,
ssr_mode=True
) |