File size: 6,120 Bytes
74c62a2
 
 
 
 
857bebe
 
74c62a2
 
 
e2eee76
 
68b189e
 
74c62a2
e2eee76
 
 
 
 
74c62a2
e2eee76
 
74c62a2
68b189e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74c62a2
 
68b189e
 
 
74c62a2
 
68b189e
 
 
 
74c62a2
68b189e
 
 
74c62a2
68b189e
 
 
 
 
 
 
 
 
 
 
74c62a2
 
68b189e
 
 
 
 
 
 
 
 
 
 
 
 
74c62a2
 
68b189e
 
 
74c62a2
68b189e
 
74c62a2
68b189e
 
 
 
 
 
 
 
 
74c62a2
 
68b189e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74c62a2
68b189e
 
74c62a2
68b189e
 
 
 
 
 
 
74c62a2
68b189e
 
 
74c62a2
68b189e
74c62a2
 
68b189e
 
 
 
 
 
74c62a2
68b189e
 
 
 
 
 
 
 
 
74c62a2
68b189e
74c62a2
68b189e
 
 
74c62a2
 
68b189e
 
 
 
 
 
74c62a2
 
68b189e
74c62a2
68b189e
 
 
 
74c62a2
68b189e
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
"""
Audiobook creation routes for the CSM-1B TTS API.
"""
import os
import uuid
import json
import shutil
import logging
from datetime import datetime
from typing import Optional, List
from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, UploadFile, File
from fastapi.responses import FileResponse
from pydantic import BaseModel
from motor.motor_asyncio import AsyncIOMotorDatabase

from app.db import get_db, AUDIOBOOKS_COLLECTION
from app.config import AUDIO_DIR, TEXT_DIR, TEMP_DIR

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

router = APIRouter()

class AudiobookBase(BaseModel):
    title: str
    author: str
    voice_id: str
    status: str = "pending"
    created_at: datetime = datetime.utcnow()
    updated_at: datetime = datetime.utcnow()

class Audiobook(AudiobookBase):
    id: str
    file_path: Optional[str] = None
    text_path: Optional[str] = None
    error: Optional[str] = None

class TextChunk(BaseModel):
    text: str
    start_time: float
    end_time: float

async def process_audiobook(book_id: str, db: AsyncIOMotorDatabase):
    """Process the audiobook in the background."""
    try:
        # Update status to processing
        await db[AUDIOBOOKS_COLLECTION].update_one(
            {"id": book_id},
            {"$set": {"status": "processing", "updated_at": datetime.utcnow()}}
        )

        # Get the audiobook data
        audiobook = await db[AUDIOBOOKS_COLLECTION].find_one({"id": book_id})
        if not audiobook:
            raise HTTPException(status_code=404, detail="Audiobook not found")

        # TODO: Implement TTS processing logic here
        # For now, we'll just simulate processing
        logger.info(f"Processing audiobook {book_id}")

        # Update status to completed
        await db[AUDIOBOOKS_COLLECTION].update_one(
            {"id": book_id},
            {
                "$set": {
                    "status": "completed",
                    "file_path": f"{AUDIO_DIR}/{book_id}.mp3",
                    "updated_at": datetime.utcnow()
                }
            }
        )

    except Exception as e:
        logger.error(f"Error processing audiobook {book_id}: {str(e)}")
        await db[AUDIOBOOKS_COLLECTION].update_one(
            {"id": book_id},
            {
                "$set": {
                    "status": "failed",
                    "error": str(e),
                    "updated_at": datetime.utcnow()
                }
            }
        )

@router.post("/", response_model=Audiobook)
async def create_audiobook(
    background_tasks: BackgroundTasks,
    title: str,
    author: str,
    voice_id: str,
    text_file: Optional[UploadFile] = File(None),
    text_content: Optional[str] = None,
    request: Request = None
):
    """Create a new audiobook."""
    db = await get_db()
    book_id = str(uuid.uuid4())

    # Validate input
    if not text_file and not text_content:
        raise HTTPException(
            status_code=400,
            detail="Either text_file or text_content must be provided"
        )

    # Create audiobook document
    audiobook = {
        "id": book_id,
        "title": title,
        "author": author,
        "voice_id": voice_id,
        "status": "pending",
        "created_at": datetime.utcnow(),
        "updated_at": datetime.utcnow()
    }

    # Handle text input
    if text_file:
        text_path = f"{TEXT_DIR}/{book_id}.txt"
        with open(text_path, "wb") as f:
            shutil.copyfileobj(text_file.file, f)
        audiobook["text_path"] = text_path
    else:
        text_path = f"{TEXT_DIR}/{book_id}.txt"
        with open(text_path, "w") as f:
            f.write(text_content)
        audiobook["text_path"] = text_path

    # Insert audiobook into database
    await db[AUDIOBOOKS_COLLECTION].insert_one(audiobook)

    # Start background processing
    background_tasks.add_task(process_audiobook, book_id, db)

    return audiobook

@router.get("/{book_id}", response_model=Audiobook)
async def get_audiobook(book_id: str):
    """Get audiobook information."""
    db = await get_db()
    audiobook = await db[AUDIOBOOKS_COLLECTION].find_one({"id": book_id})
    if not audiobook:
        raise HTTPException(status_code=404, detail="Audiobook not found")
    return audiobook

@router.get("/{book_id}/audio")
async def get_audiobook_audio(book_id: str):
    """Get audiobook audio file."""
    db = await get_db()
    audiobook = await db[AUDIOBOOKS_COLLECTION].find_one({"id": book_id})
    
    if not audiobook:
        raise HTTPException(status_code=404, detail="Audiobook not found")
    
    if audiobook["status"] != "completed":
        raise HTTPException(
            status_code=400,
            detail=f"Audiobook is not ready (status: {audiobook['status']})"
        )
    
    file_path = audiobook.get("file_path")
    if not file_path or not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="Audio file not found")
    
    return FileResponse(
        file_path,
        media_type="audio/mpeg",
        filename=f"{audiobook['title']}.mp3"
    )

@router.get("/", response_model=List[Audiobook])
async def list_audiobooks():
    """List all audiobooks."""
    db = await get_db()
    audiobooks = await db[AUDIOBOOKS_COLLECTION].find().to_list(length=None)
    return audiobooks

@router.delete("/{book_id}")
async def delete_audiobook(book_id: str):
    """Delete an audiobook."""
    db = await get_db()
    audiobook = await db[AUDIOBOOKS_COLLECTION].find_one({"id": book_id})
    
    if not audiobook:
        raise HTTPException(status_code=404, detail="Audiobook not found")
    
    # Delete associated files
    if audiobook.get("file_path") and os.path.exists(audiobook["file_path"]):
        os.remove(audiobook["file_path"])
    if audiobook.get("text_path") and os.path.exists(audiobook["text_path"]):
        os.remove(audiobook["text_path"])
    
    # Delete from database
    await db[AUDIOBOOKS_COLLECTION].delete_one({"id": book_id})
    
    return {"message": "Audiobook deleted successfully"}