Spaces:
Build error
Build error
Download app/services/context_assembler.py from anwarkxc/trackademi: direct link, hf CLI and curl.
- Browser
- Download file 7.5 kB
-
https://huggingface.co/spaces/anwarkxc/trackademi/resolve/main/app/services/context_assembler.py
- Command line
-
hf download hf://spaces/anwarkxc/trackademi/app/services/context_assembler.py
-
curl -L -o context_assembler.py https://huggingface.co/spaces/anwarkxc/trackademi/resolve/main/app/services/context_assembler.py
7.5 kB
| """Context Assembler — Strategy pattern, one AssemblyStrategy per generation | |
| mode (Mcq/Essay/Blueprint/Chat), each owning only its token budget and | |
| image-selection threshold. Everything else (deduplication) already happened | |
| in context_optimizer.py; everything after this (calling the LLM) happens in | |
| gateway.py. This factoring keeps adding a new question type or model tier a | |
| change confined to one new strategy class, not a growing if/elif chain. | |
| Fixed content order for every strategy: paragraph text -> diagram/table/ | |
| formula description -> caption -> formula (if not already covered) -> OCR | |
| text -> the image itself, attached last as the multimodal part. | |
| """ | |
| from dataclasses import dataclass, field | |
| from typing import Optional | |
| from app.services.context_optimizer import ElementBundle | |
| from app.services.graph_repository import GraphElement | |
| from app.services.policy import Policy | |
| _CHARS_PER_TOKEN = 4 | |
| class AssembledContext: | |
| text: str | |
| image_urls: list[str] = field(default_factory=list) | |
| figure_urls: list[str] = field(default_factory=list) # surfaced to the frontend as question.figure_url | |
| # Chunk id per assembled block, positionally aligned with the `[[المصدر N]]` | |
| # markers `assemble(label_sources=True)` writes into `text` (marker N -> | |
| # block_chunk_ids[N-1]). Exam generation uses this to turn the model's | |
| # self-reported `source_index` into real per-question provenance; callers | |
| # that don't label sources can ignore it. | |
| block_chunk_ids: list[str] = field(default_factory=list) | |
| def _element_description(element: GraphElement) -> str: | |
| if element.element_type == "diagram": | |
| return element.semantic_description or "" | |
| if element.element_type == "table": | |
| return element.table_summary or "" | |
| if element.element_type == "formula": | |
| return element.formula_summary or "" | |
| return "" | |
| def _estimate_tokens(text: str) -> int: | |
| return max(1, len(text) // _CHARS_PER_TOKEN) | |
| def _element_value_density(element: GraphElement, weight: float, normalized_confidence: Optional[float]) -> float: | |
| text = _element_description(element) + (element.ocr_text or "") | |
| cost = _estimate_tokens(text) + (150 if element.element_type == "diagram" else 0) # flat image-attach cost estimate | |
| importance = (element.importance_score or 50) / 100.0 | |
| confidence = normalized_confidence if normalized_confidence is not None else 1.0 | |
| value = weight * confidence * importance | |
| return value / max(cost, 1) | |
| class AssemblyStrategy: | |
| """Base strategy — subclasses only need to override `question_type_key`.""" | |
| question_type_key: str = "essay" | |
| def image_threshold(self, policy: Policy) -> int: | |
| return policy.image_importance_threshold | |
| def budget_tokens(self, policy: Policy) -> int: | |
| return policy.budget_for(self.question_type_key) | |
| def assemble( | |
| self, bundles: list[ElementBundle], policy: Policy, *, label_sources: bool = False, | |
| ) -> AssembledContext: | |
| """Assemble retrieved bundles into one context string. | |
| `label_sources` prefixes every block with a `[[المصدر N]]` marker and | |
| populates `block_chunk_ids` so a generator can cite which block it | |
| used. Off by default — chat/explanation contexts must not carry | |
| markers the model might echo into a user-facing answer. | |
| """ | |
| budget = self.budget_tokens(policy) | |
| image_threshold = self.image_threshold(policy) | |
| # Greedily rank every (bundle, element) pair by value density and take | |
| # the highest-value ones until the token budget is exhausted — not a | |
| # flat top-K, and not "include everything reachable". | |
| candidates: list[tuple[float, int, ElementBundle, GraphElement]] = [] | |
| for b_idx, bundle in enumerate(bundles): | |
| for element, relationship in bundle.elements: | |
| weight = relationship.weight or 0.5 | |
| density = _element_value_density(element, weight, relationship.normalized_confidence) | |
| candidates.append((density, b_idx, bundle, element)) | |
| candidates.sort(key=lambda c: c[0], reverse=True) | |
| selected_by_bundle: dict[int, list[GraphElement]] = {} | |
| used_tokens = 0 | |
| for density, b_idx, bundle, element in candidates: | |
| text = _element_description(element) + (element.ocr_text or "") | |
| cost = _estimate_tokens(text) | |
| if used_tokens + cost > budget: | |
| continue | |
| used_tokens += cost | |
| selected_by_bundle.setdefault(b_idx, []).append(element) | |
| blocks: list[str] = [] | |
| block_chunk_ids: list[str] = [] | |
| image_urls: list[str] = [] | |
| figure_urls: list[str] = [] | |
| for b_idx, bundle in enumerate(bundles): | |
| # The marker is written first so it survives any downstream | |
| # truncation of the block's tail, and numbered from 1 because the | |
| # model reproduces it verbatim (0-based indices invite off-by-one | |
| # answers from LLMs far more often than 1-based ones do). | |
| parts = [f"[[المصدر {len(block_chunk_ids) + 1}]]"] if label_sources else [] | |
| block_chunk_ids.append(bundle.chunk_id) | |
| parts.append(bundle.chunk_content) | |
| for element in selected_by_bundle.get(b_idx, []): | |
| description = _element_description(element) | |
| if description: | |
| parts.append(description) | |
| if element.caption: | |
| parts.append(f"[تسمية: {element.caption}]") | |
| if element.element_type == "formula" and element.formula_text: | |
| parts.append(f"[المعادلة: {element.formula_text}]") | |
| if element.element_type == "table" and element.markdown_table: | |
| parts.append(element.markdown_table) | |
| if element.ocr_text: | |
| parts.append(f"[نص داخل الصورة: {element.ocr_text}]") | |
| if element.url: | |
| figure_urls.append(element.url) | |
| if (element.importance_score or 0) >= image_threshold: | |
| image_urls.append(element.url) | |
| blocks.append("\n".join(p for p in parts if p)) | |
| return AssembledContext( | |
| text="\n\n---\n\n".join(blocks), | |
| image_urls=image_urls, | |
| figure_urls=figure_urls, | |
| block_chunk_ids=block_chunk_ids, | |
| ) | |
| class McqStrategy(AssemblyStrategy): | |
| question_type_key = "mcq" | |
| class EssayStrategy(AssemblyStrategy): | |
| question_type_key = "essay" | |
| class BlueprintStrategy(AssemblyStrategy): | |
| question_type_key = "blueprint" | |
| class ChatStrategy(AssemblyStrategy): | |
| question_type_key = "essay" # chat has no dedicated budget tier — reuse essay's | |
| class DiagramQuestionStrategy(AssemblyStrategy): | |
| question_type_key = "diagram_question" | |
| def image_threshold(self, policy: Policy) -> int: | |
| # Diagram-anchored questions should attach the image more readily. | |
| return max(0, policy.image_importance_threshold - 20) | |
| _STRATEGIES: dict[str, type[AssemblyStrategy]] = { | |
| "mcq": McqStrategy, | |
| "essay": EssayStrategy, | |
| "blueprint": BlueprintStrategy, | |
| "chat": ChatStrategy, | |
| "diagram_question": DiagramQuestionStrategy, | |
| } | |
| def get_strategy(question_type: Optional[str]) -> AssemblyStrategy: | |
| cls = _STRATEGIES.get((question_type or "essay").lower(), EssayStrategy) | |
| return cls() | |