VeuReu commited on
Commit
a826212
·
verified ·
1 Parent(s): ed4647c

Create moe_router.py

Browse files
Files changed (1) hide show
  1. main_process/moe_router.py +632 -0
main_process/moe_router.py ADDED
@@ -0,0 +1,632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import re
4
+ import ast
5
+ import json
6
+ import tempfile
7
+ from pathlib import Path
8
+ from typing import List, Dict, Counter
9
+
10
+ # --- Third-Party Libraries ---
11
+ import cv2
12
+ import torch
13
+ from fastapi import APIRouter, UploadFile, File, Query, HTTPException
14
+ from fastapi.responses import JSONResponse, StreamingResponse, FileResponse
15
+ from transformers import AutoModelForCausalLM, AutoTokenizer
16
+ from openai import OpenAI
17
+
18
+ # --- Internal Modules / Project Imports ---
19
+ from svision_client import (
20
+ extract_scenes,
21
+ add_ocr_and_faces,
22
+ keyframes_every_second_extraction,
23
+ extract_descripcion_escena
24
+ )
25
+
26
+ from asr_client import (
27
+ extract_audio_from_video,
28
+ diarize_audio,
29
+ transcribe_long_audio,
30
+ transcribe_short_audio,
31
+ identificar_veu
32
+ )
33
+
34
+ from storage.common import validate_token
35
+ from storage.files.file_manager import FileManager
36
+ from storage.embeddings_routers import get_embeddings_json
37
+
38
+ from main_process.main_router import (
39
+ get_initial_info_path,
40
+ get_initial_srt_path
41
+ )
42
+
43
+ EMBEDDINGS_ROOT = Path("/data/embeddings")
44
+ MEDIA_ROOT = Path("/data/media")
45
+ os.environ["CUDA_VISIBLE_DEVICES"] = "1"
46
+ router = APIRouter(prefix="/salamandra", tags=["Salamandra Process"])
47
+ HF_TOKEN = os.getenv("HF_TOKEN")
48
+ OPEN_AI_KEY = os.getenv("OPEN_AI_KEY")
49
+
50
+ class DataHub:
51
+ def __init__(self, video_analysis_json: str):
52
+ print("DataHub inicializando con JSON:", video_analysis_json)
53
+ self.video = json.loads(Path(video_analysis_json).read_text(encoding='utf-8'))
54
+
55
+ class NState(dict):
56
+ pass
57
+
58
+ # ---------------- LLM utilizado para el free_narration ----------------
59
+ class SalamandraClient:
60
+ def __init__(self, model_id="BSC-LT/salamandra-7b-instruct"):
61
+ self.tokenizer = AutoTokenizer.from_pretrained(model_id)
62
+ self.model = AutoModelForCausalLM.from_pretrained(
63
+ model_id,
64
+ device_map="auto",
65
+ torch_dtype=torch.bfloat16
66
+ )
67
+
68
+ def chat(self, prompt) -> str:
69
+ encodings = self.tokenizer(
70
+ prompt,
71
+ return_tensors="pt",
72
+ padding=True,
73
+ )
74
+
75
+ inputs = encodings["input_ids"].to(self.model.device)
76
+ attention_mask = encodings["attention_mask"].to(self.model.device)
77
+
78
+ outputs = self.model.generate(
79
+ input_ids=inputs,
80
+ attention_mask=attention_mask,
81
+ pad_token_id=self.tokenizer.pad_token_id,
82
+ max_new_tokens=300, # más grande si el texto es largo
83
+ temperature=0.01, # control de creatividad
84
+ top_k=50, # tokens más probables
85
+ top_p=0.9
86
+ )
87
+ print(self.tokenizer.decode(outputs[0], skip_special_tokens=True))
88
+ print("Separación")
89
+ # Cortar la parte del prompt
90
+ generated_tokens = outputs[0][inputs.shape[1]:]
91
+ return self.tokenizer.decode(generated_tokens, skip_special_tokens=True)
92
+
93
+ # Esto aquí sólo se utiliza para la valoración:
94
+ class GPT5Client:
95
+ def __init__(self, api_key: str):
96
+ key = api_key
97
+ if not key:
98
+ raise RuntimeError(f"Missing key in environment for GPT-5 client")
99
+ self.cli = OpenAI(api_key=key)
100
+
101
+ def chat(self, messages: list, model: str = 'gpt-4o-mini') -> str:
102
+ print("GPT5Client.chat llamado con", len(messages), "mensajes")
103
+ r = self.cli.chat.completions.create(model=model, messages=messages,temperature=0)
104
+ content = r.choices[0].message.content.strip()
105
+ return content
106
+
107
+
108
+ def get_video_duration(video_path: str) -> float:
109
+ """
110
+ Devuelve la duración total del vídeo en segundos.
111
+ """
112
+ cap = cv2.VideoCapture(video_path)
113
+ if not cap.isOpened():
114
+ raise RuntimeError(f"No s'ha pogut obrir el vídeo: {video_path}")
115
+
116
+ fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
117
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
118
+ cap.release()
119
+
120
+ duration_sec = total_frames / fps if total_frames > 0 else 0.0
121
+ return duration_sec
122
+
123
+ def generate_srt_con_silencios(path_srt_original, path_srt_silences, video_path):
124
+ # Obtenir duració total del vídeo
125
+ duracio_total = get_video_duration(video_path)
126
+
127
+ with open(path_srt_original, "r", encoding="utf-8-sig") as f:
128
+ srt_text = f.read()
129
+
130
+ blocks = srt_text.strip().split("\n\n")
131
+ prev = 0
132
+ srt_entries = []
133
+ idx = 1
134
+
135
+ for block in blocks:
136
+ lines = block.split("\n")
137
+ time_range = lines[1]
138
+ print(time_range)
139
+ content = " ".join(line.strip() for line in lines[2:])
140
+
141
+ start_str, end_str = time_range.split(" --> ")
142
+ start_sec = srt_time_to_seconds(start_str)
143
+ end_sec = srt_time_to_seconds(end_str)
144
+
145
+ # Afegir silenci si hi ha espai
146
+ if prev < start_sec:
147
+ srt_entries.append(
148
+ f"{idx}\n{seconds_to_srt_time(prev)} --> {seconds_to_srt_time(start_sec)}\n[silenci]\n"
149
+ )
150
+ idx += 1
151
+
152
+ # Afegir clip amb text
153
+ srt_entries.append(
154
+ f"{idx}\n{seconds_to_srt_time(start_sec)} --> {seconds_to_srt_time(end_sec)}\n{content}\n"
155
+ )
156
+ idx += 1
157
+ prev = end_sec
158
+
159
+ # Afegir últim bloc de silenci si la duració del vídeo és més llarga que l'últim clip
160
+ if prev < duracio_total:
161
+ srt_entries.append(
162
+ f"{idx}\n{seconds_to_srt_time(prev)} --> {seconds_to_srt_time(duracio_total)}\n[silenci]\n"
163
+ )
164
+
165
+ # Guardar a l'arxiu final
166
+ with open(path_srt_silences, "w", encoding="utf-8") as f:
167
+ f.write("\n".join(srt_entries))
168
+
169
+ def srt_time_to_seconds(s):
170
+ h, m, rest = s.split(":")
171
+ s, ms = rest.split(",")
172
+ return int(h)*3600 + int(m)*60 + float(s) + int(ms)/1000
173
+
174
+ def seconds_to_srt_time(seconds):
175
+ h = int(seconds // 3600)
176
+ m = int((seconds % 3600) // 60)
177
+ s = int(seconds % 60)
178
+ ms = int((seconds - int(seconds)) * 1000)
179
+ return f"{h:02}:{m:02}:{s:02},{ms:03}"
180
+
181
+ class Add_AD:
182
+ def __init__(self, data: DataHub):
183
+ self.data = data
184
+
185
+ def __call__(self, state: NState, srt_modified_silence, srt_modified_silence_con_ad) -> NState:
186
+ print("Add_Ad.__call__ iniciado")
187
+
188
+ # Leer SRT original
189
+ with open(srt_modified_silence, "r", encoding="utf-8") as f:
190
+ srt_text = f.read()
191
+
192
+ # Frames del video
193
+ frames = self.data.video.get('info_escenas', {})
194
+
195
+ # Parsear SRT a bloques
196
+ srt_blocks = []
197
+ srt_blocks_modified=[]
198
+ pattern = re.compile(
199
+ r"(\d+)\s+(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\s+(.*?)(?=\n\d+\n|\Z)",
200
+ re.S
201
+ )
202
+
203
+ for match in pattern.finditer(srt_text):
204
+ index = int(match.group(1))
205
+ start = srt_time_to_seconds(match.group(2))
206
+ end = srt_time_to_seconds(match.group(3))
207
+ text = match.group(4).strip()
208
+ srt_blocks.append({
209
+ "index": index,
210
+ "start": start,
211
+ "end": end,
212
+ "text": text
213
+ })
214
+
215
+ index=1
216
+ # Procesar cada bloque
217
+ for block in srt_blocks:
218
+ if "[silenci]" in block["text"]:
219
+ start_block = block["start"]
220
+ end_block = block["end"]
221
+
222
+ for frame in frames:
223
+ if frame.get("start")<=start_block and frame.get("end")>=end_block:
224
+ srt_blocks_modified.append({
225
+ "index":index,
226
+ "start": start_block,
227
+ "end": end_block,
228
+ "text": f"(AD): {frame.get('descripcion', '')}"
229
+ })
230
+ index+=1
231
+
232
+ elif start_block<frame.get("end")<end_block:
233
+ srt_blocks_modified.append({
234
+ "index":index,
235
+ "start": start_block,
236
+ "end": frame.get("end"),
237
+ "text": f"(AD): {frame.get('descripcion', '')}"
238
+ })
239
+ start_block=frame.get("end")
240
+ index+=1
241
+
242
+ elif start_block==frame.get("start") and start_block<end_block and frame.get("end")>=end_block:
243
+ srt_blocks_modified.append({
244
+ "index":index,
245
+ "start": start_block,
246
+ "end": end_block,
247
+ "text": f"(AD): {frame.get('descripcion', '')}"
248
+ })
249
+ start_block=end_block
250
+ index+=1
251
+
252
+ else:
253
+ srt_blocks_modified.append({
254
+ "index": index,
255
+ "start": block["start"],
256
+ "end": block["end"],
257
+ "text": block["text"]
258
+ })
259
+ index+=1
260
+
261
+ # Reconstruir el SRT final
262
+ srt_final = ""
263
+
264
+ for block in srt_blocks_modified:
265
+ start_tc = seconds_to_srt_time(block["start"])
266
+ end_tc = seconds_to_srt_time(block["end"])
267
+ srt_final += f"{block['index']}\n{start_tc} --> {end_tc}\n{block['text']}\n\n"
268
+
269
+ # Guardar en un nuevo archivo
270
+ with open(srt_modified_silence_con_ad, "w", encoding="utf-8") as f:
271
+ f.write(srt_final)
272
+
273
+ # Actualizar estado
274
+ state['srt_con_audiodescripcion'] = srt_final
275
+ return state
276
+
277
+ class Free_Narration:
278
+ def __init__(self, data: DataHub):
279
+ self.data = data
280
+
281
+ def __call__(self, state: NState, srt_original_silence_con_ad, story_path) -> NState:
282
+ print("Free_Narration.__call__ iniciado")
283
+
284
+ descriptions=[]
285
+ frames = self.data.video.get('info_escenas', [])
286
+ for frame in frames:
287
+ descriptions.append(frame["descripcion"])
288
+
289
+ full_transcription = self.data.video.get('full_transcription', [])
290
+
291
+ with open(srt_original_silence_con_ad, "r", encoding="utf-8-sig") as f:
292
+ diarization_text = f.read()
293
+
294
+ prompt = f"""
295
+ La teva tasca és elaborar una descripció lliure d'un vídeo d'unes 100 paraules a partir de la informació següent:
296
+ 1.) A partir del vídeo s'han extret captures de pantalla en els moments en què es canviava d'escena i tens una descripció de cadascuna d'elles a: {descriptions}
297
+ 2.) La transcripció completa del vídeo és: {full_transcription}
298
+ Per tant, a partir de tota aquesta informació, genera'm la història completa, intentant incloure els personatges identificats i la trama general de la història.
299
+ """
300
+ out = state['llm_Salamandra'](prompt)
301
+ print(out)
302
+
303
+ with open(story_path, "w", encoding="utf-8-sig") as f:
304
+ f.write(out)
305
+
306
+ state['free_narration'] = out
307
+
308
+ return state
309
+
310
+ class Valoracion_Final:
311
+ def __call__(self, state, srt_final, csv_evaluacion):
312
+ print("Valoracion_Final.__call__ iniciat")
313
+
314
+ # Llegeix el contingut del fitxer SRT
315
+ with open(srt_final, "r", encoding="utf-8-sig") as f:
316
+ srt_text = f.read().strip()
317
+
318
+ # Defineix el prompt principal
319
+ prompt = f"""
320
+ Ets un avaluador expert en accessibilitat audiovisual segons la NORMA UNE 153020.
321
+
322
+ Analitza el següent fitxer SRT i avalua'l segons les característiques indicades.
323
+ Per a cada característica, assigna una puntuació del 0 al 7 i una justificació breu i específica,
324
+ seguint el format establert.
325
+
326
+ SRT a analitzar:
327
+ {srt_text}
328
+
329
+ Format de sortida:
330
+ Caracteristica,Valoracio (0-7),Justificacio
331
+
332
+ Les característiques a avaluar són:
333
+ - Precisió Descriptiva: Avalua si la descripció visual dels plans, accions i context és exacta i coherent amb el contingut esperat.
334
+ - Sincronització Temporal: Avalua si el text apareix i desapareix al moment adequat segons el contingut visual o sonor.
335
+ - Claredat i Concisió: Analitza si el llenguatge és clar, natural i sense redundàncies.
336
+ - Inclusió de Diàleg/So: Determina si es recullen correctament els diàlegs, sons i elements musicals rellevants.
337
+ - Contextualització: Avalua si el context (ambient, espai, personatges, situacions) està ben representat.
338
+ - Flux i Ritme de la Narració: Avalua la fluïdesa de la lectura i la coherència temporal entre segments.
339
+
340
+ Respon només amb la taula CSV, sense cap text addicional.
341
+ """
342
+
343
+ # Missatges estructurats per al model (rols system + user)
344
+ messages = [
345
+ {"role": "system", "content": "Ets un assistent expert en accessibilitat audiovisual i normativa UNE 153020."},
346
+ {"role": "user", "content": prompt}
347
+ ]
348
+
349
+ # Crida al model (s’assumeix que state['llm_GPT'] és una funció que processa missatges)
350
+ out = state['llm_GPT'](messages)
351
+
352
+ out_text = str(out).strip()
353
+
354
+ # Escriu el resultat CSV
355
+ with open(csv_evaluacion, "w", encoding="utf-8-sig") as f:
356
+ f.write(out_text)
357
+
358
+ return state
359
+
360
+ @router.post("/generate_salamadra_result", tags=["Salamandra Process"])
361
+ async def generate_salamadra_result(
362
+ sha1: str,
363
+ token: str = Query(..., description="Token required for authorization")
364
+ ):
365
+ """
366
+ Generate all Salamandra output files (final SRT, free narration, and evaluation CSV)
367
+ for a processed video identified by its SHA1 hash.
368
+
369
+ This endpoint orchestrates the full Salamandra processing pipeline:
370
+ - Validates the access token.
371
+ - Locates the processed video and its associated metadata.
372
+ - Generates an intermediate SRT file enriched with silence markers.
373
+ - Runs the Salamandra logic to produce:
374
+ * A finalized SRT subtitle file (`result.srt`)
375
+ * A free-narration text file (`free_narration.txt`)
376
+ * An evaluation CSV (`evaluation.csv`)
377
+ - Ensures the expected directory structure exists, creating folders if necessary.
378
+ - Uses both GPT-based and Salamandra-based LLMs to generate narrative and evaluation content.
379
+
380
+ Args:
381
+ sha1 (str): The SHA1 hash that identifies the media processing workspace.
382
+ token (str): Authorization token required to execute Salamandra operations.
383
+
384
+ Raises:
385
+ HTTPException:
386
+ - 404 if the SHA1 folder does not exist.
387
+ - 404 if the `clip` folder is missing.
388
+ - 404 if no MP4 file is found inside the clip folder.
389
+
390
+ Processing Steps:
391
+ 1. Validates that all required folders exist (`sha1`, `clip`, `result/Salamandra`).
392
+ 2. Retrieves the input video and initial metadata (original SRT, info JSON).
393
+ 3. Creates temporary enriched SRT with silence detection.
394
+ 4. Runs Add_AD, Free_Narration, and Valoracion_Final modules.
395
+ 5. Generates the final Salamandra output files:
396
+ - result.srt
397
+ - free_narration.txt
398
+ - evaluation.csv
399
+
400
+ Returns:
401
+ dict: A JSON response indicating successful generation:
402
+ {
403
+ "status": "ok",
404
+ "message": "Salamandra SRT, free_narration and CSV evaluation generated"
405
+ }
406
+ """
407
+ validate_token(token)
408
+
409
+ # Resolve directories
410
+ file_manager = FileManager(MEDIA_ROOT)
411
+ sha1_folder = MEDIA_ROOT / sha1
412
+ clip_folder = sha1_folder / "clip"
413
+
414
+ if not sha1_folder.exists() or not sha1_folder.is_dir():
415
+ raise HTTPException(status_code=404, detail="SHA1 folder not found")
416
+
417
+ if not clip_folder.exists() or not clip_folder.is_dir():
418
+ raise HTTPException(status_code=404, detail="Clip folder not found")
419
+
420
+ # Locate video file
421
+ mp4_files = list(clip_folder.glob("*.mp4"))
422
+ if not mp4_files:
423
+ raise HTTPException(status_code=404, detail="No MP4 files found")
424
+ video_path = clip_folder / mp4_files[0]
425
+
426
+ # Get initial srt
427
+ srt_original = get_initial_srt_path(sha1)
428
+
429
+ # Get initial info json
430
+ informacion_json = get_initial_info_path(sha1)
431
+
432
+ # Generate srt final path
433
+ file_manager = FileManager(MEDIA_ROOT)
434
+ sha1_folder = MEDIA_ROOT / sha1
435
+ result_folder = sha1_folder / "result"
436
+ result_folder.mkdir(parents=True, exist_ok=True)
437
+ salamdra_folder = result_folder / "Salamandra"
438
+ salamdra_folder.mkdir(parents=True, exist_ok=True)
439
+ srt_final = salamdra_folder / "result.srt"
440
+
441
+ # Generate free_narration_salamandra final path
442
+ file_manager = FileManager(MEDIA_ROOT)
443
+ sha1_folder = MEDIA_ROOT / sha1
444
+ result_folder = sha1_folder / "result"
445
+ result_folder.mkdir(parents=True, exist_ok=True)
446
+ salamdra_folder = result_folder / "Salamandra"
447
+ salamdra_folder.mkdir(parents=True, exist_ok=True)
448
+ free_narration_salamandra = salamdra_folder / "free_narration.txt"
449
+
450
+ # Generate evaluation csv path
451
+ file_manager = FileManager(MEDIA_ROOT)
452
+ sha1_folder = MEDIA_ROOT / sha1
453
+ result_folder = sha1_folder / "result"
454
+ result_folder.mkdir(parents=True, exist_ok=True)
455
+ salamdra_folder = result_folder / "Salamandra"
456
+ salamdra_folder.mkdir(parents=True, exist_ok=True)
457
+ csv_evaluacion = salamdra_folder / "evaluation.csv"
458
+
459
+ # Temp srt name
460
+ srt_name = sha1 + "_srt"
461
+ tmp = tempfile.NamedTemporaryFile(mode="w+", suffix=".srt", prefix=srt_name + "_", delete=False)
462
+
463
+ generate_srt_con_silencios(srt_original, tmp.name, video_path)
464
+
465
+ datahub=DataHub(informacion_json)
466
+ add_ad = Add_AD(datahub)
467
+ free_narration = Free_Narration(datahub)
468
+ valoracion_final = Valoracion_Final()
469
+
470
+ GPTclient = GPT5Client(api_key=OPEN_AI_KEY)
471
+ salamandraclient = SalamandraClient()
472
+
473
+ state = {
474
+ "llm_GPT": GPTclient.chat,
475
+ "llm_Salamandra": salamandraclient.chat
476
+ }
477
+
478
+ state = add_ad(state, tmp.name, srt_final)
479
+ state= free_narration(state, srt_final, free_narration_salamandra)
480
+ state = valoracion_final(state, srt_final, csv_evaluacion)
481
+ tmp.close()
482
+
483
+ return {"status": "ok", "message": "Salamandra SRT, free_narration and CSV evaluation generated"}
484
+
485
+ @router.get("/download_salamadra_srt", tags=["Salamandra Process"])
486
+ def download_salamadra_srt(
487
+ sha1: str,
488
+ token: str = Query(..., description="Token required for authorization")
489
+ ):
490
+ """
491
+ Download the final SRT subtitle file generated by the Salamandra processing pipeline.
492
+
493
+ This endpoint retrieves the file `result.srt` associated with a specific SHA1 hash.
494
+ It validates the authorization token, checks the expected folder structure, and
495
+ returns the subtitle file if it exists.
496
+
497
+ Args:
498
+ sha1 (str): The SHA1 identifier corresponding to the processed media folder.
499
+ token (str): Authorization token required to access the resource.
500
+
501
+ Raises:
502
+ HTTPException:
503
+ - 404 if any of the required directories (SHA1 folder, result folder, Salamandra folder)
504
+ are missing.
505
+ - 404 if the `result.srt` file is not found.
506
+
507
+ Returns:
508
+ FileResponse: The SRT file (`result.srt`) with media type `text/srt`.
509
+ """
510
+ validate_token(token)
511
+
512
+ file_manager = FileManager(MEDIA_ROOT)
513
+ sha1_folder = MEDIA_ROOT / sha1
514
+ result_folder = sha1_folder / "result"
515
+ result_folder.mkdir(parents=True, exist_ok=True)
516
+ salamandra_folder = result_folder / "Salamandra"
517
+ salamandra_folder.mkdir(parents=True, exist_ok=True)
518
+ srt_final = salamandra_folder / "result.srt"
519
+
520
+ if not sha1_folder.exists() or not sha1_folder.is_dir():
521
+ raise HTTPException(status_code=404, detail="SHA1 folder not found")
522
+ if not result_folder.exists() or not result_folder.is_dir():
523
+ raise HTTPException(status_code=404, detail="result folder not found")
524
+ if not salamandra_folder.exists() or not salamandra_folder.is_dir():
525
+ raise HTTPException(status_code=404, detail="Salamandra folder not found")
526
+ if not srt_final.exists() or not srt_final.is_file():
527
+ raise HTTPException(status_code=404, detail="result.srt SRT not found")
528
+
529
+ return FileResponse(
530
+ path=srt_final,
531
+ media_type="text/srt",
532
+ filename="result.srt"
533
+ )
534
+
535
+ @router.get("/download_salamadra_free_narration", tags=["Salamandra Process"])
536
+ def download_salamadra_free_narration(
537
+ sha1: str,
538
+ token: str = Query(..., description="Token required for authorization")
539
+ ):
540
+ """
541
+ Download the free narration text file generated by the Salamandra process.
542
+
543
+ This endpoint retrieves `free_narration.txt` from the Salamandra result directory
544
+ associated with a specific SHA1 hash. The token is validated before accessing the
545
+ file system. If the file or required folders do not exist, appropriate HTTP
546
+ errors are returned.
547
+
548
+ Args:
549
+ sha1 (str): The SHA1 identifier for the processed media folder.
550
+ token (str): Authorization token required to access the file.
551
+
552
+ Raises:
553
+ HTTPException:
554
+ - 404 if the SHA1 folder, result folder, or Salamandra folder is missing.
555
+ - 404 if `free_narration.txt` is not found.
556
+
557
+ Returns:
558
+ FileResponse: The free narration text file with media type `text/srt`.
559
+ """
560
+ validate_token(token)
561
+
562
+ file_manager = FileManager(MEDIA_ROOT)
563
+ sha1_folder = MEDIA_ROOT / sha1
564
+ result_folder = sha1_folder / "result"
565
+ result_folder.mkdir(parents=True, exist_ok=True)
566
+ salamandra_folder = result_folder / "Salamandra"
567
+ salamandra_folder.mkdir(parents=True, exist_ok=True)
568
+ free_narration_salamandra = salamandra_folder / "free_narration.txt"
569
+
570
+ if not sha1_folder.exists() or not sha1_folder.is_dir():
571
+ raise HTTPException(status_code=404, detail="SHA1 folder not found")
572
+ if not result_folder.exists() or not result_folder.is_dir():
573
+ raise HTTPException(status_code=404, detail="result folder not found")
574
+ if not salamandra_folder.exists() or not salamandra_folder.is_dir():
575
+ raise HTTPException(status_code=404, detail="Salamandra folder not found")
576
+ if not free_narration_salamandra.exists() or not free_narration_salamandra.is_file():
577
+ raise HTTPException(status_code=404, detail="free_narration.txt not found")
578
+
579
+ return FileResponse(
580
+ path=free_narration_salamandra,
581
+ media_type="text/srt",
582
+ filename="free_narration.tx"
583
+ )
584
+
585
+ @router.get("/download_salamadra_csv_evaluation", tags=["Salamandra Process"])
586
+ def download_salamadra_csv_evaluation(
587
+ sha1: str,
588
+ token: str = Query(..., description="Token required for authorization")
589
+ ):
590
+ """
591
+ Download the evaluation CSV generated by the Salamandra processing workflow.
592
+
593
+ This endpoint returns the `evaluation.csv` file corresponding to the given SHA1 hash.
594
+ It performs token validation and ensures that the folder structure and file exist.
595
+ If any element is missing, a 404 HTTP error is raised.
596
+
597
+ Args:
598
+ sha1 (str): The SHA1 identifier representing the processed media directory.
599
+ token (str): Authorization token required for file retrieval.
600
+
601
+ Raises:
602
+ HTTPException:
603
+ - 404 if the SHA1 folder, result folder, or Salamandra folder does not exist.
604
+ - 404 if the `evaluation.csv` file is missing.
605
+
606
+ Returns:
607
+ FileResponse: The evaluation CSV file with media type `text/srt`.
608
+ """
609
+ validate_token(token)
610
+
611
+ file_manager = FileManager(MEDIA_ROOT)
612
+ sha1_folder = MEDIA_ROOT / sha1
613
+ result_folder = sha1_folder / "result"
614
+ result_folder.mkdir(parents=True, exist_ok=True)
615
+ salamandra_folder = result_folder / "Salamandra"
616
+ salamandra_folder.mkdir(parents=True, exist_ok=True)
617
+ csv_evaluacion = salamandra_folder / "evaluation.csv"
618
+
619
+ if not sha1_folder.exists() or not sha1_folder.is_dir():
620
+ raise HTTPException(status_code=404, detail="SHA1 folder not found")
621
+ if not result_folder.exists() or not result_folder.is_dir():
622
+ raise HTTPException(status_code=404, detail="result folder not found")
623
+ if not salamandra_folder.exists() or not salamandra_folder.is_dir():
624
+ raise HTTPException(status_code=404, detail="Salamandra folder not found")
625
+ if not csv_evaluacion.exists() or not csv_evaluacion.is_file():
626
+ raise HTTPException(status_code=404, detail="evaluation.csv CSV not found")
627
+
628
+ return FileResponse(
629
+ path=csv_evaluacion,
630
+ media_type="text/srt",
631
+ filename="evaluation.csv"
632
+ )