File size: 21,138 Bytes
47d2384
 
 
 
 
 
 
5c49984
47d2384
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5246c92
 
47d2384
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c49984
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47d2384
 
 
 
6bd19df
 
47d2384
 
6bd19df
 
 
47d2384
 
 
 
 
 
 
 
 
6bd19df
47d2384
 
 
 
6bd19df
 
47d2384
6bd19df
 
 
47d2384
 
 
 
5c49984
47d2384
 
 
6bd19df
47d2384
6bd19df
 
 
 
 
 
 
 
 
 
 
 
47d2384
 
5c49984
 
 
 
 
 
6bd19df
 
 
 
 
 
5c49984
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bd19df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47d2384
 
6bd19df
 
 
 
 
47d2384
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c49984
 
 
 
47d2384
 
 
 
 
5c49984
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47d2384
5c49984
 
 
 
 
47d2384
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc3d524
 
 
 
 
 
 
47d2384
 
 
 
 
 
 
 
 
 
8601f87
 
 
 
47d2384
 
 
 
 
 
6bd19df
8601f87
47d2384
 
6bd19df
47d2384
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
from __future__ import annotations

import logging
import os
import re
import tempfile
import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Optional

import requests

# --- ChromaDB needs to be imported with a guard because the ONNX runtime may
#     pull in extra dependencies on first load.
try:
    import chromadb
    from chromadb.api.models.Collection import Collection
    from chromadb.utils import embedding_functions
except ImportError:
    chromadb = None  # type: ignore[assignment]
    Collection = None  # type: ignore[assignment,misc]
    embedding_functions = None  # type: ignore[assignment]

from backend.integrations.github_client import GitHubSession
from backend.state import ContextChunk, OpenCodeReviewState

logger = logging.getLogger(__name__)

GITHUB_API_BASE = "https://api.github.com"
RAW_CONTENT_BASE = "https://raw.githubusercontent.com"

# How many chunks to retrieve per query
TOP_K = 15
# Max size (characters) for a single chunk
CHUNK_MAX_CHARS = 1_200
# How many merged PR discussions to fetch
MERGED_PR_LIMIT = 20

# Extensions we consider "source code" worth embedding
SOURCE_EXTENSIONS = {
    ".py", ".js", ".ts", ".jsx", ".tsx", ".go", ".rs", ".java", ".rb", ".php",
    ".c", ".cpp", ".h", ".hpp", ".cs", ".swift", ".kt", ".scala",
    ".md", ".rst", ".txt",
    ".yml", ".yaml", ".toml", ".cfg", ".ini",
    ".sql", ".sh", ".bash", ".zsh",
    ".html", ".css", ".scss",
}
# Files we always include if they exist
ALWAYS_INCLUDE = {
    "CONTRIBUTING.md", "CONTRIBUTING.rst",
    "README.md", "README.rst",
    "CODE_OF_CONDUCT.md",
    "STYLE_GUIDE.md",
    ".github/CONTRIBUTING.md",
}


# ─── Helpers: GitHub API ────────────────────────────────────────────────────


_GITHUB_SESSION: GitHubSession | None = None


def _gh_session() -> GitHubSession:
    """Return a lazily-initialized :class:`GitHubSession` for the retrieval
    node.  The session is cached across calls within the same PR review."""
    global _GITHUB_SESSION
    if _GITHUB_SESSION is None:
        _GITHUB_SESSION = GitHubSession()
    return _GITHUB_SESSION


def _get_json(url: str) -> Optional[dict | list]:
    """GET and return parsed JSON, or None on non-200, logging warnings.

    Uses :class:`GitHubSession` so 401 responses raise
    :class:`TokenRevokedError` automatically.
    """
    try:
        resp = _gh_session().get(url, timeout=30)
        if resp.status_code == 200:
            return resp.json()
        logger.warning("GitHub API %s returned %s", url.split("?")[0], resp.status_code)
        return None
    except requests.RequestException as exc:
        logger.warning("GitHub API request failed for %s: %s", url.split("?")[0], exc)
        return None


# ─── Helpers: chunking ──────────────────────────────────────────────────────


def _chunk_python_source(file_path: str, content: str) -> list[dict]:
    """Split Python source at top-level ``def`` / ``class`` / ``async def``."""
    chunks: list[dict] = []
    lines = content.splitlines(keepends=True)
    # Regex matches start of a top-level (non-indented) definition
    pattern = re.compile(r"^(async\s+)?(def |class )")
    current_start = 0
    for i, line in enumerate(lines):
        if i > 0 and pattern.match(line) and not line.startswith(" "):
            block = "".join(lines[current_start:i]).strip()
            if block:
                chunks.append({
                    "text": block,
                    "type": _classify_chunk(block),
                })
            current_start = i
    # Last block
    remaining = "".join(lines[current_start:]).strip()
    if remaining:
        chunks.append({"text": remaining, "type": _classify_chunk(remaining)})
    return chunks


def _chunk_generic(content: str) -> list[dict]:
    """Split text by blank lines into paragraphs, merging very short ones."""
    paragraphs = re.split(r"\n\s*\n", content)
    chunks: list[dict] = []
    buffer = ""
    for para in paragraphs:
        para = para.strip()
        if not para:
            continue
        if len(buffer) + len(para) < CHUNK_MAX_CHARS:
            buffer = (buffer + "\n\n" + para).strip()
        else:
            if buffer:
                chunks.append({"text": buffer, "type": "paragraph"})
            buffer = para
    if buffer:
        chunks.append({"text": buffer, "type": "paragraph"})
    return chunks


def _classify_chunk(text: str) -> str:
    """Return ``function``, ``class``, or ``code``."""
    if text.startswith("class "):
        return "class"
    if text.startswith(("def ", "async def ")):
        return "function"
    return "code"


def _chunk_source(file_path: str, content: str) -> list[dict]:
    """Chunk a source file into semantically meaningful pieces."""
    if file_path.endswith(".py"):
        return _chunk_python_source(file_path, content)
    return _chunk_generic(content)


def _should_include(path: str) -> bool:
    """Return True for file paths we want to embed (source code, docs)."""
    if path in ALWAYS_INCLUDE:
        return True
    # Skip hidden files, test data, vendored deps
    parts = path.replace("\\", "/").split("/")
    if any(p.startswith(".") for p in parts):
        return False
    if "test" in path.lower() or "spec" in path.lower() or "__pycache__" in path:
        return False
    if any(p in ("venv", ".venv", "node_modules", "vendor", "dist", "build") for p in parts):
        return False
    ext = os.path.splitext(path)[1].lower()
    return ext in SOURCE_EXTENSIONS


# ─── Helpers: building the vector store ─────────────────────────────────────


# ─── Global embedding-function cache ────────────────────────────────────────
# The ChromaDB SentenceTransformer embedding function loads a ~90 MB PyTorch
# model from disk every time it is instantiated, which takes ~20 s.  Cache it
# at module level and prefer the ONNX variant (loads in <1 s).
_EMBEDDING_FN = None


def _get_embedding_fn():
    """Return a cached embedding function (ONNX MiniLM, loaded once per process)."""
    global _EMBEDDING_FN
    if _EMBEDDING_FN is not None:
        return _EMBEDDING_FN
    # Prefer the ONNX-optimised variant (loads <1 s vs ~20 s for PyTorch)
    if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):
        logger.info("Using ONNX MiniLM embedding function (faster load)")
        _EMBEDDING_FN = embedding_functions.ONNXMiniLM_L6_V2()
    elif hasattr(embedding_functions, "SentenceTransformerEmbeddingFunction"):
        logger.info("Using SentenceTransformer embedding function")
        _EMBEDDING_FN = embedding_functions.SentenceTransformerEmbeddingFunction(
            model_name="all-MiniLM-L6-v2"
        )
    else:
        raise RuntimeError(
            "No usable ChromaDB embedding function found. Install with: "
            "pip install chromadb (includes ONNX MiniLM support)"
        )
    return _EMBEDDING_FN


_VECTOR_DIR: str | None = None


def _ensure_vector_dir() -> str:
    """Return a persistent vector-store directory (not temp, so it survives
    across runs).  Override via OPENCODEREVIEW_VECTOR_DIR env var."""
    global _VECTOR_DIR
    if _VECTOR_DIR is None:
        _VECTOR_DIR = os.environ.get(
            "OPENCODEREVIEW_VECTOR_DIR",
            os.path.join(os.getcwd(), ".opencodereview", "vectors"),
        )
        os.makedirs(_VECTOR_DIR, exist_ok=True)
    return _VECTOR_DIR


def _repo_collection_name(repo: str) -> str:
    return f"repo_{repo.replace('/', '_')}"


def _get_or_build_collection(
    owner: str, repo_name: str,
    head_sha: str,
    exclude_paths: set[str],
) -> Collection:
    """Return a cached ChromaDB collection for ``repo``, rebuilding only when
    the base-branch SHA changes.

    The collection metadata key ``base_sha`` stores the SHA at build time.
    On subsequent calls, if the collection exists with a matching ``base_sha``
    it is returned immediately β€” no fetch, no chunk, no embedding.
    """
    if chromadb is None:
        raise RuntimeError("chromadb is not installed β€” cannot build vector store")

    ef = _get_embedding_fn()
    client = chromadb.PersistentClient(path=_ensure_vector_dir())
    coll_name = _repo_collection_name(f"{owner}/{repo_name}")

    # ── Cache hit: collection exists with matching SHA ────────────────────
    try:
        existing = client.get_collection(name=coll_name, embedding_function=ef)
        meta = existing.metadata or {}
        if meta.get("base_sha") == head_sha:
            logger.info(
                "Vector store up-to-date (SHA=%s) β€” skipping rebuild",
                head_sha[:7],
            )
            return existing
        logger.info(
            "SHA mismatch: cached=%s, current=%s β€” rebuilding",
            (meta.get("base_sha") or "?"), head_sha[:7],
        )
        client.delete_collection(coll_name)
    except Exception:
        # Collection doesn't exist or is incompatible (e.g. different
        # embedding function class) β€” delete any remnants and create fresh.
        try:
            client.delete_collection(coll_name)
        except Exception:
            pass

    return _build_vector_store(
        owner, repo_name, head_sha, exclude_paths, client, coll_name, ef,
    )


def _fetch_and_chunk_file(
    fp: str, owner: str, repo_name: str, head_sha: str,
) -> list[dict]:
    """Fetch a single source file from GitHub and return its chunks.

    Called by :class:`ThreadPoolExecutor` workers to parallelise the
    I/O-bound file-fetching phase of vector-store construction.
    Returns an empty list on any error (404, timeout, etc.)
    """
    raw_url = f"{RAW_CONTENT_BASE}/{owner}/{repo_name}/{head_sha}/{fp}"
    try:
        resp = requests.get(raw_url, timeout=30)
        if resp.status_code != 200:
            return []
        content = resp.text
    except requests.RequestException:
        return []

    chunks = _chunk_source(fp, content)
    result: list[dict] = []
    for chunk in chunks:
        result.append({
            "text": chunk["text"],
            "meta": {
                "source": "codebase",
                "file_path": fp,
                "chunk_type": chunk["type"],
            },
            "id": str(uuid.uuid4()),
        })
    return result


def _build_vector_store(
    owner: str, repo_name: str,
    head_sha: str,
    exclude_paths: set[str],
    client: chromadb.PersistentClient,
    coll_name: str,
    ef,
) -> Collection:
    """Fetch, chunk, embed, and index the non-changed files + past PRs.

    Each data source (codebase, past PRs, docs) is added to ChromaDB
    incrementally so a transient failure in one source does not lose
    progress from earlier sources.

    .. note::

        Prefer :func:`_get_or_build_collection` β€” this function always
        rebuilds from scratch.
    """
    collection = client.create_collection(
        name=coll_name,
        metadata={
            "hnsw:space": "cosine",
            "base_sha": head_sha,       # ← freshness key for cache lookups
            "repo": f"{owner}/{repo_name}",
        },
        embedding_function=ef,
    )

    total_added = 0

    # ---- 1. Source files from the repo (excluding changed files) ------------
    logger.info("Fetching repo file tree (base branch) …")
    tree_url = (
        f"{GITHUB_API_BASE}/repos/{owner}/{repo_name}/git/trees/"
        f"{head_sha}?recursive=1"
    )
    tree_data = _get_json(tree_url)
    if tree_data and isinstance(tree_data, dict):
        tree_items: list[dict] = tree_data.get("tree", [])
        source_paths = [
            item["path"]
            for item in tree_items
            if item["type"] == "blob"
            and _should_include(item["path"])
            and item["path"] not in exclude_paths
        ]
        logger.info(
            "Source files to embed (excl. changed): %d β€” fetching in parallel …",
            len(source_paths),
        )

        code_docs: list[str] = []
        code_metadatas: list[dict] = []
        code_ids: list[str] = []

        # Fetch files concurrently β€” I/O-bound network requests benefit
        # greatly from thread-level parallelism.
        with ThreadPoolExecutor(max_workers=10) as pool:
            futures = {
                pool.submit(
                    _fetch_and_chunk_file, fp, owner, repo_name, head_sha
                ): fp
                for fp in source_paths
            }
            for future in as_completed(futures):
                fp = futures[future]
                try:
                    file_result = future.result()
                except Exception as exc:
                    logger.debug("Failed to fetch %s: %s", fp, exc)
                    continue

                for chunk in file_result:
                    code_docs.append(chunk["text"])
                    code_metadatas.append(chunk["meta"])
                    code_ids.append(chunk["id"])

        if code_docs:
            collection.add(
                documents=code_docs,
                metadatas=code_metadatas,
                ids=code_ids,
            )
            total_added += len(code_docs)
            logger.info("Code chunks indexed: %d", len(code_docs))
    else:
        logger.warning("Could not fetch repo file tree β€” continuing with past PRs only")

    # ---- 2. Past merged PR discussions --------------------------------------
    prs_url = (
        f"{GITHUB_API_BASE}/repos/{owner}/{repo_name}/pulls"
        f"?state=closed&per_page={MERGED_PR_LIMIT}&sort=updated&direction=desc"
    )
    try:
        prs_data = _get_json(prs_url)
        if prs_data and isinstance(prs_data, list):
            pr_docs: list[str] = []
            pr_metadatas: list[dict] = []
            pr_ids: list[str] = []

            for pr_item in prs_data:
                if not pr_item.get("merged_at"):
                    continue
                pr_number = pr_item["number"]
                title = pr_item.get("title", "")
                body = pr_item.get("body") or ""
                text = f"PR #{pr_number}: {title}\n\n{body}".strip()
                if len(text) < 50:
                    continue
                chunks = _chunk_generic(text)
                for chunk in chunks:
                    pr_docs.append(chunk["text"])
                    pr_metadatas.append({
                        "source": "past_pr",
                        "file_path": f"PR #{pr_number}",
                        "chunk_type": "discussion",
                    })
                    pr_ids.append(str(uuid.uuid4()))

            if pr_docs:
                collection.add(
                    documents=pr_docs,
                    metadatas=pr_metadatas,
                    ids=pr_ids,
                )
                total_added += len(pr_docs)
                logger.info("Past-PR chunks indexed: %d", len(pr_docs))
    except Exception as exc:
        logger.warning("Failed to fetch past PRs (continuing without them): %s", exc)

    # ---- 3. CONTRIBUTING.md / docs ------------------------------------------
    doc_batch_docs: list[str] = []
    doc_batch_metas: list[dict] = []
    doc_batch_ids: list[str] = []

    for doc_path in ALWAYS_INCLUDE:
        raw_url = f"{RAW_CONTENT_BASE}/{owner}/{repo_name}/{head_sha}/{doc_path}"
        try:
            resp = requests.get(raw_url, timeout=15)
            if resp.status_code == 200 and len(resp.text) > 50:
                chunks = _chunk_generic(resp.text)
                for chunk in chunks:
                    doc_batch_docs.append(chunk["text"])
                    doc_batch_metas.append({
                        "source": "codebase",
                        "file_path": doc_path,
                        "chunk_type": "docs",
                    })
                    doc_batch_ids.append(str(uuid.uuid4()))
                logger.info("  Added docs: %s", doc_path)
        except requests.RequestException:
            pass

    if doc_batch_docs:
        collection.add(
            documents=doc_batch_docs,
            metadatas=doc_batch_metas,
            ids=doc_batch_ids,
        )
        total_added += len(doc_batch_docs)

    if total_added:
        logger.info(
            "Vector store built β€” %d total chunks in '%s'",
            total_added, coll_name,
        )
    else:
        logger.warning("Vector store is empty β€” no documents to index")

    return collection


# ─── Retrieval node ──────────────────────────────────────────────────────────


def retrieval_node(state: OpenCodeReviewState) -> dict:
    """Build (once per repo) a vector store of the codebase + past PRs, then
    query it with the current PR diff to find relevant context chunks.

    Returns state updates for ``context_chunks``.
    """
    # -- Bail out early if there is no diff to query against ------------------
    if not state.diff:
        logger.info("No diff available β€” skipping retrieval")
        return {}

    # Hosted deployments must not download or execute embedding models on the
    # application machine. Enable this only on a machine intentionally sized
    # for local retrieval; the review itself always uses a remote LLM provider.
    if os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower() not in {"1", "true", "yes"}:
        logger.info("Local embeddings disabled; skipping vector retrieval")
        return {}

    # -- Parse identifiers ----------------------------------------------------
    parts = state.repo.split("/")
    if len(parts) != 2:
        logger.warning("Invalid repo format '%s' β€” skipping retrieval", state.repo)
        return {}
    owner, repo_name = parts

    changed_paths: set[str] = {f.path for f in state.changed_files}

    # -- Build (or load) the vector store for this repo -----------------------
    # Use the base branch SHA as the cache key.  When re-reviewing the same
    # repo against the same base SHA the vector store is returned immediately
    # without re-fetching / re-embedding any files.
    base_sha = state.base_sha or "HEAD"  # fallback for synthetic / test state

    if chromadb is None:
        logger.warning("chromadb not available β€” returning empty context")
        return {}

    try:
        collection = _get_or_build_collection(
            owner, repo_name, base_sha, changed_paths,
        )
    except Exception as exc:
        logger.warning("Failed to build/get vector store: %s", exc)
        return {}

    # -- Query the store with the diff ----------------------------------------
    # Use a truncated version of the diff as the query for relevance
    query = state.diff
    if len(query) > 8_000:
        # Chroma has a max input length for the embedding model
        query = query[:8_000]

    try:
        results = collection.query(
            query_texts=[query],
            n_results=TOP_K,
        )
    except Exception as exc:
        logger.warning("Vector store query failed: %s", exc)
        return {}

    # -- Build ContextChunk objects from results ------------------------------
    context_chunks: list[ContextChunk] = []
    if results and results.get("documents") and results["documents"][0]:
        docs_list = results["documents"][0]
        meta_list = results["metadatas"][0] if results.get("metadatas") else []
        dist_list = results["distances"][0] if results.get("distances") else []

        for i, doc_text in enumerate(docs_list):
            meta: dict = meta_list[i] if i < len(meta_list) else {}
            dist: float = dist_list[i] if i < len(dist_list) else 0.0
            # Convert distance to a relevance score (cosine distance β†’ 1 - d)
            relevance = max(0.0, min(1.0, 1.0 - dist))

            context_chunks.append(ContextChunk(
                source=meta.get("source", "codebase"),
                file_path=meta.get("file_path", ""),
                content=doc_text,
                relevance_score=round(relevance, 3),
            ))

    logger.info(
        "Retrieved %d context chunks (query=%s)",
        len(context_chunks), _human_size(len(state.diff)),
    )

    return {
        "context_chunks": context_chunks,  # Annotated[..., add] β†’ accumulated
    }


# ─── Utility ─────────────────────────────────────────────────────────────────


def _human_size(bytes_: int) -> str:
    if bytes_ < 1024:
        return f"{bytes_} B"
    elif bytes_ < 1024 * 1024:
        return f"{bytes_ / 1024:.1f} KiB"
    else:
        return f"{bytes_ / (1024 * 1024):.1f} MiB"