|
| 1 | +import json |
| 2 | +import logging |
| 3 | +from pathlib import Path |
| 4 | +from typing import Literal |
| 5 | + |
| 6 | +from pydub import AudioSegment |
| 7 | + |
| 8 | +from neuralnoise.models import StudioConfig |
| 9 | +from neuralnoise.studio import PodcastStudio |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +def generate_podcast_episode( |
| 15 | + name: str, |
| 16 | + content: str, |
| 17 | + config: StudioConfig | None = None, |
| 18 | + config_path: str | Path | None = None, |
| 19 | + format: Literal["wav", "mp3", "ogg"] = "wav", |
| 20 | + only_script: bool = False, |
| 21 | +) -> AudioSegment | None: |
| 22 | + """Generate a podcast episode from a given content. |
| 23 | +
|
| 24 | + Args: |
| 25 | + name: Name of the podcast episode. |
| 26 | + content: Content to generate the podcast episode from. |
| 27 | + config: Studio configuration (optional). |
| 28 | + config_path: Path to the studio configuration file (optional). |
| 29 | + format: Format of the podcast episode. |
| 30 | + only_script: Whether to only generate the script and not the podcast. |
| 31 | + """ |
| 32 | + # Create output directory |
| 33 | + output_dir = Path("output") / name |
| 34 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 35 | + |
| 36 | + # Load configuration |
| 37 | + if config_path: |
| 38 | + logger.info("🔧 Loading configuration from %s", config_path) |
| 39 | + with open(config_path, "r") as f: |
| 40 | + config = StudioConfig.model_validate_json(f.read()) |
| 41 | + |
| 42 | + if not config: |
| 43 | + raise ValueError("No studio configuration provided") |
| 44 | + |
| 45 | + studio = PodcastStudio(work_dir=output_dir, config=config) |
| 46 | + |
| 47 | + # Generate the script |
| 48 | + script_path = output_dir / "script.json" |
| 49 | + |
| 50 | + if script_path.exists(): |
| 51 | + logger.info("💬 Loading cached script") |
| 52 | + script = json.loads(script_path.read_text()) |
| 53 | + else: |
| 54 | + logger.info("💬 Generating podcast script") |
| 55 | + script = studio.generate_script(content) |
| 56 | + |
| 57 | + script_path.write_text(json.dumps(script, ensure_ascii=False)) |
| 58 | + |
| 59 | + if only_script: |
| 60 | + return None |
| 61 | + |
| 62 | + # Generate audio segments and create the podcast |
| 63 | + logger.info("🎙️ Recording podcast episode") |
| 64 | + podcast = studio.generate_podcast_from_script(script) |
| 65 | + |
| 66 | + # Export podcast |
| 67 | + podcast_filepath = output_dir / f"output.{format}" |
| 68 | + logger.info("️💾 Exporting podcast to %s", podcast_filepath) |
| 69 | + podcast.export(podcast_filepath, format=format) |
| 70 | + |
| 71 | + logger.info("✅ Podcast generation complete") |
| 72 | + |
| 73 | + return podcast |
0 commit comments