From d52eb10567ffb19bb572d0bf7c2dd6766ebf3d72 Mon Sep 17 00:00:00 2001 From: wsq_star Date: Tue, 25 Feb 2025 15:05:22 +0000 Subject: [PATCH] network retry --- README.md | 8 ++++++++ requirements.txt | 5 ++++- talk2scene.py | 38 ++++++++++++++++++++++++++++---------- 3 files changed, 40 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 06deebf..3a64579 100644 --- a/README.md +++ b/README.md @@ -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 +``` --- diff --git a/requirements.txt b/requirements.txt index 6aa4778..2744257 100644 --- a/requirements.txt +++ b/requirements.txt @@ -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 \ No newline at end of file +stability-sdk>=0.3.0 # For Stable Diffusion integration + +# for networked applications +tenacity>=8.0.1 \ No newline at end of file diff --git a/talk2scene.py b/talk2scene.py index 024571a..704e025 100644 --- a/talk2scene.py +++ b/talk2scene.py @@ -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"}) @@ -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" @@ -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