File size: 6,890 Bytes
b17b915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# narrator_agent.py
from __future__ import annotations
from typing import Dict, List, Any
from langgraph.graph import StateGraph, END
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from dataclasses import dataclass
import json
import time


@dataclass
class NarratorInput:
    dialogues_srt: str
    frame_descriptions: List[Dict[str, Any]]  # [{"timestamp": "00:01:23,000", "description": "..."}]
    une_guidelines_path: str
    max_cycles: int = 3


@dataclass
class NarratorOutput:
    narrative_text: str
    srt_text: str
    critic_feedback: str | None = None
    approved: bool = False


class NarrationSystem:
    """

    LangGraph-based multi-agent system:

    - NarratorNode: generates narration + SRT according to UNE-153010

    - CriticNode: evaluates conformity with UNE and coherence

    - IdentityManagerNode: adjusts character identification if needed

    - BackgroundDescriptorNode: fixes background/scene coherence

    """

    def __init__(self, model_url: str, une_guidelines_path: str):
        self.model_url = model_url
        self.une_guidelines_path = une_guidelines_path

        # LLM endpoints (each node could use a different deployment if desired)
        self.narrator_llm = ChatOpenAI(base_url=model_url, model="gpt-4o-mini", temperature=0.6)
        self.critic_llm = ChatOpenAI(base_url=model_url, model="gpt-4o-mini", temperature=0.3)
        self.identity_llm = ChatOpenAI(base_url=model_url, model="gpt-4o-mini", temperature=0.4)
        self.background_llm = ChatOpenAI(base_url=model_url, model="gpt-4o-mini", temperature=0.4)

        with open(une_guidelines_path, "r", encoding="utf-8") as f:
            self.une_rules = f.read()

        # Build LangGraph workflow
        self.graph = self.build_graph()

    # -----------------------------------------------------------
    # LangGraph nodes
    # -----------------------------------------------------------

    def narrator_node(self, state):
        dialogues = state["dialogues_srt"]
        frames = state["frame_descriptions"]

        prompt = ChatPromptTemplate.from_template("""

Eres un narrador de audiodescripciones según la norma UNE-153010.

Combina coherentemente los diálogos del siguiente SRT con las descripciones de escena dadas.



Sigue estas pautas:

- Genera una narración libre que integre ambos tipos de información.

- Evita redundancias o descripciones triviales.

- Limita la duración de las audiodescripciones para que quepan entre los diálogos.

- Devuelve **dos bloques**:

1️⃣ `NARRATION_TEXT`: narración libre completa en texto continuo.

2️⃣ `UNE_SRT`: subtítulos con los diálogos y las audiodescripciones UNE.



## DIÁLOGOS SRT

{dialogues}



## DESCRIPCIONES DE FRAMES

{frames}

        """)

        response = self.narrator_llm.invoke(prompt.format(dialogues=dialogues, frames=json.dumps(frames, ensure_ascii=False)))
        return {"narration": response.content, "critic_feedback": None, "approved": False}

    def critic_node(self, state):
        narration = state["narration"]
        prompt = ChatPromptTemplate.from_template("""

Actúa como un revisor experto en audiodescripción conforme a la norma UNE-153010.

Evalúa el siguiente texto y SRT generados, detectando:

- Incoherencias en asignación de personajes.

- Errores en la identificación de escenarios.

- Desviaciones respecto a la norma UNE-153010.

- Incoherencias narrativas generales.



Devuelve:

- "APPROVED" si el resultado es conforme.

- En caso contrario, una lista JSON con observaciones clasificadas en:

  - "characters"

  - "scenes"

  - "norma"

  - "coherence"



## NORMA UNE-153010

{une_rules}



## TEXTO Y SRT A EVALUAR

{narration}

        """)

        response = self.critic_llm.invoke(prompt.format(une_rules=self.une_rules, narration=narration))
        text = response.content.strip()

        if "APPROVED" in text.upper():
            return {"critic_feedback": None, "approved": True}
        return {"critic_feedback": text, "approved": False}

    def identity_node(self, state):
        fb = state.get("critic_feedback", "")
        narration = state["narration"]
        prompt = ChatPromptTemplate.from_template("""

El siguiente feedback señala incoherencias en personajes o diálogos.

Corrige únicamente esos aspectos manteniendo el resto igual.



## FEEDBACK

{fb}



## TEXTO ORIGINAL

{narration}

        """)
        response = self.identity_llm.invoke(prompt.format(fb=fb, narration=narration))
        return {"narration": response.content}

    def background_node(self, state):
        fb = state.get("critic_feedback", "")
        narration = state["narration"]
        prompt = ChatPromptTemplate.from_template("""

El siguiente feedback señala incoherencias en escenarios o contexto visual.

Ajusta las descripciones de fondo manteniendo el estilo y duración UNE.



## FEEDBACK

{fb}



## TEXTO ORIGINAL

{narration}

        """)
        response = self.background_llm.invoke(prompt.format(fb=fb, narration=narration))
        return {"narration": response.content}

    # -----------------------------------------------------------
    # Graph assembly
    # -----------------------------------------------------------

    def build_graph(self):
        g = StateGraph()
        g.add_node("NarratorNode", self.narrator_node)
        g.add_node("CriticNode", self.critic_node)
        g.add_node("IdentityManagerNode", self.identity_node)
        g.add_node("BackgroundDescriptorNode", self.background_node)

        g.set_entry_point("NarratorNode")
        g.add_edge("NarratorNode", "CriticNode")
        g.add_conditional_edges(
            "CriticNode",
            lambda state: "done" if state.get("approved") else "retry",
            {
                "done": END,
                "retry": "IdentityManagerNode",
            },
        )
        g.add_edge("IdentityManagerNode", "BackgroundDescriptorNode")
        g.add_edge("BackgroundDescriptorNode", "CriticNode")

        return g.compile()

    # -----------------------------------------------------------
    # Run loop
    # -----------------------------------------------------------

    def run(self, dialogues_srt: str, frame_descriptions: List[Dict[str, Any]], max_cycles: int = 3) -> NarratorOutput:
        state = {"dialogues_srt": dialogues_srt, "frame_descriptions": frame_descriptions}
        result = self.graph.invoke(state)
        return NarratorOutput(
            narrative_text=result.get("narration", ""),
            srt_text=result.get("narration", ""),  # could be parsed separately if model emits dual block
            critic_feedback=result.get("critic_feedback"),
            approved=result.get("approved", False),
        )