File size: 3,800 Bytes
f764cdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Normalize heterogeneous repository files into model-readable text."""

from __future__ import annotations

import json
from pathlib import PurePosixPath

from .repo import RepoFile


NOTEBOOK_SUFFIXES = {".ipynb"}
MARKDOWN_SUFFIXES = {".md", ".mdx", ".markdown", ".rst", ".adoc"}


def normalized_path(path: str) -> str:
    return PurePosixPath(path).as_posix().lstrip("/")


def decoded_content(file: RepoFile) -> str:
    if isinstance(file.content, str):
        return file.content
    return file.content.decode(file.encoding or "utf-8", errors="replace")


def is_binary(file: RepoFile) -> bool:
    if isinstance(file.content, str):
        return False
    head = file.content[:8192]
    if b"\x00" in head:
        return True
    if not head:
        return False
    control = sum(byte < 9 or 13 < byte < 32 for byte in head)
    return control / len(head) > 0.05


def file_role(file: RepoFile) -> str:
    path = normalized_path(file.path)
    name = PurePosixPath(path).name.lower()
    suffix = PurePosixPath(path).suffix.lower()
    if is_binary(file):
        return "binary"
    if suffix in NOTEBOOK_SUFFIXES:
        return "notebook"
    if suffix in MARKDOWN_SUFFIXES or name.startswith("readme"):
        return "documentation"
    if name in {"makefile", "cmakelists.txt", "build.gradle", "build.gradle.kts", "pom.xml"}:
        return "build"
    if name in {"package.json", "pyproject.toml", "cargo.toml", "go.mod", "composer.json"}:
        return "manifest"
    return "source" if file.language else "unknown"


def notebook_text(file: RepoFile) -> str | None:
    """Render a notebook as an ordered cell stream; return None if malformed."""
    try:
        data = json.loads(decoded_content(file))
    except (json.JSONDecodeError, TypeError, UnicodeError):
        return None
    cells = data.get("cells")
    if not isinstance(cells, list):
        return None
    rendered: list[str] = []
    for cell in cells:
        if not isinstance(cell, dict):
            continue
        kind = cell.get("cell_type")
        source = cell.get("source", "")
        if isinstance(source, list):
            source = "".join(part for part in source if isinstance(part, str))
        if not isinstance(source, str):
            continue
        if kind == "markdown":
            rendered.append("# Cell: Markdown\n" + source.rstrip())
        elif kind == "code":
            rendered.append("# Cell: Code\n" + source.rstrip())
            outputs = cell.get("outputs")
            if isinstance(outputs, list) and outputs:
                output = _notebook_output(outputs[-1])
                if output:
                    rendered.append("# Cell: Output\n" + output.rstrip())
    return "\n".join(rendered).rstrip() + ("\n" if rendered else "")


def _notebook_output(output: object) -> str:
    if not isinstance(output, dict):
        return ""
    value = output.get("text")
    if value is None and isinstance(output.get("data"), dict):
        value = output["data"].get("text/plain")
    if isinstance(value, list):
        return "".join(part for part in value if isinstance(part, str))
    return value if isinstance(value, str) else ""


def training_content(file: RepoFile, config) -> tuple[str, str, str]:
    """Return rendered content, policy, and role for one file."""
    role = file_role(file)
    if role == "binary":
        return "", "metadata_only", role
    if file.is_vendor and config.metadata_only_vendor:
        return "", "metadata_only", role
    if file.is_generated and config.metadata_only_generated:
        return "", "metadata_only", role
    if role == "notebook":
        rendered = notebook_text(file)
        if rendered is not None:
            return rendered, "structured", role
    return decoded_content(file), "full", role