File size: 17,619 Bytes
34b52e0
 
e4073dc
34b52e0
 
1549856
 
34b52e0
 
 
a26a0d1
1549856
34b52e0
 
1549856
 
 
 
 
34b52e0
a26a0d1
ebbc799
e4073dc
 
34b52e0
1549856
 
 
34b52e0
 
 
 
 
 
 
 
 
1549856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4073dc
 
34b52e0
 
e4073dc
34b52e0
 
 
 
e4073dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ed6591
f8a828a
e4073dc
 
 
 
 
 
 
5ed6591
f8a828a
34b52e0
 
e4073dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34b52e0
 
1549856
 
 
 
 
 
 
 
 
 
ebbc799
 
 
 
 
a26a0d1
0136d07
 
 
 
 
e51cfa9
a26a0d1
0136d07
a26a0d1
 
e51cfa9
a26a0d1
e4073dc
1549856
e4073dc
a26a0d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebbc799
a26a0d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebbc799
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a26a0d1
 
 
 
 
 
e51cfa9
a26a0d1
ebbc799
a26a0d1
 
 
 
34b52e0
 
 
e51cfa9
 
 
 
 
 
1549856
34b52e0
f1cf4a9
 
 
a26a0d1
1549856
f1cf4a9
 
 
 
a26a0d1
f1cf4a9
1549856
 
 
 
 
 
 
 
 
f1cf4a9
1549856
 
34b52e0
 
ebbc799
 
1549856
f1cf4a9
949430d
 
2aae2f0
 
 
f1cf4a9
1549856
 
 
 
 
 
 
34b52e0
 
2aae2f0
f1cf4a9
f8a828a
1549856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34b52e0
2aae2f0
9deba43
1549856
 
 
 
 
 
 
 
f1cf4a9
1549856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34b52e0
1549856
a26a0d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34b52e0
1549856
34b52e0
 
 
 
a26a0d1
9deba43
a26a0d1
34b52e0
ebbc799
1549856
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
"""WitGym engine β€” pure function core. No I/O, no UI.

This is the single file that both CLI (main.py) and Gradio (app.py) call.
"""
import re
import time
from typing import Iterator, Optional
from loguru import logger
from sentence_transformers import SentenceTransformer
from witgym import config
from witgym.model import load_model, generate_text
from witgym.schemas import WitGymResponse, PipelineEvent, fallback_metadata
from witgym.extractor import extract_comedy_metadata
from witgym.retriever import load_index, retrieve_scenes
from witgym.generator import (
    generate_candidates_stream,
    rank_candidates,
    compress_winner_stream,
)
from witgym.conversation import ConversationManager
from witgym.router import classify_intent
from witgym.prompts import BANTER_PROMPT, COACHING_ASK_PROMPT, EXPLAIN_PROMPT, SHARPEN_PROMPT, DRILL_KEYS

_shared_resources = None

STREAM_MIN_INTERVAL = 0.08
STREAM_MIN_CHARS = 3


def _cap_two_sentences(text: str) -> str:
    """Hard cap at 2 sentences β€” safety net if model ignores prompt constraint."""
    sentences = re.split(r'(?<=[.!?])\s+', text.strip())
    if len(sentences) <= 2:
        return text.strip()
    return " ".join(sentences[:2]).strip()


def _maybe_emit_token(
    phase: str,
    persona: Optional[str],
    acc: str,
    last_emit: float,
    metadata,
    scenes,
    candidates,
    **extra,
) -> tuple[Optional[PipelineEvent], float, str]:
    now = time.monotonic()
    if len(acc) >= STREAM_MIN_CHARS or (now - last_emit) >= STREAM_MIN_INTERVAL:
        event = PipelineEvent(
            phase=phase,
            persona=persona,
            partial_text=acc,
            metadata=metadata,
            scenes=scenes,
            candidates=candidates,
            **extra,
        )
        return event, now, ""
    return None, last_emit, acc


class SharedResources:
    """Heavy resources loaded once per process (model/tokenizer, embedder, index)."""

    def __init__(self, index_path: str = config.INDEX_PATH):
        logger.info("Loading shared WitGym resources...")
        self.model, self.tokenizer = load_model()
        logger.info(f"Loading embedding model: {config.EMBED_MODEL_ID}")
        self.embed_model = SentenceTransformer(config.EMBED_MODEL_ID, device=config.DEVICE)
        self.index = load_index(index_path)
        logger.success("Shared resources ready.")


def get_shared_resources(index_path: str = config.INDEX_PATH) -> SharedResources:
    """Process-wide singleton for Spaces / Gradio multi-session use."""
    global _shared_resources
    if _shared_resources is None:
        _shared_resources = SharedResources(index_path=index_path)
    return _shared_resources


class WitGymEngine:
    """Stateful engine. Load once, call respond() in a loop."""

    def __init__(
        self,
        index_path: str = config.INDEX_PATH,
        resources: Optional[SharedResources] = None,
        conversation: Optional[ConversationManager] = None,
        last_wit_response: Optional[WitGymResponse] = None,
        character: str = "AI",
    ):
        if resources is None:
            logger.info("Initialising WitGymEngine...")
            self._resources = SharedResources(index_path=index_path)
        else:
            self._resources = resources
        self.conversation = conversation or ConversationManager()
        self._last_wit_response: Optional[WitGymResponse] = last_wit_response
        self.character = character
        logger.success("WitGymEngine ready.")

    @property
    def model(self):
        return self._resources.model

    @property
    def tokenizer(self):
        return self._resources.tokenizer

    @property
    def embed_model(self):
        return self._resources.embed_model

    @property
    def index(self):
        return self._resources.index

    def respond(self, user_input: str) -> WitGymResponse:
        """Full two-pass pipeline. Returns WitGymResponse with all intermediate data."""
        result = None
        for event in self.respond_stream(user_input):
            if event.phase == "done" and event.response is not None:
                result = event.response
        if result is None:
            raise RuntimeError("respond_stream did not emit a done event")
        return result

    def respond_stream(self, user_input: str) -> Iterator[PipelineEvent]:
        """Incremental pipeline for Gradio streaming UI."""
        drill_type = DRILL_KEYS.get(user_input.strip())
        if drill_type and self._last_wit_response is not None:
            yield from self._handle_drill(drill_type, self._last_wit_response)
            return

        if self.conversation.coaching_state.get("awaiting"):
            from witgym.router import _heuristic_route
            if _heuristic_route(user_input) == "banter" or len(user_input.strip()) < 5:
                self.conversation.coaching_state = {}
                yield from self._handle_banter(user_input)
                return
            original = self.conversation.coaching_state.get("original_input", user_input)
            yield from self._run_wit_pipeline(
                user_input,
                route="coaching",
                display_input=user_input,
                coaching_context=(original, user_input),
                include_explanation=True,
            )
            return

        route = classify_intent(user_input, self.model, self.tokenizer)

        if route == "banter":
            yield from self._handle_banter(user_input)
            return

        if route == "coaching":
            yield from self._handle_coaching_ask(user_input)
            return

        self.conversation.set_mode("quick_wit")
        yield from self._run_wit_pipeline(user_input, route="quick_wit")

    def _handle_banter(self, user_input: str) -> Iterator[PipelineEvent]:
        logger.info("Banter route β€” dynamic reply")
        self.conversation.set_mode("banter")
        self._last_wit_response = None
        reply = generate_text(
            BANTER_PROMPT.format(user_input=user_input),
            self.model,
            self.tokenizer,
            config_type="generate",
        )
        reply = _cap_two_sentences(reply.strip())
        if not reply or reply.lstrip().startswith("1.") or "analyze user" in reply.lower():
            reply = "I'm here for awkward moments and sharp comebacks β€” toss me a situation."
        metadata = fallback_metadata(user_input)
        self.conversation.add_turn(user_input, reply, metadata, mode="banter")
        response = WitGymResponse(
            metadata=metadata,
            retrieved_scenes=[],
            candidates=[],
            selected=reply,
            route="banter",
        )
        yield PipelineEvent(phase="banter", response=response)
        yield PipelineEvent(phase="done", response=response)

    def _handle_coaching_ask(self, user_input: str) -> Iterator[PipelineEvent]:
        logger.info("Coaching route β€” Turn 1 clarifying question")
        self.conversation.set_mode("coaching")
        question = generate_text(
            COACHING_ASK_PROMPT.format(user_input=user_input),
            self.model,
            self.tokenizer,
            config_type="generate",
        )
        question = question.strip().split("\n")[0].strip() or "What did you actually say back?"
        self.conversation.coaching_state = {
            "awaiting": True,
            "original_input": user_input,
        }
        metadata = fallback_metadata(user_input)
        response = WitGymResponse(
            metadata=metadata,
            retrieved_scenes=[],
            candidates=[],
            selected=question,
            route="coaching",
            coaching_question=question,
        )
        yield PipelineEvent(phase="coaching_ask", partial_text=question, response=response)
        yield PipelineEvent(phase="done", response=response)

    def _handle_drill(self, drill_type: str, last: WitGymResponse) -> Iterator[PipelineEvent]:
        """Refine the last wit response. Does NOT call add_turn() β€” no memory pollution."""
        joke = last.selected
        metadata = last.metadata

        if drill_type == "angle":
            yield from self._run_wit_pipeline(
                metadata.surface,
                route=last.route,
                exclude_joke=joke,
            )
            return

        if drill_type == "sharpen":
            situation = last.retrieved_scenes[0].setup if last.retrieved_scenes else metadata.surface
            reply = generate_text(
                SHARPEN_PROMPT.format(situation=situation, joke=joke, subtext=metadata.subtext),
                self.model, self.tokenizer, config_type="generate",
            )
            reply = _cap_two_sentences(reply.strip())
            self._last_wit_response = WitGymResponse(
                metadata=metadata,
                retrieved_scenes=last.retrieved_scenes,
                candidates=last.candidates,
                selected=reply,
                route=last.route,
                winning_persona=last.winning_persona,
            )
        else:  # explain
            reply = generate_text(
                EXPLAIN_PROMPT.format(
                    joke=joke,
                    archetype=metadata.archetype.value,
                    subtext=metadata.subtext,
                ),
                self.model, self.tokenizer, config_type="generate",
            )
            reply = _cap_two_sentences(reply.strip())

        response = WitGymResponse(
            metadata=metadata,
            retrieved_scenes=last.retrieved_scenes,
            candidates=last.candidates,
            selected=reply,
            route="drill",
        )
        yield PipelineEvent(phase="banter", response=response)
        yield PipelineEvent(phase="done", response=response)

    def _run_wit_pipeline(
        self,
        user_input: str,
        route: str = "quick_wit",
        *,
        display_input: Optional[str] = None,
        coaching_context: Optional[tuple[str, str]] = None,
        include_explanation: bool = False,
        exclude_joke: Optional[str] = None,
    ) -> Iterator[PipelineEvent]:
        """CBR-RAG pipeline shared by quick_wit and coaching Turn 2."""
        turn_user_input = display_input or user_input

        if self.conversation.needs_compression(self.tokenizer):
            self.conversation.compress(self.model, self.tokenizer)

        metadata = extract_comedy_metadata(
            user_input,
            self.model,
            self.tokenizer,
            coaching_context=coaching_context,
        )
        yield PipelineEvent(phase="metadata", metadata=metadata)

        if metadata.twist_potential < 4:
            logger.info(f"twist_potential={metadata.twist_potential} < 4 β€” returning straight reply")
            selected = "Yeah, that tracks."
            self.conversation.add_turn(turn_user_input, selected, metadata, mode=route)
            response = WitGymResponse(
                metadata=metadata,
                retrieved_scenes=[],
                candidates=[],
                selected=selected,
                route=route,
            )
            yield PipelineEvent(
                phase="ranked",
                metadata=metadata,
                scenes=[],
                candidates=[],
                selected=selected,
            )
            yield PipelineEvent(phase="done", response=response)
            return

        scenes = retrieve_scenes(self.index, metadata, self.embed_model)
        yield PipelineEvent(phase="scenes", metadata=metadata, scenes=scenes)

        context_str = self.conversation.get_context_string()
        if exclude_joke:
            context_str = f"[Previous line β€” do NOT repeat]: {exclude_joke}\n" + context_str
        personas_to_run = ["cynic", "conviction", "absurdist"]
        if metadata.twist_potential <= 6:
            personas_to_run = ["cynic", "absurdist"]
            logger.info(f"twist_potential={metadata.twist_potential} ≀ 6 β€” cynic + absurdist")
        elif metadata.twist_potential > 8:
            personas_to_run = ["cynic", "absurdist", "bisociate"]
            logger.info(f"twist_potential={metadata.twist_potential} > 8 β€” bisociate replaces conviction")

        candidates = []
        candidate_acc = ""
        candidate_persona: Optional[str] = None
        last_emit = 0.0
        pending_chars = ""

        for item in generate_candidates_stream(
            user_input, metadata, scenes,
            self.model, self.tokenizer,
            context_str,
            personas_to_run=personas_to_run,
            character=self.character,
        ):
            event_type = item[0]
            payload = item[1] if len(item) == 2 else item[1:]
            if event_type == "candidate_start":
                candidate_acc = ""
                candidate_persona = payload
                yield PipelineEvent(
                    phase="candidate_start",
                    persona=payload,
                    metadata=metadata,
                    scenes=scenes,
                    candidates=list(candidates),
                )
            elif event_type == "candidate_token":
                persona_name, token_piece = payload
                candidate_acc += token_piece
                pending_chars += token_piece
                evt, last_emit, pending_chars = _maybe_emit_token(
                    "candidate_token",
                    persona_name,
                    pending_chars,
                    last_emit,
                    metadata,
                    scenes,
                    list(candidates),
                )
                if evt:
                    evt.partial_text = candidate_acc
                    yield evt
            elif event_type == "candidate_done":
                if pending_chars and candidate_persona:
                    yield PipelineEvent(
                        phase="candidate_token",
                        persona=candidate_persona,
                        partial_text=candidate_acc,
                        metadata=metadata,
                        scenes=scenes,
                        candidates=list(candidates),
                    )
                    pending_chars = ""
                if payload is not None:
                    candidates.append(payload)
                yield PipelineEvent(
                    phase="candidate_done",
                    persona=getattr(payload, "persona", None),
                    metadata=metadata,
                    scenes=scenes,
                    candidates=list(candidates),
                )
            elif event_type == "candidates_complete":
                candidates = payload

        selected = rank_candidates(user_input, metadata, candidates, self.model, self.tokenizer)
        winning_persona = next((c.persona for c in candidates if c.text == selected), None)
        yield PipelineEvent(
            phase="ranked",
            metadata=metadata,
            scenes=scenes,
            candidates=candidates,
            selected=selected,
            winning_persona=winning_persona,
        )

        yield PipelineEvent(phase="final_start", partial_text=selected, winning_persona=winning_persona)
        compressed = selected
        final_acc = ""
        pending_chars = ""
        last_emit = 0.0
        for event_type, payload in compress_winner_stream(selected, self.model, self.tokenizer):
            if event_type == "skip":
                compressed = payload
                yield PipelineEvent(phase="final_token", partial_text=compressed, winning_persona=winning_persona)
            elif event_type == "start":
                final_acc = selected
            elif event_type == "token":
                final_acc += payload
                pending_chars += payload
                evt, last_emit, pending_chars = _maybe_emit_token(
                    "final_token",
                    winning_persona,
                    pending_chars,
                    last_emit,
                    metadata,
                    scenes,
                    candidates,
                    winning_persona=winning_persona,
                )
                if evt:
                    evt.partial_text = final_acc
                    yield evt
            elif event_type == "done":
                if pending_chars:
                    yield PipelineEvent(
                        phase="final_token",
                        partial_text=final_acc,
                        winning_persona=winning_persona,
                    )
                compressed = payload

        selected = _cap_two_sentences(compressed)
        explanation = None
        if include_explanation:
            explanation = generate_text(
                EXPLAIN_PROMPT.format(
                    joke=selected,
                    archetype=metadata.archetype.value,
                    subtext=metadata.subtext,
                ),
                self.model,
                self.tokenizer,
                config_type="generate",
            )
            explanation = _cap_two_sentences(explanation.strip())

        self.conversation.add_turn(turn_user_input, selected, metadata, mode=route)

        response = WitGymResponse(
            metadata=metadata,
            retrieved_scenes=scenes,
            candidates=candidates,
            selected=selected,
            route=route,
            winning_persona=winning_persona,
            explanation=explanation,
        )
        self._last_wit_response = response
        yield PipelineEvent(phase="done", response=response)