akhaliq HF Staff commited on
Commit
29ea35b
Β·
verified Β·
1 Parent(s): 5202a13

Update Gradio app with multiple files

Browse files
Files changed (2) hide show
  1. app.py +22 -75
  2. requirements.txt +2 -2
app.py CHANGED
@@ -1,5 +1,4 @@
1
  import gradio as gr
2
- import openai
3
  import os
4
  import json
5
  import time
@@ -8,43 +7,15 @@ from typing import Optional, Tuple, Dict, Any
8
  import tempfile
9
  import base64
10
  import re
 
11
 
12
- # Initialize OpenAI client with Poe API configuration
13
- client = openai.OpenAI(
14
- api_key=os.getenv("POE_API_KEY"), # Set your Poe API key as environment variable
15
- base_url="https://api.poe.com/v1",
 
16
  )
17
 
18
- def format_sora_prompt(
19
- prompt: str,
20
- duration: int = 8,
21
- size: str = "1280x720"
22
- ) -> str:
23
- """Format the prompt with Sora-2 specific parameters."""
24
- formatted_prompt = f"{prompt}\n\n--duration {duration} --size {size}"
25
- return formatted_prompt
26
-
27
- def extract_video_url(content: str) -> Optional[str]:
28
- """Extract video URL from the response content."""
29
- # Try to find direct video URL
30
- url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+\.(?:mp4|mov|avi|webm)'
31
- urls = re.findall(url_pattern, content)
32
- if urls:
33
- return urls[0]
34
-
35
- # Try to find any URL that might be a video
36
- general_url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+'
37
- urls = re.findall(general_url_pattern, content)
38
- for url in urls:
39
- if any(vid_keyword in url.lower() for vid_keyword in ['video', 'mp4', 'mov', 'media', 'cdn']):
40
- return url
41
-
42
- # Return first URL if found
43
- if urls:
44
- return urls[0]
45
-
46
- return None
47
-
48
  def generate_video(
49
  prompt: str,
50
  duration: int = 8,
@@ -52,59 +23,35 @@ def generate_video(
52
  api_key: Optional[str] = None
53
  ) -> Tuple[Optional[str], str]:
54
  """
55
- Generate video using Sora-2 through Poe API.
56
  Returns tuple of (video_path, status_message).
57
  """
58
  try:
59
  # Use provided API key or environment variable
60
  if api_key:
61
- temp_client = openai.OpenAI(
 
62
  api_key=api_key,
63
- base_url="https://api.poe.com/v1",
64
  )
65
  else:
66
  temp_client = client
67
- if not os.getenv("POE_API_KEY") and not api_key:
68
- return None, "❌ Please set POE_API_KEY environment variable."
69
-
70
- # Format prompt with parameters
71
- formatted_prompt = format_sora_prompt(prompt, duration, size)
72
 
73
- # Call Sora-2 through Poe API
74
- chat = temp_client.chat.completions.create(
75
- model="Sora-2",
76
- messages=[{"role": "user", "content": formatted_prompt}],
77
  )
78
 
79
- # Extract the response content
80
- content = chat.choices[0].message.content
 
 
81
 
82
- # Try to extract video URL from response
83
- video_url = extract_video_url(content)
84
-
85
- if video_url:
86
- # Download the video
87
- try:
88
- headers = {
89
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
90
- }
91
- video_response = requests.get(video_url, headers=headers, timeout=60)
92
- video_response.raise_for_status()
93
-
94
- # Save to temporary file
95
- with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp_file:
96
- tmp_file.write(video_response.content)
97
- video_path = tmp_file.name
98
-
99
- status_message = f"βœ… Video generated successfully!"
100
- return video_path, status_message
101
-
102
- except requests.exceptions.RequestException as e:
103
- return None, f"❌ Failed to download video: {str(e)}"
104
- else:
105
- # If no URL found, the response might contain the video data directly
106
- # or might need different parsing
107
- return None, f"❌ Could not extract video from response. Response: {content[:200]}..."
108
 
109
  except Exception as e:
110
  error_msg = f"❌ Error generating video: {str(e)}"
 
1
  import gradio as gr
 
2
  import os
3
  import json
4
  import time
 
7
  import tempfile
8
  import base64
9
  import re
10
+ from huggingface_hub import InferenceClient
11
 
12
+ # Initialize Hugging Face Inference Client with fal-ai provider
13
+ client = InferenceClient(
14
+ provider="fal-ai",
15
+ api_key=os.environ["HF_TOKEN"],
16
+ bill_to="huggingface",
17
  )
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  def generate_video(
20
  prompt: str,
21
  duration: int = 8,
 
23
  api_key: Optional[str] = None
24
  ) -> Tuple[Optional[str], str]:
25
  """
26
+ Generate video using Sora-2 through Hugging Face Inference API with fal-ai provider.
27
  Returns tuple of (video_path, status_message).
28
  """
29
  try:
30
  # Use provided API key or environment variable
31
  if api_key:
32
+ temp_client = InferenceClient(
33
+ provider="fal-ai",
34
  api_key=api_key,
35
+ bill_to="huggingface",
36
  )
37
  else:
38
  temp_client = client
39
+ if not os.environ.get("HF_TOKEN") and not api_key:
40
+ return None, "❌ Please set HF_TOKEN environment variable."
 
 
 
41
 
42
+ # Call Sora-2 through Hugging Face Inference API
43
+ video_bytes = temp_client.text_to_video(
44
+ prompt,
45
+ model="akhaliq/sora-2",
46
  )
47
 
48
+ # Save to temporary file
49
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp_file:
50
+ tmp_file.write(video_bytes)
51
+ video_path = tmp_file.name
52
 
53
+ status_message = f"βœ… Video generated successfully!"
54
+ return video_path, status_message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  except Exception as e:
57
  error_msg = f"❌ Error generating video: {str(e)}"
requirements.txt CHANGED
@@ -1,5 +1,5 @@
1
  gradio>=5.0.0
2
- openai>=1.0.0
3
  requests>=2.31.0
4
  numpy>=1.24.0
5
- Pillow>=10.0.0
 
 
1
  gradio>=5.0.0
 
2
  requests>=2.31.0
3
  numpy>=1.24.0
4
+ Pillow>=10.0.0
5
+ huggingface-hub>=0.20.0