Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,15 @@ paths:
设置 OpenAI API 密钥为环境变量:
```bash
export OPENAI_API_KEY="your-api-key"

```
或者 自己新建.env文件

```txt
OPENAI_API_KEY=你的key
WHISPER_URL=https://api.openai.com/v1/audio/transcriptions
CHAT_URL=https://api.openai.com/v1/chat/completions
```

---

Expand Down
5 changes: 4 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,7 @@ asyncio>=3.4.3
concurrent-log-handler>=0.9.20

# Optional (for advanced features)
stability-sdk>=0.3.0 # For Stable Diffusion integration
stability-sdk>=0.3.0 # For Stable Diffusion integration

# for networked applications
tenacity>=8.0.1
38 changes: 28 additions & 10 deletions talk2scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
import yaml
from moviepy.editor import *
from moviepy.config import change_settings
from dotenv import load_dotenv
from tenacity import retry, stop_after_attempt, wait_fixed, RetryError

# Load environment variables from .env file
load_dotenv()

# Configure FFmpeg path
change_settings({"FFMPEG_BINARY": "/usr/bin/ffmpeg"})
Expand Down Expand Up @@ -45,27 +50,36 @@ def generate_scenes(self, text: str) -> List[Dict]:
# ======================== Core Implementations ========================
class WhisperTranscriber(ITranscriber):
"""OpenAI Whisper transcription implementation."""

@retry(stop=stop_after_attempt(3), wait=wait_fixed(10))
def transcribe(self, audio_path: str) -> str:
try:
with open(audio_path, "rb") as f:
with open(audio_path, "rb") as f:
f.seek(0) # 确保文件指针位置正确
try:
response = requests.post(
"https://api.openai.com/v1/audio/transcriptions",
os.getenv('WHISPER_URL', 'https://api.openai.com/v1/audio/transcriptions'),
headers={"Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}"},
files={"file": f},
data={"model": "whisper-1"}
data={"model": os.getenv('WHISPER_MODEL', 'whisper-1')},
timeout=30 # 超时设置已存在
)
response.raise_for_status()
return response.json()["text"]
except Exception as e:
logger.error(f"Transcription failed: {str(e)}")
raise
except requests.exceptions.Timeout as te:
logger.error(f"Transcription timed out: {str(te)}")
raise ValueError("请求超时,请稍后重试") from te
except requests.exceptions.RequestException as e:
logger.error(f"Transcription failed: {str(e)}")
raise

class GPTSceneGenerator(ILLMService):
"""GPT-4 scene generation implementation."""

@retry(stop=stop_after_attempt(3), wait=wait_fixed(10))
def generate_scenes(self, text: str) -> List[Dict]:
try:
response = requests.post(
"https://api.openai.com/v1/chat/completions",
os.getenv('CHAT_URL', 'https://api.openai.com/v1/chat/completions'),
headers={
"Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}",
"Content-Type": "application/json"
Expand All @@ -79,11 +93,15 @@ def generate_scenes(self, text: str) -> List[Dict]:
"role": "user",
"content": text
}]
}
},
timeout=30 # Add timeout to prevent indefinite hanging
)
response.raise_for_status()
return json.loads(response.json()["choices"][0]["message"]["content"])
except Exception as e:
except requests.exceptions.Timeout as te:
logger.error(f"Scene generation timed out: {str(te)}")
raise ValueError("请求超时,请稍后重试") from te
except requests.exceptions.RequestException as e:
logger.error(f"Scene generation failed: {str(e)}")
raise

Expand Down