Spaces:
Runtime error
Runtime error
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260import osimport jsonimport numpy as npimport matplotlib.pyplot as pltfrom scipy.interpolate import make_interp_splinefrom typing import List, Optional, Literal, Dict, Tuplefrom pydantic import BaseModel, Fieldimport networkx as nximport gradio as grfrom huggingface_hub import InferenceClientfrom collections import defaultdict
# ------------------------------------------------------------------# 1. Modelos Pydantic (igual que antes, para validación)# ------------------------------------------------------------------class InteractionNode(BaseModel): id: int = Field(..., description="Identificador secuencial único (1-based) del turno.") speaker: str = Field(..., description="Nombre normalizado y consistente del hablante.") content_summary: str = Field(..., description="Resumen breve y objetivo del contenido del mensaje.") reply_to_id: Optional[int] = Field( None, description="ID del turno al que responde directamente. None si inicia un hilo nuevo o es general." ) topic_label: str = Field(..., description="Etiqueta corta del tema principal (ej. 'Planificación', 'Social').") is_topic_shift: bool = Field(False, description="True si este turno introduce un cambio significativo de tema.") sentiment_score: float = Field( ..., ge=-1.0, le=1.0, description="Sentimiento del mensaje: -1.0 (muy negativo) a 1.0 (muy positivo)." ) interaction_type: Literal['statement', 'question', 'answer', 'interruption', 'agreement', 'disagreement'] = Field( ..., description="Tipo de acto de habla." )
class ConversationSegment(BaseModel): interactions: List[InteractionNode] active_participants: List[str] dominant_topic: str
# ------------------------------------------------------------------# 2. Cliente Hugging Face Inference (modelo potente y gratuito vía serverless)# ------------------------------------------------------------------client = InferenceClient(model="meta-llama/Meta-Llama-3.1-70B-Instruct")# Alternativa excelente: "Qwen/Qwen2.5-72B-Instruct"
# ------------------------------------------------------------------# 3. Parsing del transcript# ------------------------------------------------------------------def parse_transcript(raw_transcript: str) -> List[Dict[str, str]]: messages = [] for line_num, line in enumerate(raw_transcript.strip().split("\n"), 1): if ":" in line: speaker, text = line.split(":", 1) messages.append({"id": line_num, "speaker": speaker.strip(), "text": text.strip()}) return messages
# ------------------------------------------------------------------# 4. Análisis con LLM de Hugging Face (prompt reforzado para JSON)# ------------------------------------------------------------------def analyze_conversation(messages: List[Dict[str, str]]) -> ConversationSegment: numbered_lines = [f"{msg['id']}. {msg['speaker']}: {msg['text']}" for msg in messages] transcript_text = "\n".join(numbered_lines)
system_prompt = ( "You are an expert conversation analyst. Analyze the provided transcript turn by turn. " "Normalize speaker names consistently. Infer direct replies accurately. " "Detect topic shifts, sentiment, and speech act type. " "Output ONLY a valid JSON object matching the exact structure below. " "No additional text, explanations, or markdown." )
schema_description = """ { "interactions": [ { "id": integer, "speaker": string, "content_summary": string, "reply_to_id": integer or null, "topic_label": string, "is_topic_shift": boolean, "sentiment_score": float (-1.0 to 1.0), "interaction_type": one of ["statement", "question", "answer", "interruption", "agreement", "disagreement"] } ], "active_participants": [string], "dominant_topic": string } """
full_prompt = f"{system_prompt}\n\nSchema:\n{schema_description}\n\nTranscript:\n{transcript_text}\n\nJSON output:"
response = client.text_generation( full_prompt, max_new_tokens=8192, temperature=0.1, stop_sequences=["</s>", "\n\n"] )
text = response.strip() # Limpieza básica por si incluye markdown if text.startswith("```json"): text = text[7:] if text.endswith("```"): text = text[:-3] text = text.strip()
try: data = json.loads(text) return ConversationSegment(**data) except json.JSONDecodeError as e: raise ValueError(f"Error al parsear JSON del modelo: {e}\nRespuesta recibida: {text}")
# ------------------------------------------------------------------# 5. Construcción de grafo y posiciones Y (con mejora de centralidad)# ------------------------------------------------------------------def build_graph_and_positions(interactions: List[InteractionNode]) -> Tuple[Dict[str, List[Tuple[int, float]]], List[int], Dict[str, float]]: G = nx.DiGraph() for node in interactions: if node.reply_to_id is not None: target_node = next((n for n in interactions if n.id == node.reply_to_id), None) if target_node: G.add_edge(node.speaker, target_node.speaker) # speaker responde a target
# Centralidad (in-degree como influencia recibida) in_degree = dict(G.in_degree()) max_degree = max(in_degree.values()) if in_degree else 1 centrality = {speaker: in_degree.get(speaker, 0) / max_degree for speaker in {n.speaker for n in interactions}}
# Posiciones Y (greedy bundling) current_order: List[str] = [] position_history: Dict[str, List[Tuple[int, float]]] = defaultdict(list) topic_shifts: List[int] = []
for node in interactions: t = node.id speaker = node.speaker
if node.is_topic_shift: topic_shifts.append(t)
if speaker not in current_order: current_order.append(speaker)
if node.reply_to_id: target_node = next((n for n in interactions if n.id == node.reply_to_id), None) if target_node and target_node.speaker in current_order: current_order.remove(speaker) target_idx = current_order.index(target_node.speaker) current_order.insert(target_idx + 1, speaker)
for rank, sp in enumerate(current_order): position_history[sp].append((t, rank))
return position_history, topic_shifts, centrality
# ------------------------------------------------------------------# 6. Renderizado XKCD# ------------------------------------------------------------------def render_storyline(position_history, interactions, topic_shifts, centrality, output_path="storyline.png"): speech_counts = defaultdict(int) for node in interactions: speech_counts[node.speaker] += 1 max_speeches = max(speech_counts.values()) if speech_counts else 1
with plt.xkcd(): fig, ax = plt.subplots(figsize=(20, 12)) colors = plt.cm.tab20(np.linspace(0, 1, 20)) color_map = {} color_idx = 0
for speaker, points in position_history.items(): if not points: continue ts, ys = zip(*points) t_smooth = np.linspace(min(ts), max(ts), 500) spl = make_interp_spline(ts, ys, k=min(3, len(ts)-1)) y_smooth = spl(t_smooth)
if speaker not in color_map: color_map[speaker] = colors[color_idx % 20] color_idx += 1
# Grosor combinado: participación + centralidad linewidth = 2.0 + 8.0 * (speech_counts[speaker] / max_speeches + centrality.get(speaker, 0))
ax.plot(t_smooth, y_smooth, color=color_map[speaker], linewidth=linewidth, label=speaker) ax.text(t_smooth[0] - 0.5, y_smooth[0], speaker, fontsize=12, ha='right', va='center')
for t in topic_shifts: ax.axvline(t, color='gray', linestyle='--', alpha=0.6) ax.text(t, ax.get_ylim()[1] * 0.95, 'Cambio\nde tema', rotation=90, va='top', ha='right', fontsize=10, color='gray')
ax.set_xlabel('Progresión temporal (turnos)') ax.set_title('Visualización Narrativa de Dinámicas Conversacionales (estilo XKCD)') ax.set_yticks([]) plt.tight_layout() plt.savefig(output_path, dpi=200) plt.close() return output_path
# ------------------------------------------------------------------# 7. Pipeline principal para Gradio# ------------------------------------------------------------------def process_transcript(transcript: str): if not transcript.strip(): raise gr.Error("Por favor ingrese una transcripción.") messages = parse_transcript(transcript) if len(messages) < 2: raise gr.Error("La transcripción debe contener al menos dos mensajes.") segment = analyze_conversation(messages) position_history, topic_shifts, centrality = build_graph_and_positions(segment.interactions) image_path = render_storyline(position_history, segment.interactions, topic_shifts, centrality) summary = f"Participantes: {', '.join(segment.active_participants)}\nTema dominante: {segment.dominant_topic}\nTurnos analizados: {len(segment.interactions)}" return image_path, summary
# ------------------------------------------------------------------# 8. Interfaz Gradio# ------------------------------------------------------------------with gr.Blocks(title="Conversation Storyline Visualizer") as demo: gr.Markdown("# Visualización Narrativa de Conversaciones (estilo XKCD)") gr.Markdown("Ingrese una transcripción en formato **Speaker: mensaje** (una línea por turno). El sistema analizará la estructura conversacional y generará una visualización narrativa.") with gr.Row(): input_text = gr.Textbox(label="Transcripción", lines=15, placeholder="Alice: Hola...\nBob: Bien, gracias...") btn = gr.Button("Generar visualización") with gr.Row(): output_image = gr.Image(label="Visualización narrativa") output_summary = gr.Textbox(label="Resumen del análisis", lines=6) gr.Examples( examples=[ ["""Alice: ¡Hola a todos! ¿Cómo están?Bob: Hola Alice, bien gracias.Charlie: Hey genteAlice: ¿Alguien ha visto la nueva película de sci-fi?Bob: Sí, está genialCharlie: ¿Cuál? Yo quiero recomendacionesDavid: Perdón por llegar tarde. ¿De qué hablamos?Alice: De películas, DavidBob: Pero volviendo al trabajo, ¿avanzaron el reporte?Charlie: Yo sí, terminé mi parteDavid: Yo tambiénAlice: Perfecto, entonces mañana lo revisamosCharlie: Por cierto, ¿quién va al almuerzo hoy?Bob: Yo paso, tengo reunión """] ], inputs=input_text ) btn.click(fn=process_transcript, inputs=input_text, outputs=[output_image, output_summary])
demo.launch()app.pyAdded+260