File size: 14,549 Bytes
8031a8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27acc7d
8031a8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27acc7d
8031a8f
27acc7d
8031a8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27acc7d
8031a8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27acc7d
8031a8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27acc7d
 
8031a8f
 
 
 
 
 
 
 
 
 
 
 
 
 
27acc7d
8031a8f
 
 
 
 
 
 
 
 
 
 
 
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
from fastapi import FastAPI, UploadFile, File, Form , HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import sys
import os
import shutil
import uuid

# Ensure sibling module fluency is discoverable
#sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from fluency.fluency_api import main as analyze_fluency_main
from tone_modulation.tone_api import main as analyze_tone_main
from vcs.vcs_api import main as analyze_vcs_main
from vers.vers_api import main as analyze_vers_main
from voice_confidence_score.voice_confidence_api import main as analyze_voice_confidence_main
from vps.vps_api import main as analyze_vps_main
from ves.ves import calc_voice_engagement_score
from transcribe import transcribe_audio
from filler_count.filler_score import analyze_fillers
from emotion.emo_predict import predict_emotion

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, replace "*" with allowed frontend domains
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.post("/analyze_fluency/")
async def analyze_fluency(file: UploadFile):
    # idk if we can use pydantic model here If we need I can add later
    if not file.filename.endswith(('.wav', '.mp3','.m4a','.mp4','.flac')):
        raise HTTPException(status_code=400, detail="Invalid file type. Only .wav and .mp3 files are supported.")
    
    # Generate a safe temporary file path for temporary storage of the uploaded file this will be deleted after processing
    temp_filename = f"temp_{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
    temp_dir = "temp_uploads"
    temp_filepath = os.path.join(temp_dir, temp_filename)
    os.makedirs(temp_dir, exist_ok=True)

    try:
        # Save uploaded file
        with open(temp_filepath, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)


        result = analyze_fluency_main(temp_filepath, model_size="base")

        return JSONResponse(content=result)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Fluency analysis failed: {str(e)}")

    finally:
        # Clean up temporary file
        if os.path.exists(temp_filepath):
            os.remove(temp_filepath)
            
@app.post('/analyze_tone/')
async def analyze_tone(file: UploadFile):
    """
    Endpoint to analyze tone of an uploaded audio file (.wav or .mp3).
    """
    if not file.filename.endswith(('.wav', '.mp3','.m4a','.mp4','.flac')):
        raise HTTPException(status_code=400, detail="Invalid file type. Only .wav and .mp3 files are supported.")
    
    # Generate a safe temporary file path
    temp_filename = f"temp_{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
    temp_dir = "temp_uploads"
    temp_filepath = os.path.join(temp_dir, temp_filename)
    os.makedirs(temp_dir, exist_ok=True)

    try:
        # Save uploaded file
        with open(temp_filepath, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Analyze tone using your custom function
        result = analyze_tone_main(temp_filepath)

        return JSONResponse(content=result)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Tone analysis failed: {str(e)}")

    finally:
        # Clean up temporary file
        if os.path.exists(temp_filepath):
            os.remove(temp_filepath)

@app.post('/analyze_vcs/')
async def analyze_vcs(file: UploadFile):
    """
    Endpoint to analyze voice clarity of an uploaded audio file (.wav or .mp3).
    """
    if not file.filename.endswith(('.wav', '.mp3','.m4a','.mp4','.flac')):
        raise HTTPException(status_code=400, detail="Invalid file type. Only .wav and .mp3 files are supported.")
    
    # Generate a safe temporary file path
    temp_filename = f"temp_{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
    temp_dir = "temp_uploads"
    temp_filepath = os.path.join(temp_dir, temp_filename)
    os.makedirs(temp_dir, exist_ok=True)

    try:
        # Save uploaded file
        with open(temp_filepath, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Analyze voice clarity using your custom function
        result = analyze_vcs_main(temp_filepath)

        return JSONResponse(content=result)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Voice clarity analysis failed: {str(e)}")

    finally:
        # Clean up temporary file
        if os.path.exists(temp_filepath):
            os.remove(temp_filepath)

@app.post('/analyze_vers/')
async def analyze_vers(file: UploadFile):
    """
    Endpoint to analyze VERS of an uploaded audio file (.wav or .mp3).
    """
    if not file.filename.endswith(('.wav', '.mp3','.m4a','.mp4','.flac')):
        raise HTTPException(status_code=400, detail="Invalid file type. Only .wav and .mp3 files are supported.")
    
    # Generate a safe temporary file path
    temp_filename = f"temp_{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
    temp_dir = "temp_uploads"
    temp_filepath = os.path.join(temp_dir, temp_filename)
    os.makedirs(temp_dir, exist_ok=True)

    try:
        # Save uploaded file
        with open(temp_filepath, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Analyze VERS using your custom function
        result = analyze_vers_main(temp_filepath)

        return JSONResponse(content=result)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"VERS analysis failed: {str(e)}")

    finally:
        # Clean up temporary file
        if os.path.exists(temp_filepath):
            os.remove(temp_filepath)
            
@app.post('/voice_confidence/')
async def analyze_voice_confidence(file: UploadFile):
    """
    Endpoint to analyze voice confidence of an uploaded audio file (.wav or .mp3).
    """
    if not file.filename.endswith(('.wav', '.mp3','.m4a','.mp4','.flac')):
        raise HTTPException(status_code=400, detail="Invalid file type. Only .wav and .mp3 files are supported.")
    
    # Generate a safe temporary file path
    temp_filename = f"temp_{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
    temp_dir = "temp_uploads"
    temp_filepath = os.path.join(temp_dir, temp_filename)
    os.makedirs(temp_dir, exist_ok=True)

    try:
        # Save uploaded file
        with open(temp_filepath, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Analyze voice confidence using your custom function
        result = analyze_voice_confidence_main(temp_filepath)

        return JSONResponse(content=result)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Voice confidence analysis failed: {str(e)}")

    finally:
        # Clean up temporary file
        if os.path.exists(temp_filepath):
            os.remove(temp_filepath)

@app.post('/analyze_vps/')
async def analyze_vps(file: UploadFile):
    """
    Endpoint to analyze voice pacing score of an uploaded audio file (.wav or .mp3).
    """
    if not file.filename.endswith(('.wav', '.mp3','.m4a','.mp4','.flac')):
        raise HTTPException(status_code=400, detail="Invalid file type. Only .wav and .mp3 files are supported.")
    
    # Generate a safe temporary file path
    temp_filename = f"temp_{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
    temp_dir = "temp_uploads"
    temp_filepath = os.path.join(temp_dir, temp_filename)
    os.makedirs(temp_dir, exist_ok=True)

    try:
        # Save uploaded file
        with open(temp_filepath, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Analyze voice pacing score using your custom function
        result = analyze_vps_main(temp_filepath)

        return JSONResponse(content=result)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Voice pacing score analysis failed: {str(e)}")

    finally:
        # Clean up temporary file
        if os.path.exists(temp_filepath):
            os.remove(temp_filepath)

@app.post('/voice_engagement_score/')
async def analyze_voice_engagement_score(file: UploadFile):
    """
    Endpoint to analyze voice engagement score of an uploaded audio file (.wav or .mp3).
    """
    if not file.filename.endswith(('.wav', '.mp3','.m4a','.mp4','.flac')):
        raise HTTPException(status_code=400, detail="Invalid file type. Only .wav and .mp3 files are supported.")
    
    # Generate a safe temporary file path
    temp_filename = f"temp_{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
    temp_dir = "temp_uploads"
    temp_filepath = os.path.join(temp_dir, temp_filename)
    os.makedirs(temp_dir, exist_ok=True)

    try:
        # Save uploaded file
        with open(temp_filepath, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Analyze voice engagement score using your custom function
        result = calc_voice_engagement_score(temp_filepath)

        return JSONResponse(content=result)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Voice engagement score analysis failed: {str(e)}")

    finally:
        # Clean up temporary file
        if os.path.exists(temp_filepath):
            os.remove(temp_filepath)

@app.post('/analyze_fillers/')
async def analyze_fillers_count(file: UploadFile):
    """
    Endpoint to analyze filler words in an uploaded audio file (.wav or .mp3).
    """
    if not file.filename.endswith(('.wav', '.mp3','.mp4','.m4a','.flac')):
        raise HTTPException(status_code=400, detail="Invalid file type. Only .wav and .mp3 files are supported.")
    
    # Generate a safe temporary file path
    temp_filename = f"temp_{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
    temp_dir = "temp_uploads"
    temp_filepath = os.path.join(temp_dir, temp_filename)
    os.makedirs(temp_dir, exist_ok=True)

    try:
        # Save uploaded file
        with open(temp_filepath, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Call the analysis function with the file path
        result = analyze_fillers(temp_filepath)  # Pass the file path, not the UploadFile object

        return JSONResponse(content=result)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Filler analysis failed: {str(e)}")

    finally:
        # Clean up temporary file
        if os.path.exists(temp_filepath):
            os.remove(temp_filepath)


import time 



@app.post('/transcribe/')
async def transcribe(file: UploadFile, language: str = Form(...)):
    """
    Endpoint to transcribe an uploaded audio file (.wav or .mp3).
    """
    #calculate time to transcribe
    start_time = time.time()
    if not file.filename.endswith(('.wav', '.mp3','mp4','.m4a','.flac')):
        raise HTTPException(status_code=400, detail="Invalid file type. Only .wav ,mp4 and .mp3 files are supported.")
    
    # Generate a safe temporary file path
    temp_filename = f"temp_{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
    temp_dir = "temp_uploads"
    temp_filepath = os.path.join(temp_dir, temp_filename)
    os.makedirs(temp_dir, exist_ok=True)

    try:
        # Save uploaded file
        with open(temp_filepath, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Transcribe using your custom function
        result = transcribe_audio(temp_filepath, language=language, model_size="base")
        end_time = time.time()
        transcription_time = end_time - start_time
        response = {
            "transcription": result,
            "transcription_time": transcription_time
        }
    
        return JSONResponse(content=response)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Transcription failed: {str(e)}")
    
    finally:
        # Clean up temporary file
        if os.path.exists(temp_filepath):
            os.remove(temp_filepath)


@app.post('/analyze_all/')
async def analyze_all(file: UploadFile, language: str = Form(...)):
    """
    Endpoint to analyze all aspects of an uploaded audio file (.wav or .mp3).
    """
    if not file.filename.endswith(('.wav', '.mp3','.m4a','.mp4','.flac')):
        raise HTTPException(status_code=400, detail="Invalid file type. Only .wav and .mp3 files are supported.")
    
    # Generate a safe temporary file path
    temp_filename = f"temp_{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
    temp_dir = "temp_uploads"
    temp_filepath = os.path.join(temp_dir, temp_filename)
    os.makedirs(temp_dir, exist_ok=True)

    try:
        # Save uploaded file
        with open(temp_filepath, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Analyze all aspects using your custom functions
        fluency_result = analyze_fluency_main(temp_filepath, model_size="base")
        tone_result = analyze_tone_main(temp_filepath)
        vcs_result = analyze_vcs_main(temp_filepath)
        vers_result = analyze_vers_main(temp_filepath)
        voice_confidence_result = analyze_voice_confidence_main(temp_filepath)
        vps_result = analyze_vps_main(temp_filepath)
        ves_result = calc_voice_engagement_score(temp_filepath)
        filler_count = analyze_fillers(temp_filepath)  # Assuming this function returns a dict with filler count
        transcript = transcribe_audio(temp_filepath, language, "base") #fix this
        emotion = predict_emotion(temp_filepath) 
        avg_score = (fluency_result['fluency_score'] + tone_result['speech_dynamism_score'] + vcs_result['Voice Clarity Sore'] + vers_result['VERS Score'] + voice_confidence_result['voice_confidence_score'] + vps_result['VPS'] + ves_result['ves']) / 7


        # Combine results into a single response
        combined_result = {
            "fluency": fluency_result,
            "tone": tone_result,
            "vcs": vcs_result,
            "vers": vers_result,
            "voice_confidence": voice_confidence_result,
            "vps": vps_result,
            "ves": ves_result,
            "filler_words": filler_count,
            "transcript": transcript,
            "emotion": emotion ,
            "sank_score": avg_score
        }

        return JSONResponse(content=combined_result)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}")

    finally:
        # Clean up temporary file
        if os.path.exists(temp_filepath):
            os.remove(temp_filepath)