File size: 10,067 Bytes
c034a74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff704b5
4196bc7
c034a74
2bb03a8
4196bc7
 
 
 
1570ec4
4196bc7
 
 
 
2bb03a8
 
 
 
ff704b5
4196bc7
 
 
 
 
 
 
 
 
 
 
 
 
 
c034a74
2bb03a8
 
4196bc7
c034a74
60e1507
4196bc7
1570ec4
60e1507
3a240c4
 
ae31f7e
3a240c4
c034a74
4196bc7
2bb03a8
 
 
 
 
 
 
 
4196bc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a318fb7
4196bc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60e1507
4196bc7
 
 
 
 
60e1507
 
 
 
 
4196bc7
 
 
a318fb7
4196bc7
2bb03a8
908288f
4196bc7
2bb03a8
 
 
 
 
 
4196bc7
ff704b5
60e1507
2bb03a8
 
 
 
c034a74
2bb03a8
4196bc7
 
2bb03a8
4196bc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bb03a8
4196bc7
 
 
 
 
 
 
 
 
 
 
 
 
 
2bb03a8
4196bc7
 
 
 
 
 
 
 
 
2bb03a8
4196bc7
2bb03a8
4196bc7
 
2bb03a8
 
 
4196bc7
2bb03a8
 
60e1507
4196bc7
2bb03a8
 
60e1507
4196bc7
 
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# from fastapi import FastAPI, Response
# from fastapi.responses import FileResponse
# from kokoro import KPipeline
# import soundfile as sf
# import os
# import numpy as np
# import torch 
# from huggingface_hub import InferenceClient

# def llm_chat_response(text):
#     HF_TOKEN = os.getenv("HF_TOKEN")
#     client = InferenceClient(api_key=HF_TOKEN)
#     messages = [
# 	{
# 		"role": "user",
# 		"content": [
# 			{
# 				"type": "text",
# 				"text": text + str('describe in one line only')
# 			} #,
# 			# {
# 			# 	"type": "image_url",
# 			# 	"image_url": {
# 			# 		"url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
# 			# 	}
# 			# }
#             ]
# 	}
#     ]

#     response_from_llama = client.chat.completions.create(
#     model="meta-llama/Llama-3.2-11B-Vision-Instruct", 
# 	messages=messages, 
# 	max_tokens=500)

#     return response_from_llama.choices[0].message['content']

# app = FastAPI()

# # Initialize pipeline once at startup
# pipeline = KPipeline(lang_code='a')

# @app.post("/generate")
# async def generate_audio(text: str, voice: str = "af_heart", speed: float = 1.0):
    
#     text_reply = llm_chat_response(text)
    
#     # Generate audio
#     generator = pipeline(
#         text_reply, 
#         voice=voice,
#         speed=speed,
#         split_pattern=r'\n+'
#     )
    
#     # # Save first segment only for demo
#     # for i, (gs, ps, audio) in enumerate(generator):
#     #     sf.write(f"output_{i}.wav", audio, 24000)
#     #     return FileResponse(
#     #         f"output_{i}.wav",
#     #         media_type="audio/wav",
#     #         filename="output.wav"
#     #     )
    
#     # return Response("No audio generated", status_code=400)


#     # Process only the first segment for demo
#     for i, (gs, ps, audio) in enumerate(generator):

#         # Convert PyTorch tensor to NumPy array
#         audio_numpy = audio.cpu().numpy()
#         # Convert to 16-bit PCM
        
#         # Ensure the audio is in the range [-1, 1]
#         audio_numpy = np.clip(audio_numpy, -1, 1)
#         # Convert to 16-bit signed integers
#         pcm_data = (audio_numpy * 32767).astype(np.int16)
        
#         # Convert to bytes (automatically uses row-major order)
#         raw_audio = pcm_data.tobytes()
        
#         # Return PCM data with minimal necessary headers
#         return Response(
#             content=raw_audio,
#             media_type="application/octet-stream",
#             headers={
#                 "Content-Disposition": f'attachment; filename="output.pcm"',
#                 "X-Sample-Rate": "24000",
#                 "X-Bits-Per-Sample": "16",
#                 "X-Endianness": "little"
#             }
#         )
    
#     return Response("No audio generated", status_code=400)

import os
import uuid
import base64
import logging
from fastapi import FastAPI, HTTPException, Response, Request
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import Optional, ClassVar, List
from huggingface_hub import InferenceClient
import numpy as np
import torch
from kokoro import KPipeline  # Assuming you have this pipeline for audio generation

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

# Create FastAPI app
app = FastAPI(
    title="Text-to-Speech API with Vision Support",
    description="This API uses meta-llama/Llama-3.2-11B-Vision-Instruct, which requires an image input.",
    version="1.0.0"
)

# Mount a static directory for serving saved images
STATIC_DIR = "static_images"
if not os.path.exists(STATIC_DIR):
    os.makedirs(STATIC_DIR)
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")

# Pydantic model for request
class TextImageRequest(BaseModel):
    text: Optional[str] = None
    image_base64: Optional[str] = None
    voice: str = "af_heart"  # Default voice
    speed: float = 1.0

    # Use ClassVar so that Pydantic doesn't treat this as a model field.
    AVAILABLE_VOICES: ClassVar[List[str]] = ["af_heart"]

    def validate_voice(self):
        if self.voice not in self.AVAILABLE_VOICES:
            return "af_heart"
        return self.voice

# (Optional) Pydantic models for responses
class AudioResponse(BaseModel):
    status: str
    message: str

class ErrorResponse(BaseModel):
    error: str
    detail: Optional[str] = None

# Function to call the LLM model following the reference code exactly
def llm_chat_response(text: str, image_base64: str) -> str:
    HF_TOKEN = os.getenv("HF_TOKEN")
    logger.info("Checking HF_TOKEN...")
    if not HF_TOKEN:
        logger.error("HF_TOKEN not configured")
        raise HTTPException(status_code=500, detail="HF_TOKEN not configured")
    
    logger.info("Initializing InferenceClient...")
    client = InferenceClient(
        provider="hf-inference",
        api_key=HF_TOKEN
    )
    
    # Save the base64-encoded image locally so it is accessible via a URL
    filename = f"{uuid.uuid4()}.jpg"
    image_path = os.path.join(STATIC_DIR, filename)
    try:
        image_data = base64.b64decode(image_base64)
    except Exception as e:
        logger.error(f"Error decoding image: {str(e)}")
        raise HTTPException(status_code=400, detail="Invalid base64 image data")
    
    with open(image_path, "wb") as f:
        f.write(image_data)
    
    # Construct the public URL for the saved image.
    # BASE_URL should be set to your public URL if not running locally.
    base_url = os.getenv("BASE_URL", "http://localhost:8000")
    image_url = f"{base_url}/static/{filename}"
    
    # Build the message exactly as in the reference code.
    # This model requires a list with two items: one for text and one for the image.
    prompt = text if text else "Describe this image in one sentence."
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": prompt},
                {"type": "image_url", "image_url": {"url": image_url}}
            ]
        }
    ]
    logger.info(f"Message structure: {messages}")
    
    try:
        completion = client.chat.completions.create(
            model="meta-llama/Llama-3.2-11B-Vision-Instruct",
            messages=messages,
            max_tokens=500
        )
        response = completion.choices[0].message.content
        logger.info(f"Extracted response: {response}")
        return response
    except Exception as e:
        logger.error(f"Error during model inference: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# Initialize audio generation pipeline (your audio conversion pipeline)
try:
    logger.info("Initializing KPipeline...")
    pipeline = KPipeline(lang_code='a')
    logger.info("KPipeline initialized successfully")
except Exception as e:
    logger.error(f"Failed to initialize KPipeline: {str(e)}")
    # The API can still run, but audio generation will fail.

@app.post("/generate", responses={
    200: {"content": {"application/octet-stream": {}}},
    400: {"model": ErrorResponse},
    500: {"model": ErrorResponse}
})
async def generate_audio(request: TextImageRequest):
    """
    Generate audio from a multimodal (text+image) input.
    This model does not support text-only inputs.
    """
    logger.info("Received generation request")
    # Ensure an image is provided because the model is multimodal.
    if not request.image_base64:
        raise HTTPException(status_code=400, detail="This model requires an image input.")
    
    # Get the text prompt. If none is provided, use a default.
    user_text = request.text if request.text else "Describe this image in one sentence."
    
    # Get the LLM's response
    logger.info("Calling the LLM model")
    text_reply = llm_chat_response(user_text, request.image_base64)
    logger.info(f"LLM response: {text_reply}")
    
    # Validate voice parameter (if needed for audio generation)
    validated_voice = request.validate_voice()
    if validated_voice != request.voice:
        logger.warning(f"Voice '{request.voice}' not available; using '{validated_voice}' instead")
    
    # Convert the text reply to audio using your audio pipeline
    logger.info(f"Generating audio using voice={validated_voice}, speed={request.speed}")
    try:
        # Generate audio segments (assumes pipeline yields segments)
        generator = pipeline(
            text_reply,
            voice=validated_voice,
            speed=request.speed,
            split_pattern=r'\n+'
        )
        for i, (gs, ps, audio) in enumerate(generator):
            logger.info(f"Audio generated, segment {i}")
            # Convert audio tensor to 16-bit PCM bytes
            audio_numpy = audio.cpu().numpy()
            audio_numpy = np.clip(audio_numpy, -1, 1)
            pcm_data = (audio_numpy * 32767).astype(np.int16)
            raw_audio = pcm_data.tobytes()
            
            return Response(
                content=raw_audio,
                media_type="application/octet-stream",
                headers={
                    "Content-Disposition": 'attachment; filename="output.pcm"',
                    "X-Sample-Rate": "24000",
                    "X-Bits-Per-Sample": "16",
                    "X-Endianness": "little"
                }
            )
        raise HTTPException(status_code=400, detail="No audio segments generated.")
    except Exception as e:
        logger.error(f"Error generating audio: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/")
async def root():
    return {"message": "Welcome! Use POST /generate with text and image_base64."}

@app.exception_handler(404)
async def not_found_handler(request: Request, exc):
    return JSONResponse(status_code=404, content={"error": "Endpoint not found."})

@app.exception_handler(405)
async def method_not_allowed_handler(request: Request, exc):
    return JSONResponse(status_code=405, content={"error": "Method not allowed."})