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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
import asyncio
import os
import traceback
from collections import defaultdict
from collections.abc import Coroutine
from typing import Any

from jinja2 import Template

from pptagent.agent import Agent
from pptagent.llms import LLM, AsyncLLM
from pptagent.model_utils import (
    get_cluster,
    get_image_embedding,
    images_cosine_similarity,
)
from pptagent.presentation import Picture, Presentation, SlidePage
from pptagent.utils import (
    Config,
    edit_distance,
    get_logger,
    is_image_path,
    package_join,
    pjoin,
)

logger = get_logger(__name__)

CATEGORY_SPLIT_TEMPLATE = Template(
    open(package_join("prompts", "category_split.txt")).read()
)
ASK_CATEGORY_PROMPT = open(package_join("prompts", "ask_category.txt")).read()


def check_schema(schema: dict | Any, slide: SlidePage):
    if not isinstance(schema, dict):
        raise ValueError(
            f"Output schema should be a dict, but got {type(schema)}: {schema}\n",
            """  {

                "element_name": {

                    "description": "purpose of this element", # do not mention any detail, just purpose

                    "type": "text" or "image",

                    "data": ["text1", "text2"] or ["logo:...", "logo:..."]

                    }

            }""",
        )

    similar_ele = None
    max_similarity = -1
    for el_name, element in schema.items():
        if "data" not in element or len(element["data"]) == 0:
            raise ValueError(
                f"Empty element is not allowed, but got {el_name}: {element}. Content of each element should be in the `data` field.\n",
                "If this infered to an empty or unexpected element, remove it from the schema.",
            )
        if not isinstance(element["data"], list):
            logger.debug("Converting single text element to list: %s", element["data"])
            element["data"] = [element["data"]]
        if element["type"] == "text":

            for item in element["data"]:
                for para in slide.iter_paragraphs():
                    similarity = edit_distance(para.text, item)
                    if similarity > 0.8:
                        break
                    if similarity > max_similarity:
                        max_similarity = similarity
                        similar_ele = para.text
                else:
                    raise ValueError(
                        f"Text element `{el_name}` contains text `{item}` that does not match any single paragraph <p> in the current slide. The most similar paragraph found was `{similar_ele}`.",
                        "This error typically occurs when either: 1) multiple paragraphs are incorrectly merged into a single element, or 2) a single paragraph is incorrectly split into multiple items.",
                    )

        elif element["type"] == "image":

            for caption in element["data"]:
                for shape in slide.shape_filter(Picture):
                    similarity = edit_distance(shape.caption, caption)
                    if similarity > 0.8:
                        break
                    if similarity > max_similarity:
                        max_similarity = similarity
                        similar_ele = shape.caption
                else:
                    raise ValueError(
                        f"Image caption of {el_name}: {caption} not found in the `alt` attribute of <img> elements of current slide, the most similar caption is {similar_ele}"
                    )

        else:
            raise ValueError(
                f"Unknown type of {el_name}: {element['type']}, should be one of ['text', 'image']"
            )


class SlideInducter:
    """

    Stage I: Presentation Analysis.

    This stage is to analyze the presentation: cluster slides into different layouts, and extract content schema for each layout.

    """

    def __init__(

        self,

        prs: Presentation,

        ppt_image_folder: str,

        template_image_folder: str,

        config: Config,

        image_models: list,

        language_model: LLM,

        vision_model: LLM,

        use_assert: bool = True,

    ):
        """

        Initialize the SlideInducter.



        Args:

            prs (Presentation): The presentation object.

            ppt_image_folder (str): The folder containing PPT images.

            template_image_folder (str): The folder containing normalized slide images.

            config (Config): The configuration object.

            image_models (list): A list of image models.

        """
        self.prs = prs
        self.config = config
        self.ppt_image_folder = ppt_image_folder
        self.template_image_folder = template_image_folder
        self.language_model = language_model
        self.vision_model = vision_model
        self.image_models = image_models
        self.schema_extractor = Agent(
            "schema_extractor",
            {
                "language": language_model,
            },
        )
        if not use_assert:
            return

        num_template_images = sum(
            is_image_path(f) for f in os.listdir(template_image_folder)
        )
        num_ppt_images = sum(is_image_path(f) for f in os.listdir(ppt_image_folder))
        num_slides = len(prs.slides)

        if not (num_template_images == num_ppt_images == num_slides):
            raise ValueError(
                f"Slide count mismatch detected:\n"
                f"- Presentation slides: {num_slides}\n"
                f"- Template images: {num_template_images} ({template_image_folder})\n"
                f"- PPT images: {num_ppt_images} ({ppt_image_folder})\n"
                f"All counts must be equal."
            )

    def layout_induct(self) -> dict:
        """

        Perform layout induction for the presentation, should be called before content induction.

        Return a dict representing layouts, each layout is a dict with keys:

        - key: the layout name, e.g. "Title and Content:text"

        - `template_id`: the id of the template slide

        - `slides`: the list of slide ids

        Moreover, the dict has a key `functional_keys`, which is a list of functional keys.

        """
        layout_induction = defaultdict(lambda: defaultdict(list))
        content_slides_index, functional_cluster = self.category_split()
        for layout_name, cluster in functional_cluster.items():
            layout_induction[layout_name]["slides"] = cluster
            layout_induction[layout_name]["template_id"] = cluster[0]

        functional_keys = list(layout_induction.keys())
        function_slides_index = set()
        for layout_name, cluster in layout_induction.items():
            function_slides_index.update(cluster["slides"])
        used_slides_index = function_slides_index.union(content_slides_index)
        for i in range(len(self.prs.slides)):
            if i + 1 not in used_slides_index:
                content_slides_index.add(i + 1)
        self.layout_split(content_slides_index, layout_induction)
        layout_induction["functional_keys"] = functional_keys
        return layout_induction

    def category_split(self):
        """

        Split slides into categories based on their functional purpose.

        """
        functional_cluster = self.language_model(
            CATEGORY_SPLIT_TEMPLATE.render(slides=self.prs.to_text()),
            return_json=True,
        )
        assert isinstance(functional_cluster, dict) and all(
            isinstance(k, str) and isinstance(v, list)
            for k, v in functional_cluster.items()
        ), "Functional cluster must be a dictionary with string keys and list values"
        functional_slides = set(sum(functional_cluster.values(), []))
        content_slides_index = set(range(1, len(self.prs) + 1)) - functional_slides

        return content_slides_index, functional_cluster

    def layout_split(self, content_slides_index: set[int], layout_induction: dict):
        """

        Cluster slides into different layouts.

        """
        embeddings = get_image_embedding(self.template_image_folder, *self.image_models)
        assert len(embeddings) == len(self.prs)
        content_split = defaultdict(list)
        for slide_idx in content_slides_index:
            slide = self.prs.slides[slide_idx - 1]
            content_type = slide.get_content_type()
            layout_name = slide.slide_layout_name
            content_split[(layout_name, content_type)].append(slide_idx)

        for (layout_name, content_type), slides in content_split.items():
            sub_embeddings = [
                embeddings[f"slide_{slide_idx:04d}.jpg"] for slide_idx in slides
            ]
            similarity = images_cosine_similarity(sub_embeddings)
            for cluster in get_cluster(similarity):
                slide_indexs = [slides[i] for i in cluster]
                template_id = max(
                    slide_indexs,
                    key=lambda x: len(self.prs.slides[x - 1].shapes),
                )
                cluster_name = (
                    self.vision_model(
                        ASK_CATEGORY_PROMPT,
                        pjoin(self.ppt_image_folder, f"slide_{template_id:04d}.jpg"),
                    )
                    + ":"
                    + content_type
                )
                layout_induction[cluster_name]["template_id"] = template_id
                layout_induction[cluster_name]["slides"] = slide_indexs

    def content_induct(self, layout_induction: dict):
        """

        Perform content schema extraction for the presentation.

        """
        for layout_name, cluster in layout_induction.items():
            if layout_name == "functional_keys" or "content_schema" in cluster:
                continue
            slide = self.prs.slides[cluster["template_id"] - 1]
            turn_id, schema = self.schema_extractor(slide=slide.to_html())
            schema = self._fix_schema(schema, slide, turn_id)
            layout_induction[layout_name]["content_schema"] = schema

        return layout_induction

    def _fix_schema(

        self,

        schema: dict,

        slide: SlidePage,

        turn_id: int = None,

        retry: int = 0,

    ) -> dict:
        """

        Fix schema by checking and retrying if necessary.

        """
        try:
            check_schema(schema, slide)
        except ValueError as e:
            retry += 1
            logger.debug("Failed at schema extraction: %s", e)
            if retry == 3:
                logger.error("Failed to extract schema for slide-%s: %s", turn_id, e)
                raise e
            schema = self.schema_extractor.retry(
                e, traceback.format_exc(), turn_id, retry
            )
            return self._fix_schema(schema, slide, turn_id, retry)
        return schema


class SlideInducterAsync(SlideInducter):
    def __init__(

        self,

        prs: Presentation,

        ppt_image_folder: str,

        template_image_folder: str,

        config: Config,

        image_models: list,

        language_model: AsyncLLM,

        vision_model: AsyncLLM,

    ):
        """

        Initialize the SlideInducterAsync with async models.



        Args:

            prs (Presentation): The presentation object.

            ppt_image_folder (str): The folder containing PPT images.

            template_image_folder (str): The folder containing normalized slide images.

            config (Config): The configuration object.

            image_models (list): A list of image models.

            language_model (AsyncLLM): The async language model.

            vision_model (AsyncLLM): The async vision model.

        """
        super().__init__(
            prs,
            ppt_image_folder,
            template_image_folder,
            config,
            image_models,
            language_model,
            vision_model,
        )
        self.language_model = self.language_model.to_async()
        self.vision_model = self.vision_model.to_async()
        self.schema_extractor = self.schema_extractor.to_async()

    async def category_split(self):
        """

        Async version: Split slides into categories based on their functional purpose.

        """
        functional_cluster = await self.language_model(
            CATEGORY_SPLIT_TEMPLATE.render(slides=self.prs.to_text()),
            return_json=True,
        )
        assert isinstance(functional_cluster, dict) and all(
            isinstance(k, str) and isinstance(v, list)
            for k, v in functional_cluster.items()
        ), "Functional cluster must be a dictionary with string keys and list values"
        functional_slides = set(sum(functional_cluster.values(), []))
        content_slides_index = set(range(1, len(self.prs) + 1)) - functional_slides

        return content_slides_index, functional_cluster

    async def layout_split(

        self, content_slides_index: set[int], layout_induction: dict

    ):
        """

        Async version: Cluster slides into different layouts.

        """
        embeddings = get_image_embedding(self.template_image_folder, *self.image_models)
        assert len(embeddings) == len(self.prs)
        content_split = defaultdict(list)
        for slide_idx in content_slides_index:
            slide = self.prs.slides[slide_idx - 1]
            content_type = slide.get_content_type()
            layout_name = slide.slide_layout_name
            content_split[(layout_name, content_type)].append(slide_idx)

        async with asyncio.TaskGroup() as tg:
            for (layout_name, content_type), slides in content_split.items():
                sub_embeddings = [
                    embeddings[f"slide_{slide_idx:04d}.jpg"] for slide_idx in slides
                ]
                similarity = images_cosine_similarity(sub_embeddings)
                for cluster in get_cluster(similarity):
                    slide_indexs = [slides[i] for i in cluster]
                    template_id = max(
                        slide_indexs,
                        key=lambda x: len(self.prs.slides[x - 1].shapes),
                    )

                    tg.create_task(
                        self.vision_model(
                            ASK_CATEGORY_PROMPT,
                            pjoin(
                                self.ppt_image_folder, f"slide_{template_id:04d}.jpg"
                            ),
                        )
                    ).add_done_callback(
                        lambda f, tid=template_id, sidxs=slide_indexs, ctype=content_type: layout_induction[
                            f.result() + ":" + ctype
                        ].update(
                            {"template_id": tid, "slides": sidxs}
                        )
                    )

    async def layout_induct(self):
        """

        Async version: Perform layout induction for the presentation.

        """
        layout_induction = defaultdict(lambda: defaultdict(list))
        content_slides_index, functional_cluster = await self.category_split()
        for layout_name, cluster in functional_cluster.items():
            layout_induction[layout_name]["slides"] = cluster
            layout_induction[layout_name]["template_id"] = cluster[0]

        functional_keys = list(layout_induction.keys())
        function_slides_index = set()
        for layout_name, cluster in layout_induction.items():
            function_slides_index.update(cluster["slides"])
        used_slides_index = function_slides_index.union(content_slides_index)
        for i in range(len(self.prs.slides)):
            if i + 1 not in used_slides_index:
                content_slides_index.add(i + 1)
        await self.layout_split(content_slides_index, layout_induction)
        layout_induction["functional_keys"] = functional_keys
        return layout_induction

    async def content_induct(self, layout_induction: dict):
        """

        Async version: Perform content schema extraction for the presentation.

        """
        async with asyncio.TaskGroup() as tg:
            for layout_name, cluster in layout_induction.items():
                if layout_name == "functional_keys" or "content_schema" in cluster:
                    continue
                slide = self.prs.slides[cluster["template_id"] - 1]
                coro = self.schema_extractor(slide=slide.to_html())

                tg.create_task(self._fix_schema(coro, slide)).add_done_callback(
                    lambda f, key=layout_name: layout_induction[key].update(
                        {"content_schema": f.result()}
                    )
                )

        return layout_induction

    async def _fix_schema(

        self,

        schema: dict | Coroutine[dict, None, None],

        slide: SlidePage,

        turn_id: int = None,

        retry: int = 0,

    ):
        if retry == 0:
            turn_id, schema = await schema
        try:
            check_schema(schema, slide)
        except ValueError as e:
            retry += 1
            logger.debug("Failed at schema extraction: %s", e)
            if retry == 3:
                logger.error("Failed to extract schema for slide-%s: %s", turn_id, e)
                raise e
            schema = await self.schema_extractor.retry(
                e, traceback.format_exc(), turn_id, retry
            )
            return await self._fix_schema(schema, slide, turn_id, retry)
        return schema