Here is a complete Python script to transcribe all voice memos in the `memos/` directory and save them into `transcripts/`.

### Prerequisites

Make sure you have the `requests` library installed:

```bash
pip install requests
```

### Python Script (`transcribe_memos.py`)

```python
import os
import sys
from pathlib import Path
import requests

# Supported audio formats
AUDIO_EXTENSIONS = {".mp3", ".wav", ".m4a", ".ogg", ".flac", ".aac", ".webm"}

# Directories
MEMOS_DIR = Path("memos")
TRANSCRIPTS_DIR = Path("transcripts")

# API Configuration
AI_BUILDER_TOKEN = os.environ.get("AI_BUILDER_TOKEN")
API_ENDPOINT = os.environ.get(
    "AI_BUILDER_API_URL", 
    "https://api.ai-builder.space/v1/audio/transcriptions"
)


def transcribe_file(file_path: Path, token: str) -> str:
    """Send an audio file to the speech recognition API and return the transcript."""
    headers = {
        "Authorization": f"Bearer {token}",
    }

    with open(file_path, "rb") as audio_file:
        files = {
            "file": (file_path.name, audio_file)
        }
        # Standard transcription payload (Whisper-compatible)
        data = {
            "model": "whisper-1"
        }

        response = requests.post(
            API_ENDPOINT,
            headers=headers,
            files=files,
            data=data,
            timeout=120  # Audio processing can take some time
        )

    response.raise_for_status()
    result = response.json()

    # Handles responses returning {"text": "..."} or raw transcription fields
    return result.get("text") or result.get("transcription", "")


def main():
    if not AI_BUILDER_TOKEN:
        print("Error: Environment variable 'AI_BUILDER_TOKEN' is not set.", file=sys.stderr)
        sys.exit(1)

    if not MEMOS_DIR.exists() or not MEMOS_DIR.is_dir():
        print(f"Error: Source directory '{MEMOS_DIR}' does not exist.", file=sys.stderr)
        sys.exit(1)

    # Ensure output directory exists
    TRANSCRIPTS_DIR.mkdir(parents=True, exist_ok=True)

    # Gather audio files
    audio_files = [f for f in MEMOS_DIR.iterdir() if f.suffix.lower() in AUDIO_EXTENSIONS]

    if not audio_files:
        print(f"No audio files found in '{MEMOS_DIR}'.")
        return

    print(f"Found {len(audio_files)} audio file(s) to transcribe.\n")

    for index, file_path in enumerate(audio_files, start=1):
        output_txt_path = TRANSCRIPTS_DIR / f"{file_path.stem}.txt"
        print(f"[{index}/{len(audio_files)}] Transcribing: {file_path.name}...")

        try:
            transcript = transcribe_file(file_path, AI_BUILDER_TOKEN)

            # Write the result to a text file
            output_txt_path.write_text(transcript.strip(), encoding="utf-8")
            print(f"  ✓ Saved to: {output_txt_path}")

        except requests.exceptions.HTTPError as http_err:
            print(f"  ✗ HTTP Error ({response_code(http_err)}): {http_err}", file=sys.stderr)
        except Exception as err:
            print(f"  ✗ Failed to transcribe {file_path.name}: {err}", file=sys.stderr)

    print("\nBatch transcription completed.")


def response_code(exc):
    return exc.response.status_code if exc.response is not None else "Unknown"


if __name__ == "__main__":
    main()
```

### How to Run

1. Set your token:
   ```bash
   export AI_BUILDER_TOKEN="your_api_token_here"
   ```
2. Run the script:
   ```bash
   python transcribe_memos.py
   ```

### Notes
* If your AI Builder Space workspace uses a custom base URL or custom model identifier, you can override the endpoint without changing the code by setting `export AI_BUILDER_API_URL="https://your-custom-endpoint/..."`.
* Each transcript is saved with the identical basename (e.g. `memos/meeting_01.mp3` becomes `transcripts/meeting_01.txt`).