Skip to content

Latest commit

 

History

History
74 lines (60 loc) · 1.83 KB

File metadata and controls

74 lines (60 loc) · 1.83 KB

Coding Snippets for my own reference

try except blocks to catch 3 types of errors

try:
    # your code here
    response = requests.request("POST", url, headers=headers, data=payload)
    response.raise_for_status()
    
except KeyError as e:
    print(f"[ERROR] KeyError: Missing key {e}")
except requests.exceptions.RequestException as e:
    print(f"[ERROR] Request Failed: {e}")
except Exception as e:
    print(f"[ERROR] Unexpected Error: {str(e)}")

Check if variable exists and raise ValueError

api_key = os.getenv('CANTONESE_AI_API_KEY')
content_json_file = os.getenv('CONTENT_JSON_FILE')
voice_id = os.getenv('VOICE_ID')

if not api_key:
    raise ValueError("CANTONESE_AI_API_KEY is missing in .env")
if not content_json_file:
    raise ValueError("CONTENT_JSON_FILE is missing in .env")
if not voice_id:
    raise ValueError("VOICE_ID is missing in .env")
audio_base64 = response_data.get('file')
if audio_base64 is None:
    raise ValueError("API Response missing 'file' key")

Loading JSON + safe .get() usage

with open('content.json', 'r', encoding='utf-8') as f:
    content = json.load(f)

for item in content:
    item_id   = item.get('id')
    category  = item.get('category')
    text      = item.get('text')

    if item_id is None or category is None or text is None:
        print(f"[ERROR] Missing required field in item: {item}")
        continue

Sanitize filename using regex

raw_name = f"{item_id}_{category}"
safe_name = re.sub(r'[^a-zA-Z0-9_\u4e00-\u9fff]', '_', raw_name)
safe_filename = f"audios/{safe_name}.mp3"

Check if file already exists and skip

if os.path.exists(safe_filename):
    print(f"[SKIP] {safe_filename} already exists")
    continue

Rate limiting using time.sleep()

finally:
    time.sleep(1.5)   # 1.5 seconds delay between requests