File size: 8,484 Bytes
a8ed78c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Non-destructive source patch for One Petro Library classification V1.

Usage: python apply_patch.py --check
       python apply_patch.py --apply
       python apply_patch.py --undo

Works in a local checkout of the author's Hugging Face Space. Does not touch
SQLite, data/, .env, Telegram file IDs, or any user documents.
"""
from __future__ import annotations

import argparse
import ast
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import sys

ROOT = Path(__file__).resolve().parent
TAX = ROOT / "admin_panel" / "petroleum_taxonomy.py"
ENGINE = ROOT / "admin_panel" / "pdf_engine.py"
PRECISION = ROOT / "admin_panel" / "precision_classifier.py"
BACKUP_DIR = ROOT / ".onepetro_precision_backups"
MARKER = "# ONEPETRO_PRECISION_V1_BEGIN"
QUICK_MARKER = "# ONEPETRO_PRECISION_DEEP_ONLY_V1"
CONTENT_MARKER = "# ONEPETRO_PRECISION_NO_UNREAD_AUTO_MOVE_V1"

WRAPPER = '''\n\n# ONEPETRO_PRECISION_V1_BEGIN
# Route all existing petro.classify(...) call sites through the conservative
# petroleum-specific layer while retaining the original taxonomy and interface.
_classify_before_precision_v1 = classify
from .precision_classifier import classify_with_safeguards as _precision_classify_v1


def classify(title: str, cover: str, body: str) -> tuple[str, str, float, str]:
    return _precision_classify_v1(
        title, cover, body, _classify_before_precision_v1, SECTORS
    )
# ONEPETRO_PRECISION_V1_END
'''

OLD_QUICK = '''        if auto_move_to_section:
            if confidence >= .86 and cat != 'general':
                target_pid=(await move_file_to_sub_discipline(db,file_pk,cat,sub)) or page_id
            else:
                target_pid=await move_file_to_review(db,file_pk)'''

NEW_QUICK = '''        if auto_move_to_section:
            # ONEPETRO_PRECISION_DEEP_ONLY_V1: quick metadata is NOT evidence of PDF content.
            # Save the Telegram reference; only the deep pass assigns a final folder.
            target_pid=await move_file_to_review(db,file_pk)'''

OLD_CONTENT = '''    content_complete = any(len(re.sub(r"\\s+", "", txt)) >= 30 for _,txt in pages_data)
    if confidence < 0.86:'''

NEW_CONTENT = '''    content_complete = any(len(re.sub(r"\\s+", "", txt)) >= 30 for _,txt in pages_data)
    # ONEPETRO_PRECISION_NO_UNREAD_AUTO_MOVE_V1: do not classify an unread file as verified.
    if not content_complete:
        confidence = min(confidence, 0.60)
        explanation += "; no meaningful extracted document text; needs review"
    if confidence < 0.86:'''


def sha256(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def encode(src: str) -> bytes:
    return src.encode("utf-8")


def make_patch(original_tax: str, original_engine: str) -> tuple[str, str, list[str]]:
    notes: list[str] = []
    if MARKER in original_tax and QUICK_MARKER in original_engine and CONTENT_MARKER in original_engine:
        return original_tax, original_engine, ["Already patched; no changes required"]
    if MARKER in original_tax or QUICK_MARKER in original_engine or CONTENT_MARKER in original_engine:
        raise ValueError("Partial patch detected: refuse to modify. Inspect the source or restore backup.")

    if "SECTORS =" not in original_tax or "def classify(" not in original_tax:
        raise ValueError("Expected taxonomy identifiers not found; repository may have changed.")
    if "async def index_uploaded_pdf(" not in original_engine:
        raise ValueError("Expected PDF indexing entry point not found; repository may have changed.")
    if not PRECISION.is_file():
        raise FileNotFoundError("admin_panel/precision_classifier.py is missing. Copy the patch folder first.")

    fixed_tax, count = re.subn(r"sector_margin:\.2\s+f", "sector_margin:.2f", original_tax)
    if count > 1:
        raise ValueError("Unexpected number of format-specifier matches")
    if count == 1:
        notes.append("Fixed invalid sector_margin float formatter")
    elif "sector_margin:.2f" in fixed_tax:
        notes.append("Float formatter already fixed")
    else:
        raise ValueError("Expected sector-margin format specifier not found; please review manually")

    patched_tax = fixed_tax.rstrip("\n") + WRAPPER
    if original_engine.count(OLD_QUICK) != 1:
        raise ValueError("Quick-stage block differs from inspected revision; no files modified")
    if original_engine.count(OLD_CONTENT) != 1:
        raise ValueError("Deep-stage content check differs from inspected revision; no files modified")
    patched_engine = original_engine.replace(OLD_QUICK, NEW_QUICK, 1).replace(OLD_CONTENT, NEW_CONTENT, 1)
    notes.extend(["Quick pass cannot permanently move an unread document",
                  "Deep pass requires meaningful text before high-confidence auto-move",
                  "Existing category names and SQLite schema left unchanged"])
    for name, src in (("petroleum_taxonomy.py", patched_tax), ("pdf_engine.py", patched_engine)):
        ast.parse(src, filename=name)
    return patched_tax, patched_engine, notes


def apply() -> None:
    originals = {p: p.read_bytes() for p in (TAX, ENGINE)}
    t, e, notes = make_patch(originals[TAX].decode("utf-8"), originals[ENGINE].decode("utf-8"))
    if MARKER in originals[TAX].decode("utf-8"):
        print("Already patched. No modifications made.")
        return

    snapshot = BACKUP_DIR / datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    snapshot.mkdir(parents=True, exist_ok=False)
    manifest = {}
    for file, data in originals.items():
        rel = file.relative_to(ROOT)
        backup = snapshot / rel
        backup.parent.mkdir(parents=True, exist_ok=True)
        backup.write_bytes(data)
        manifest[str(rel)] = {"original_sha256": sha256(data)}
    (snapshot / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")

    replacements = {TAX: encode(t), ENGINE: encode(e)}
    try:
        for path, payload in replacements.items():
            tmp = path.with_name(path.name + ".onepetro_tmp")
            tmp.write_bytes(payload)
            os.replace(tmp, path)
        print("PATCH APPLIED. Backup:", snapshot)
        for n in notes:
            print(" +", n)
        print("Next: python run_precision_tests.py")
    except Exception:
        for path, data in originals.items():
            path.write_bytes(data)
        raise


def undo() -> None:
    if not BACKUP_DIR.is_dir():
        raise ValueError("No local backups found")
    backups = sorted(p for p in BACKUP_DIR.iterdir() if p.is_dir())
    if not backups:
        raise ValueError("No local backups found")
    last = backups[-1]
    if MARKER not in TAX.read_text(encoding="utf-8"):
        raise ValueError("Patched file marker not present. Refusing to overwrite manual edits.")
    for rel in ("admin_panel/petroleum_taxonomy.py", "admin_panel/pdf_engine.py"):
        candidate = last / rel
        if not candidate.is_file():
            raise FileNotFoundError(candidate)
        target = ROOT / rel
        tmp = target.with_name(target.name + ".undo_tmp")
        tmp.write_bytes(candidate.read_bytes())
        os.replace(tmp, target)
    print("Original source restored from:", last)
    print("precision_classifier.py remains, but is now unused; database/files were not touched.")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    modes = parser.add_mutually_exclusive_group(required=True)
    modes.add_argument("--check", action="store_true", help="Validate patch compatibility without writing")
    modes.add_argument("--apply", action="store_true", help="Back up and modify source files")
    modes.add_argument("--undo", action="store_true", help="Restore last local source backup")
    args = parser.parse_args()
    if args.undo:
        undo()
        return
    if not TAX.is_file() or not ENGINE.is_file():
        raise FileNotFoundError("Run this script from a copy of ONE PETRO LIBRARY (with admin_panel/ files)")
    if args.apply:
        apply()
    else:
        _, _, notes = make_patch(TAX.read_text(encoding="utf-8"), ENGINE.read_text(encoding="utf-8"))
        print("PATCH COMPATIBLE; no files modified.")
        for n in notes:
            print(" +", n)


if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, SyntaxError) as exc:
        print("PATCH ABORTED SAFELY:", exc, file=sys.stderr)
        sys.exit(2)