Delete page_modules
Browse filesFiles changed (5)
- page_modules/__init__.pyDeleted-1
- page_modules/analyze_transcriptions.pyDeleted-214
- page_modules/process_video.pyDeleted-215
- page_modules/statistics.pyDeleted-46
- page_modules/validation.pyDeleted-221
1"""Modular page renderers for the Veureu Streamlit app."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214"""UI logic for the "Analitzar video-transcripcions" page."""
from __future__ import annotations
from pathlib import Pathfrom typing import Dict
import streamlit as st
from utils import save_bytes
def render_analyze_transcriptions_page(api, permissions: Dict[str, bool]) -> None: st.header("Analitzar video-transcripcions") base_dir = Path("/tmp/data/videos")
if not base_dir.exists(): st.info("No s'ha trobat la carpeta **videos**. Crea-la i afegeix-hi subcarpetes amb els teus vídeos.") st.stop()
carpetes = [p.name for p in sorted(base_dir.iterdir()) if p.is_dir() and p.name != "completed"] if not carpetes: st.info("No s'ha trobat la carpeta **videos**. Crea-la i afegeix-hi subcarpetes amb els teus vídeos.") st.stop()
if "current_video" not in st.session_state: st.session_state.current_video = None
seleccio = st.selectbox("Selecciona un vídeo (carpeta):", carpetes, index=None, placeholder="Tria una carpeta…")
if seleccio != st.session_state.current_video: st.session_state.current_video = seleccio if "version_selector" in st.session_state: del st.session_state["version_selector"] st.session_state.add_ad_checkbox = False st.rerun()
if not seleccio: st.stop()
vid_dir = base_dir / seleccio mp4s = sorted(vid_dir.glob("*.mp4"))
col_video, col_txt = st.columns([2, 1], gap="large")
with col_video: subcarpetas_ad = [p.name for p in sorted(vid_dir.iterdir()) if p.is_dir()] default_index_sub = subcarpetas_ad.index("Salamandra") if "Salamandra" in subcarpetas_ad else 0 subcarpeta_seleccio = st.selectbox( "Selecciona una versió d'audiodescripció:", subcarpetas_ad, index=default_index_sub if subcarpetas_ad else None, placeholder="Tria una versió…" if subcarpetas_ad else "No hi ha versions", key="version_selector", )
video_ad_path = vid_dir / subcarpeta_seleccio / "une_ad.mp4" if subcarpeta_seleccio else None is_ad_video_available = video_ad_path is not None and video_ad_path.exists()
add_ad_video = st.checkbox( "Afegir audiodescripció", disabled=not is_ad_video_available, key="add_ad_checkbox", )
video_to_show = None if add_ad_video and is_ad_video_available: video_to_show = video_ad_path elif mp4s: video_to_show = mp4s[0]
if video_to_show: st.video(str(video_to_show)) else: st.warning("No s'ha trobat cap fitxer **.mp4** a la carpeta seleccionada.")
st.markdown("---") st.markdown("#### Accions") c1, c2 = st.columns(2) with c1: if st.button("Reconstruir àudio amb narració lliure", use_container_width=True, key="rebuild_free_ad"): if subcarpeta_seleccio: free_ad_path = vid_dir / subcarpeta_seleccio / "free_ad.txt" if free_ad_path.exists(): with st.spinner("Generant àudio de la narració lliure..."): text_content = free_ad_path.read_text(encoding="utf-8") voice = "central/grau" response = api.tts_matxa(text=text_content, voice=voice) if "mp3_bytes" in response: output_path = vid_dir / subcarpeta_seleccio / "free_ad.mp3" save_bytes(output_path, response["mp3_bytes"]) st.success(f"Àudio generat i desat a: {output_path}") else: st.error(f"Error en la generació de l'àudio: {response.get('error', 'Desconegut')}") else: st.warning("No s'ha trobat el fitxer 'free_ad.txt' en aquesta versió.")
with c2: if st.button("Reconstruir vídeo amb audiodescripció", use_container_width=True, key="rebuild_video_ad"): if subcarpeta_seleccio and mp4s: une_srt_path = vid_dir / subcarpeta_seleccio / "une_ad.srt" video_original_path = mp4s[0] if une_srt_path.exists(): with st.spinner( "Reconstruint el vídeo amb l'audiodescripció... Aquesta operació pot trigar una estona." ): response = api.rebuild_video_with_ad( video_path=str(video_original_path), srt_path=str(une_srt_path), ) if "video_bytes" in response: output_path = vid_dir / subcarpeta_seleccio / "video_ad_rebuilt.mp4" save_bytes(output_path, response["video_bytes"]) st.success(f"Vídeo reconstruït i desat a: {output_path}") st.info( "Pots visualitzar-lo activant la casella 'Afegir audiodescripció' i seleccionant el nou fitxer si cal." ) else: st.error(f"Error en la reconstrucció del vídeo: {response.get('error', 'Desconegut')}") else: st.warning("No s'ha trobat el fitxer 'une_ad.srt' en aquesta versió.")
with col_txt: tipus_ad_options = ["narració lliure", "UNE-153010"] tipus_ad_seleccio = st.selectbox("Fitxer d'audiodescripció a editar:", tipus_ad_options)
ad_filename = "free_ad.txt" if tipus_ad_seleccio == "narració lliure" else "une_ad.srt"
text_content = "" ad_path = None if subcarpeta_seleccio: ad_path = vid_dir / subcarpeta_seleccio / ad_filename if ad_path.exists(): try: text_content = ad_path.read_text(encoding="utf-8") except Exception: text_content = ad_path.read_text(errors="ignore") else: st.info(f"No s'ha trobat el fitxer **{ad_filename}**.") else: st.warning("Selecciona una versió per veure els fitxers.")
new_text = st.text_area( f"Contingut de {tipus_ad_seleccio}", value=text_content, height=500, key=f"editor_{seleccio}_{subcarpeta_seleccio}_{ad_filename}", )
if st.button( "▶️ Reproduir narració", use_container_width=True, disabled=not new_text.strip(), key="play_button_editor", ): with st.spinner("Generant àudio..."): pass
if st.button("Desar canvis", use_container_width=True, type="primary"): if ad_path: try: ad_path.write_text(new_text, encoding="utf-8") st.success(f"Fitxer **{ad_filename}** desat correctament.") st.rerun() except Exception as e: st.error(f"No s'ha pogut desar el fitxer: {e}") else: st.error("No s'ha seleccionat una ruta de fitxer vàlida per desar.")
st.markdown("---") st.subheader("Avaluació de la qualitat de l'audiodescripció")
can_rate = permissions.get("valorar", False) controls_disabled = not can_rate
c1, c2, c3 = st.columns(3) with c1: transcripcio = st.slider("Transcripció", 1, 10, 7, disabled=controls_disabled) identificacio = st.slider("Identificació de personatges", 1, 10, 7, disabled=controls_disabled) with c2: localitzacions = st.slider("Localitzacions", 1, 10, 7, disabled=controls_disabled) activitats = st.slider("Activitats", 1, 10, 7, disabled=controls_disabled) with c3: narracions = st.slider("Narracions", 1, 10, 7, disabled=controls_disabled) expressivitat = st.slider("Expressivitat", 1, 10, 7, disabled=controls_disabled)
comments = st.text_area( "Comentaris (opcional)", placeholder="Escriu els teus comentaris lliures…", height=120, disabled=controls_disabled, )
if not can_rate: st.info("El teu rol no permet enviar valoracions.") else: if st.button("Enviar valoració", type="primary", use_container_width=True): try: from database import add_feedback_ad
add_feedback_ad( video_name=seleccio, user_id=st.session_state.user["id"], transcripcio=transcripcio, identificacio=identificacio, localitzacions=localitzacions, activitats=activitats, narracions=narracions, expressivitat=expressivitat, comments=comments or None, ) st.success("Gràcies! La teva valoració s'ha desat correctament.") except Exception as e: st.error(f"S'ha produït un error en desar la valoració: {e}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215"""UI logic for the "Processar vídeo nou" page."""
from __future__ import annotations
import reimport shutilimport subprocessfrom pathlib import Path
import streamlit as st
def _get_video_duration(path: str) -> float: """Return video duration in seconds using ffprobe, ffmpeg or OpenCV as fallback.""" cmd = [ "ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", path, ] try: result = subprocess.run(cmd, capture_output=True, text=True, check=True) return float(result.stdout.strip()) except (subprocess.CalledProcessError, ValueError, FileNotFoundError): pass
if shutil.which("ffmpeg"): try: ffmpeg_cmd = ["ffmpeg", "-i", path] result = subprocess.run(ffmpeg_cmd, capture_output=True, text=True, check=False) output = result.stderr or result.stdout or "" match = re.search(r"Duration:\s*(\d+):(\d+):(\d+\.\d+)", output) if match: hours, minutes, seconds = match.groups() total_seconds = (int(hours) * 3600) + (int(minutes) * 60) + float(seconds) return float(total_seconds) except FileNotFoundError: pass
# Últim recurs: intentar amb OpenCV si està disponible try: import cv2
cap = cv2.VideoCapture(path) if cap.isOpened(): fps = cap.get(cv2.CAP_PROP_FPS) or 0 frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0 cap.release()
if fps > 0 and frame_count > 0: return float(frame_count / fps) else: cap.release() except Exception: pass
return 0.0
def _transcode_video(input_path: str, output_path: str, max_duration: int | None = None) -> None: cmd = ["ffmpeg", "-y", "-i", input_path] if max_duration is not None: cmd += ["-t", str(max_duration)] cmd += [ "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-c:a", "aac", "-movflags", "+faststart", output_path, ] result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0: raise RuntimeError(result.stderr.strip() or "ffmpeg failed")
def render_process_video_page() -> None: st.header("Processar un nou clip de vídeo")
# Inicializar el estado de la página si no existe if "video_uploaded" not in st.session_state: st.session_state.video_uploaded = None if "characters_detected" not in st.session_state: st.session_state.characters_detected = None if "characters_saved" not in st.session_state: st.session_state.characters_saved = False
# --- 1. Subida del vídeo --- MAX_SIZE_MB = 20 MAX_DURATION_S = 240 # 4 minutos
uploaded_file = st.file_uploader( "Puja un clip de vídeo (MP4, < 20MB, < 4 minuts)", type=["mp4"], key="video_uploader", )
if uploaded_file is not None: # Resetear el estado si se sube un nuevo archivo if st.session_state.video_uploaded is None or uploaded_file.name != st.session_state.video_uploaded.get( "original_name" ): st.session_state.video_uploaded = {"original_name": uploaded_file.name, "status": "validating"} st.session_state.characters_detected = None st.session_state.characters_saved = False
if st.session_state.video_uploaded["status"] == "validating": is_valid = True if uploaded_file.size > MAX_SIZE_MB * 1024 * 1024: st.error(f"El vídeo supera el límit de {MAX_SIZE_MB}MB.") is_valid = False
if is_valid: with st.spinner("Processant el vídeo..."): temp_path = Path("temp_video.mp4") with temp_path.open("wb") as f: f.write(uploaded_file.getbuffer())
was_truncated = False final_video_path = None try: duration = _get_video_duration(str(temp_path)) if not duration: st.error("No s'ha pogut obtenir la durada del vídeo.") is_valid = False
if is_valid: if duration > MAX_DURATION_S: was_truncated = True
video_name = Path(uploaded_file.name).stem video_dir = Path("/tmp/data/videos") / video_name video_dir.mkdir(parents=True, exist_ok=True) final_video_path = video_dir / f"{video_name}.mp4"
try: _transcode_video( str(temp_path), str(final_video_path), MAX_DURATION_S if was_truncated else None, ) except RuntimeError as exc: st.error(f"No s'ha pogut processar el vídeo: {exc}") is_valid = False
if is_valid and final_video_path is not None: st.session_state.video_uploaded.update( { "status": "processed", "path": str(final_video_path), "was_truncated": was_truncated, } ) st.rerun() finally: if temp_path.exists(): temp_path.unlink()
if st.session_state.video_uploaded and st.session_state.video_uploaded["status"] == "processed": st.success(f"Vídeo '{st.session_state.video_uploaded['original_name']}' pujat i processat correctament.") if st.session_state.video_uploaded["was_truncated"]: st.warning("El vídeo s'ha truncat a 4 minuts.")
st.markdown("---") col1, col2 = st.columns([1, 3]) with col1: detect_button_disabled = st.session_state.video_uploaded is None if st.button("Detectar Personatges", disabled=detect_button_disabled): with st.spinner("Detectant personatges..."): st.session_state.characters_detected = [ { "id": "char1", "image_path": "init_data/placeholder.png", "description": "Dona amb cabell ros i ulleres", }, { "id": "char2", "image_path": "init_data/placeholder.png", "description": "Home amb barba i barret", }, ] st.session_state.characters_saved = False
if st.session_state.characters_detected: st.subheader("Personatges detectats") for char in st.session_state.characters_detected: with st.form(key=f"form_{char['id']}"): col1, col2 = st.columns(2) with col1: st.image(char["image_path"], width=150) with col2: st.caption(char["description"]) st.text_input("Nom del personatge", key=f"name_{char['id']}") st.form_submit_button("Cercar")
st.markdown("---_**")
col1, col2, col3 = st.columns([1, 1, 2]) with col1: if st.button("Desar", type="primary"): st.session_state.characters_saved = True st.success("Personatges desats correctament.")
with col2: if st.session_state.characters_saved: st.button("Generar Audiodescripció")12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""UI logic for the "Estadístiques" page."""
from __future__ import annotations
import pandas as pdimport streamlit as st
from database import get_feedback_ad_stats
def render_statistics_page() -> None: st.header("Estadístiques")
stats = get_feedback_ad_stats() if not stats: st.caption("Encara no hi ha valoracions.") st.stop()
df = pd.DataFrame(stats, columns=stats[0].keys()) ordre = st.radio( "Ordre de rànquing", ["Descendent (millors primer)", "Ascendent (pitjors primer)"], horizontal=True, ) if ordre.startswith("Asc"): df = df.sort_values("avg_global", ascending=True) else: df = df.sort_values("avg_global", ascending=False)
st.subheader("Rànquing de vídeos") st.dataframe( df[ [ "video_name", "n", "avg_global", "avg_transcripcio", "avg_identificacio", "avg_localitzacions", "avg_activitats", "avg_narracions", "avg_expressivitat", ] ], use_container_width=True, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221"""UI logic for the "Validació" page."""
from __future__ import annotations
from datetime import datetimefrom pathlib import Pathfrom typing import Dict
import streamlit as st
def _build_candidates(runtime_videos: Path) -> Path: candidates = [ runtime_videos, Path(__file__).resolve().parent.parent / "videos", Path.cwd() / "videos", ] for candidate in candidates: if candidate.exists(): return candidate return candidates[0]
def render_validation_page( compliance_client, runtime_videos: Path, permissions: Dict[str, bool], username: str,) -> None: if not permissions.get("validar", False): st.warning("⚠️ No tens permisos per accedir a aquesta secció de validació.") st.stop()
st.header("🔍 Validació de Vídeos")
tab_videos, tab_ads = st.tabs(["📹 Validar Vídeos", "🎬 Validar Audiodescripcions"])
base_dir = _build_candidates(runtime_videos) if not base_dir.exists(): st.info("📝 No s'ha trobat la carpeta **videos**. Crea-la i afegeix-hi subcarpetes amb els teus vídeos.") st.stop()
with tab_videos: st.subheader("📹 Validar Vídeos Pujats")
video_folders = [] for folder in sorted(base_dir.iterdir()): if folder.is_dir() and folder.name != "completed": video_files = list(folder.glob("*.mp4")) + list(folder.glob("*.avi")) + list(folder.glob("*.mov")) if video_files: mod_time = folder.stat().st_mtime fecha = datetime.fromtimestamp(mod_time).strftime("%Y-%m-%d %H:%M") video_folders.append( { "name": folder.name, "path": str(folder), "created_at": fecha, "video_files": video_files, } )
if not video_folders: st.info("📝 No hi ha vídeos pujats pendents de validació.") else: opciones_video = [f"{video['name']} - {video['created_at']}" for video in video_folders] seleccion = st.selectbox( "Selecciona un vídeo per validar:", opciones_video, index=0 if opciones_video else None, )
if seleccion: indice = opciones_video.index(seleccion) video_seleccionat = video_folders[indice]
col1, col2 = st.columns([2, 1])
with col1: st.markdown("### 📹 Informació del Vídeo") st.markdown(f"**Nom:** {video_seleccionat['name']}") st.markdown(f"**Data:** {video_seleccionat['created_at']}") st.markdown(f"**Arxius:** {len(video_seleccionat['video_files'])} vídeos trobats")
if video_seleccionat["video_files"]: video_path = str(video_seleccionat["video_files"][0]) st.markdown("**Vídeo principal:**") st.video(video_path) else: st.warning("⚠️ No s'han trobat arxius de vídeo.")
with col2: st.markdown("### 🔍 Accions de Validació")
col_btn1, col_btn2 = st.columns(2)
with col_btn1: if st.button("✅ Acceptar", type="primary", key=f"accept_video_{video_seleccionat['name']}"): success = compliance_client.record_validator_decision( document_id=f"video_{video_seleccionat['name']}", validator_email=f"{username}@veureu.local", decision="acceptat", comments=f"Vídeo validat per {username}", ) if success: st.success("✅ Vídeo acceptat i registrat al servei de compliance") else: st.error("❌ Error registrant el veredicte")
with col_btn2: if st.button("❌ Rebutjar", type="secondary", key=f"reject_video_{video_seleccionat['name']}" ): success = compliance_client.record_validator_decision( document_id=f"video_{video_seleccionat['name']}", validator_email=f"{username}@veureu.local", decision="rebutjat", comments=f"Vídeo rebutjat per {username}", ) if success: st.success("✅ Vídeo rebutjat i registrat al servei de compliance") else: st.error("❌ Error registrant el veredicte")
with tab_ads: st.subheader("🎬 Validar Audiodescripcions")
videos_con_ad = [] if base_dir.exists(): for folder in sorted(base_dir.iterdir()): if folder.is_dir() and folder.name != "completed": for subfolder_name in ["MoE", "Salamandra"]: subfolder = folder / subfolder_name if subfolder.exists(): ad_files = list(subfolder.glob("*_ad.txt")) + list(subfolder.glob("*_ad.srt")) if ad_files: mod_time = folder.stat().st_mtime fecha = datetime.fromtimestamp(mod_time).strftime("%Y-%m-%d %H:%M") videos_con_ad.append( { "name": folder.name, "path": str(folder), "created_at": fecha, "ad_files": ad_files, "ad_folder": str(subfolder), } )
if not videos_con_ad: st.info("📝 No hi ha audiodescripcions pendents de validació.") else: videos_ad_ordenats = sorted(videos_con_ad, key=lambda x: x["created_at"], reverse=True) opciones_ad = [f"{video['name']} - {video['created_at']}" for video in videos_ad_ordenats]
seleccion_ad = st.selectbox( "Selecciona una audiodescripció per validar:", opciones_ad, index=0 if opciones_ad else None, )
if seleccion_ad: indice = opciones_ad.index(seleccion_ad) video_seleccionat = videos_ad_ordenats[indice]
col1, col2 = st.columns([2, 1])
with col1: st.markdown("### 🎬 Informació de l'Audiodescripció") st.markdown(f"**Vídeo:** {video_seleccionat['name']}") st.markdown(f"**Data:** {video_seleccionat['created_at']}") st.markdown(f"**Carpeta:** {Path(video_seleccionat['ad_folder']).name}") st.markdown(f"**Arxius:** {len(video_seleccionat['ad_files'])} audiodescripcions trobades")
if video_seleccionat["ad_files"]: ad_path = video_seleccionat["ad_files"][0] st.markdown(f"#### 📄 Contingut ({ad_path.name}):") try: texto = ad_path.read_text(encoding="utf-8") except Exception: texto = ad_path.read_text(errors="ignore") st.text_area("Contingut de l'audiodescripció:", texto, height=300, disabled=True) else: st.warning("⚠️ No s'han trobat arxius d'audiodescripció.")
with col2: st.markdown("### 🔍 Accions de Validació")
col_btn1, col_btn2 = st.columns(2)
with col_btn1: if st.button("✅ Acceptar", type="primary", key=f"accept_ad_{video_seleccionat['name']}"): success = compliance_client.record_validator_decision( document_id=f"ad_{video_seleccionat['name']}", validator_email=f"{username}@veureu.local", decision="acceptat", comments=f"Audiodescripció validada per {username}", ) if success: st.success("✅ Audiodescripció acceptada i registrada al servei de compliance") else: st.error("❌ Error registrant el veredicte")
with col_btn2: if st.button("❌ Rebutjar", type="secondary", key=f"reject_ad_{video_seleccionat['name']}" ): success = compliance_client.record_validator_decision( document_id=f"ad_{video_seleccionat['name']}", validator_email=f"{username}@veureu.local", decision="rebutjat", comments=f"Audiodescripció rebutjada per {username}", ) if success: st.success("✅ Audiodescripció rebutjada i registrada al servei de compliance") else: st.error("❌ Error registrant el veredicte")
st.markdown("---") st.markdown("### ℹ️ Informació del Procés de Validació") st.markdown( """ - **Tots els veredictes** es registren al servei de compliance per garantir la traçabilitat - **Cada validació** inclou veredicte, nom del vídeo i validador responsable - **Els registres** compleixen amb la normativa AI Act i GDPR """ )page_modules/__init__.pyDeleted-1
page_modules/analyze_transcriptions.pyDeleted-214
page_modules/process_video.pyDeleted-215
page_modules/statistics.pyDeleted-46
page_modules/validation.pyDeleted-221