codehaven 0.14.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codehaven-0.14.0.dist-info/METADATA +686 -0
- codehaven-0.14.0.dist-info/RECORD +57 -0
- codehaven-0.14.0.dist-info/WHEEL +5 -0
- codehaven-0.14.0.dist-info/entry_points.txt +3 -0
- codehaven-0.14.0.dist-info/licenses/LICENSE +21 -0
- codehaven-0.14.0.dist-info/top_level.txt +1 -0
- offline_agent/__init__.py +2 -0
- offline_agent/__main__.py +4 -0
- offline_agent/agent.py +815 -0
- offline_agent/answers.py +438 -0
- offline_agent/arabic.py +106 -0
- offline_agent/changes.py +228 -0
- offline_agent/chats.py +121 -0
- offline_agent/cli.py +379 -0
- offline_agent/coder.py +199 -0
- offline_agent/dependencies.py +132 -0
- offline_agent/doctor.py +190 -0
- offline_agent/documents.py +189 -0
- offline_agent/edits.py +204 -0
- offline_agent/errors.py +41 -0
- offline_agent/evaluation.py +284 -0
- offline_agent/evidence.py +187 -0
- offline_agent/exclusions.py +95 -0
- offline_agent/export.py +27 -0
- offline_agent/gui.css +237 -0
- offline_agent/gui.html +177 -0
- offline_agent/gui.js +1213 -0
- offline_agent/gui.py +967 -0
- offline_agent/gui_arabic.js +226 -0
- offline_agent/guides.py +203 -0
- offline_agent/history.py +126 -0
- offline_agent/index_cache.py +78 -0
- offline_agent/insights.py +333 -0
- offline_agent/javascript.py +200 -0
- offline_agent/knowledge.py +569 -0
- offline_agent/languages.py +396 -0
- offline_agent/memory.py +192 -0
- offline_agent/messages.py +51 -0
- offline_agent/model.py +498 -0
- offline_agent/more_languages.py +253 -0
- offline_agent/ocr.py +204 -0
- offline_agent/prompts.py +130 -0
- offline_agent/references/langgraph-approvals.md +38 -0
- offline_agent/references/langgraph-checkpoints.md +37 -0
- offline_agent/references/langgraph-graphs.md +42 -0
- offline_agent/references/langgraph.md +49 -0
- offline_agent/review.py +205 -0
- offline_agent/scans.py +325 -0
- offline_agent/semantic.py +264 -0
- offline_agent/slash.py +53 -0
- offline_agent/study.py +210 -0
- offline_agent/symbols.py +201 -0
- offline_agent/tasks.py +164 -0
- offline_agent/test_runner.py +264 -0
- offline_agent/trace.py +239 -0
- offline_agent/tracebacks.py +98 -0
- offline_agent/workspace.py +419 -0
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Static Python import resolution over already indexed local files only."""
|
|
2
|
+
import ast
|
|
3
|
+
import sys
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
from pathlib import PurePosixPath
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PythonDependencies:
|
|
9
|
+
"""Imports, top-level definitions, and symbol spans of Python files, found with ast: nothing is imported or run."""
|
|
10
|
+
def __init__(self, files, reuse=None):
|
|
11
|
+
"""Analyse files, a dict of repository path -> text.
|
|
12
|
+
|
|
13
|
+
reuse maps a path to its (definitions, spans, edges, missing) from an earlier analysis of the same text and the same
|
|
14
|
+
set of paths; those files are not parsed again.
|
|
15
|
+
|
|
16
|
+
edges: importer -> {imported file: [names taken from it]}, where "" stands for the module as a whole.
|
|
17
|
+
definitions: file -> {top-level name: line}. spans: file -> [{"name", "start", "end"}] for every function
|
|
18
|
+
and class, nested ones too. A file that does not parse is counted in parse_failures and skipped.
|
|
19
|
+
missing: file -> [{"module", "name", "line", "local"}] for each import of code that is not in the repository and
|
|
20
|
+
not in Python's standard library: name is what the import binds in the file, and local marks a relative import.
|
|
21
|
+
"""
|
|
22
|
+
self.missing = {}
|
|
23
|
+
self.edges = {}
|
|
24
|
+
self.definitions = {}
|
|
25
|
+
self.spans = {}
|
|
26
|
+
self.parse_failures = 0
|
|
27
|
+
self.files = files
|
|
28
|
+
reuse = reuse or {}
|
|
29
|
+
for name, text in files.items():
|
|
30
|
+
if name in reuse:
|
|
31
|
+
self.definitions[name], self.spans[name], self.edges[name], self.missing[name] = reuse[name]
|
|
32
|
+
continue
|
|
33
|
+
try:
|
|
34
|
+
tree = ast.parse(text, filename=name)
|
|
35
|
+
except (SyntaxError, ValueError, RecursionError):
|
|
36
|
+
self.parse_failures += 1
|
|
37
|
+
continue
|
|
38
|
+
definitions = {}
|
|
39
|
+
for node in tree.body:
|
|
40
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
41
|
+
definitions[node.name] = node.lineno
|
|
42
|
+
elif isinstance(node, (ast.Assign, ast.AnnAssign)):
|
|
43
|
+
targets = node.targets if isinstance(node, ast.Assign) else [node.target]
|
|
44
|
+
for target in targets:
|
|
45
|
+
if isinstance(target, ast.Name):
|
|
46
|
+
definitions[target.id] = node.lineno
|
|
47
|
+
self.definitions[name] = definitions
|
|
48
|
+
# One walk of the tree collects both the spans and the imports: walking it twice doubled the indexing time.
|
|
49
|
+
spans = self.spans[name] = []
|
|
50
|
+
found = defaultdict(set)
|
|
51
|
+
missing = self.missing[name] = []
|
|
52
|
+
for node in ast.walk(tree):
|
|
53
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
54
|
+
# A span starts at its first decorator, so decorators are shown together with what they decorate.
|
|
55
|
+
spans.append({"name": node.name, "start": min([node.lineno] + [d.lineno for d in node.decorator_list]),
|
|
56
|
+
"end": node.end_lineno})
|
|
57
|
+
elif isinstance(node, ast.Import):
|
|
58
|
+
for alias in node.names:
|
|
59
|
+
target = self._absolute(alias.name, name)
|
|
60
|
+
self._add(found, target, None)
|
|
61
|
+
if not target:
|
|
62
|
+
# "import a.b" binds a; "import a.b as c" binds c.
|
|
63
|
+
self._missing(missing, alias.name, alias.asname or alias.name.split('.')[0], node.lineno)
|
|
64
|
+
elif isinstance(node, ast.ImportFrom):
|
|
65
|
+
# Relative import: one dot is the importing file's own folder, and each further dot climbs one folder.
|
|
66
|
+
if node.level:
|
|
67
|
+
parent = list(PurePosixPath(name).parent.parts)
|
|
68
|
+
if node.level > len(parent):
|
|
69
|
+
for alias in node.names:
|
|
70
|
+
self._missing(missing, '.' * node.level + (node.module or ''), alias.asname or alias.name,
|
|
71
|
+
node.lineno, local=True)
|
|
72
|
+
continue
|
|
73
|
+
base = parent[:len(parent) - node.level + 1]
|
|
74
|
+
if node.module:
|
|
75
|
+
base += node.module.split('.')
|
|
76
|
+
stem = '/'.join(base)
|
|
77
|
+
target = self._resolve(stem)
|
|
78
|
+
for alias in node.names:
|
|
79
|
+
# In "from .pkg import name", name may be a submodule with its own file, or a symbol inside pkg.
|
|
80
|
+
child = self._resolve(stem + '/' + alias.name)
|
|
81
|
+
self._add(found, child or target, None if child else alias.name)
|
|
82
|
+
if not child and not target:
|
|
83
|
+
self._missing(missing, '.' * node.level + (node.module or ''), alias.asname or alias.name,
|
|
84
|
+
node.lineno, local=True)
|
|
85
|
+
else:
|
|
86
|
+
module = node.module or ''
|
|
87
|
+
target = self._absolute(module, name)
|
|
88
|
+
for alias in node.names:
|
|
89
|
+
child = self._absolute(module + '.' + alias.name, name)
|
|
90
|
+
self._add(found, child or target, None if child else alias.name)
|
|
91
|
+
if not child and not target:
|
|
92
|
+
self._missing(missing, module, alias.asname or alias.name, node.lineno)
|
|
93
|
+
# Package initializers can also define import-time behavior.
|
|
94
|
+
for target in list(found):
|
|
95
|
+
parts = PurePosixPath(target).parent.parts
|
|
96
|
+
for length in range(1, len(parts) + 1):
|
|
97
|
+
initializer = '/'.join(parts[:length]) + '/__init__.py'
|
|
98
|
+
if initializer in files and initializer != name:
|
|
99
|
+
found[initializer].add('')
|
|
100
|
+
self.edges[name] = {target: sorted(symbols) for target, symbols in sorted(found.items())
|
|
101
|
+
if target != name}
|
|
102
|
+
|
|
103
|
+
def _resolve(self, stem):
|
|
104
|
+
"""The indexed file for a module path without suffix: a module, a package initializer, or a stub. None if not indexed."""
|
|
105
|
+
for suffix in ('.py', '/__init__.py', '.pyi', '/__init__.pyi'):
|
|
106
|
+
if stem + suffix in self.files:
|
|
107
|
+
return stem + suffix
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
def _absolute(self, module, importer):
|
|
111
|
+
"""The indexed file for a dotted module name, tried from the repository root, from src/, and beside the importer."""
|
|
112
|
+
stem = module.replace('.', '/')
|
|
113
|
+
for prefix in ('', 'src/', str(PurePosixPath(importer).parent) + '/'):
|
|
114
|
+
result = self._resolve(prefix + stem)
|
|
115
|
+
if result:
|
|
116
|
+
return result
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
@staticmethod
|
|
120
|
+
def _missing(missing, module, bound, line, local=False):
|
|
121
|
+
"""Record an import of code that is not here. The standard library and __future__ are known code, so left out."""
|
|
122
|
+
top = module.split('.')[0]
|
|
123
|
+
if not local and (top in sys.stdlib_module_names or top == '__future__'):
|
|
124
|
+
return
|
|
125
|
+
if bound != '*':
|
|
126
|
+
missing.append({"module": module, "name": bound, "line": line, "local": local})
|
|
127
|
+
|
|
128
|
+
@staticmethod
|
|
129
|
+
def _add(found, target, symbol):
|
|
130
|
+
"""Record that target is imported; a whole-module or star import is stored as the empty name."""
|
|
131
|
+
if target:
|
|
132
|
+
found[target].add('' if symbol in (None, '*') else symbol)
|
offline_agent/doctor.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Start-up help: say what is missing and how to get it, and start a local Ollama server when asked.
|
|
2
|
+
|
|
3
|
+
Nothing here uses the internet. The checks look for programs on this computer and ask Ollama on its loopback
|
|
4
|
+
address. --start-ollama runs the installed `ollama serve` bound to 127.0.0.1 with its cloud features off, the
|
|
5
|
+
same way scripts/start_ollama.py does, and stops it again when CodeHaven exits.
|
|
6
|
+
"""
|
|
7
|
+
import importlib.util
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import time
|
|
12
|
+
import urllib.parse
|
|
13
|
+
|
|
14
|
+
from .model import MODEL
|
|
15
|
+
|
|
16
|
+
START_SECONDS = 20 # How long to wait for a server that was just started.
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def running(model):
|
|
20
|
+
"""Whether an Ollama server answers at the model's loopback endpoint."""
|
|
21
|
+
try:
|
|
22
|
+
return isinstance(model.request("/api/tags").get("models"), list)
|
|
23
|
+
except ValueError:
|
|
24
|
+
return False
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def start_ollama(model, output=print):
|
|
28
|
+
"""Start `ollama serve` for this run if no server is answering. Returns the process to stop later, or None.
|
|
29
|
+
|
|
30
|
+
The server listens on the loopback address of --endpoint only and has cloud features off. A server that is
|
|
31
|
+
already running is left as it is, and so is its cloud setting.
|
|
32
|
+
"""
|
|
33
|
+
if running(model):
|
|
34
|
+
output("Ollama is already running; using it as it is.")
|
|
35
|
+
return None
|
|
36
|
+
program = shutil.which("ollama")
|
|
37
|
+
if program is None:
|
|
38
|
+
raise ValueError("Ollama is not installed, or is not on PATH. Install it from https://ollama.com/, then run this again.")
|
|
39
|
+
address = urllib.parse.urlsplit(model.endpoint)
|
|
40
|
+
env = {**os.environ, "OLLAMA_NO_CLOUD": "1", "OLLAMA_HOST": f"{address.hostname}:{address.port or 11434}"}
|
|
41
|
+
process = subprocess.Popen([program, "serve"], env=env, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
|
|
42
|
+
stderr=subprocess.DEVNULL)
|
|
43
|
+
deadline = time.monotonic() + START_SECONDS
|
|
44
|
+
while time.monotonic() < deadline:
|
|
45
|
+
if process.poll() is not None:
|
|
46
|
+
raise ValueError(f"Ollama stopped as soon as it started (exit code {process.returncode}). Run `ollama serve` to see why.")
|
|
47
|
+
if running(model):
|
|
48
|
+
output(f"Started Ollama on {env['OLLAMA_HOST']} with cloud features off. It stops when CodeHaven exits.")
|
|
49
|
+
return process
|
|
50
|
+
time.sleep(0.25)
|
|
51
|
+
stop_ollama(process)
|
|
52
|
+
raise ValueError(f"Ollama did not answer within {START_SECONDS} seconds of starting.")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def stop_ollama(process):
|
|
56
|
+
"""Stop a server started by start_ollama, waiting briefly before forcing it."""
|
|
57
|
+
if process is None or process.poll() is not None:
|
|
58
|
+
return
|
|
59
|
+
process.terminate()
|
|
60
|
+
try:
|
|
61
|
+
process.wait(5)
|
|
62
|
+
except subprocess.TimeoutExpired:
|
|
63
|
+
process.kill()
|
|
64
|
+
process.wait()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def missing_server(model):
|
|
68
|
+
"""Why the model could not be reached, as lines that each say what to do next."""
|
|
69
|
+
if shutil.which("ollama") is None:
|
|
70
|
+
return ["Ollama: not installed. Install it from https://ollama.com/ (needed once, while online).",
|
|
71
|
+
f"Then download the model once: ollama pull {model.model}"]
|
|
72
|
+
if not running(model):
|
|
73
|
+
return [f"Ollama: installed, but no server answers at {model.endpoint}.",
|
|
74
|
+
"Start it for this run by adding --start-ollama, for example: codehaven --gui --start-ollama",
|
|
75
|
+
"Or leave one running in another terminal: ollama serve"]
|
|
76
|
+
try:
|
|
77
|
+
installed = [found["name"] for found in model.local_models()]
|
|
78
|
+
except ValueError:
|
|
79
|
+
installed = []
|
|
80
|
+
lines = [f"Ollama: running, but the model {model.model} is not installed.",
|
|
81
|
+
f"Download it once, while online: ollama pull {model.model}"]
|
|
82
|
+
if installed:
|
|
83
|
+
lines.append("Or use one that is installed: --model " + installed[0]
|
|
84
|
+
+ (f" (also installed: {', '.join(installed[1:4])})" if installed[1:] else ""))
|
|
85
|
+
return lines
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def extras(docker_image=None):
|
|
89
|
+
"""One line per optional tool: found, or what it adds and how to install it. None of them is needed to chat."""
|
|
90
|
+
lines = []
|
|
91
|
+
lines.append("Pictures of code: Tesseract found." if shutil.which("tesseract") else
|
|
92
|
+
"Pictures of code: off. Install Tesseract to turn it on (brew install tesseract, or apt install tesseract-ocr).")
|
|
93
|
+
pdf = importlib.util.find_spec("pypdf") is not None or shutil.which("pdftotext")
|
|
94
|
+
lines.append("PDFs: a PDF reader was found." if pdf else
|
|
95
|
+
"PDFs: off. Install one to turn it on (python -m pip install pypdf, or brew install poppler).")
|
|
96
|
+
lines.append("Isolated tests: Docker found." + (f" Image expected: {docker_image}." if docker_image else "")
|
|
97
|
+
if shutil.which("docker") else
|
|
98
|
+
"Isolated tests: off. Install Docker to let CodeHaven run a project's tests in a container.")
|
|
99
|
+
lines.append("Git changes: git found." if shutil.which("git") else "Git changes: off. Install git to ask about your changes.")
|
|
100
|
+
return lines
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def default_model_hint(model):
|
|
104
|
+
"""A line for --doctor when the model in use is not the tested default."""
|
|
105
|
+
return (f"Note: {model.model} is not the tested default ({MODEL}); answers may differ." if model.model != MODEL else "")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# The model to suggest for a computer's memory, smallest first: (at least this many GB, model, why).
|
|
109
|
+
# Measured in docs/EVALS.md: the 7B coder model is the tested default; the 14B one is as often right and cites more
|
|
110
|
+
# carefully; the 0.5B model was right about a third of the time, so it is never suggested.
|
|
111
|
+
SUGGESTIONS = [
|
|
112
|
+
(0, "qwen2.5-coder:3b", "smaller than the tested default; expect more wrong or unverified answers"),
|
|
113
|
+
(12, MODEL, "the tested default"),
|
|
114
|
+
(32, "qwen2.5:14b", "as often right as the default and more careful with citations, about half as fast"),
|
|
115
|
+
]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def memory_gb():
|
|
119
|
+
"""This computer's memory in GB, or None when it cannot be told. Read from the system, never from the network."""
|
|
120
|
+
try:
|
|
121
|
+
if hasattr(os, "sysconf") and "SC_PHYS_PAGES" in os.sysconf_names:
|
|
122
|
+
return round(os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") / 1024 ** 3)
|
|
123
|
+
except (OSError, ValueError):
|
|
124
|
+
pass
|
|
125
|
+
if os.name == "nt":
|
|
126
|
+
import ctypes
|
|
127
|
+
|
|
128
|
+
class Status(ctypes.Structure):
|
|
129
|
+
"""The fields of MEMORYSTATUSEX that Windows fills in."""
|
|
130
|
+
_fields_ = [("length", ctypes.c_ulong), ("load", ctypes.c_ulong), ("total", ctypes.c_ulonglong),
|
|
131
|
+
("available", ctypes.c_ulonglong), ("page_total", ctypes.c_ulonglong),
|
|
132
|
+
("page_available", ctypes.c_ulonglong), ("virtual_total", ctypes.c_ulonglong),
|
|
133
|
+
("virtual_available", ctypes.c_ulonglong), ("extended", ctypes.c_ulonglong)]
|
|
134
|
+
status = Status()
|
|
135
|
+
status.length = ctypes.sizeof(Status)
|
|
136
|
+
if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
|
|
137
|
+
return round(status.total / 1024 ** 3)
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def suggested_model(gigabytes=None):
|
|
142
|
+
"""(model, why) to suggest for a computer with this much memory (this one's when not given)."""
|
|
143
|
+
gigabytes = memory_gb() if gigabytes is None else gigabytes
|
|
144
|
+
if gigabytes is None:
|
|
145
|
+
return MODEL, "the tested default (this computer's memory could not be read)"
|
|
146
|
+
choice = [row for row in SUGGESTIONS if gigabytes >= row[0]][-1]
|
|
147
|
+
return choice[1], f"{choice[2]}; this computer has {gigabytes} GB of memory"
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def setup(model, ask=input, output=print, run=subprocess.run):
|
|
151
|
+
"""Guided first run: check Ollama, start it if needed, and download a model only if the user says yes.
|
|
152
|
+
|
|
153
|
+
This is the one place CodeHaven uses the internet, and only through `ollama pull`, after asking. Returns 0 when
|
|
154
|
+
CodeHaven is ready to use, 1 otherwise.
|
|
155
|
+
"""
|
|
156
|
+
program = shutil.which("ollama")
|
|
157
|
+
if program is None:
|
|
158
|
+
output("Ollama is not installed. Install it from https://ollama.com/ (once, while online), then run codehaven --setup again.")
|
|
159
|
+
return 1
|
|
160
|
+
output("Ollama: installed.")
|
|
161
|
+
server = None
|
|
162
|
+
if not running(model):
|
|
163
|
+
server = start_ollama(model, output)
|
|
164
|
+
try:
|
|
165
|
+
installed = {found["name"] for found in model.local_models()}
|
|
166
|
+
suggestion, why = suggested_model()
|
|
167
|
+
output(f"Suggested model for this computer: {suggestion} ({why}).")
|
|
168
|
+
wanted = model.model if model.model in installed else suggestion
|
|
169
|
+
if wanted not in installed:
|
|
170
|
+
answer = ask(f"Download {wanted} now with ollama pull? It is a few GB and needs the internet once. [y/N] ")
|
|
171
|
+
if answer.strip().lower() != "y":
|
|
172
|
+
output(f"Nothing was downloaded. When you are ready: ollama pull {wanted}")
|
|
173
|
+
return 1
|
|
174
|
+
done = run([program, "pull", wanted], env={**os.environ, "OLLAMA_NO_CLOUD": "1"})
|
|
175
|
+
if done.returncode:
|
|
176
|
+
output(f"ollama pull {wanted} did not finish (exit code {done.returncode}). Check the connection and try again.")
|
|
177
|
+
return 1
|
|
178
|
+
output(f"Chat model: {wanted} is installed.")
|
|
179
|
+
embedders = [name for name in installed if "embed" in name]
|
|
180
|
+
if not embedders:
|
|
181
|
+
answer = ask("Also download nomic-embed-text (about 270 MB) so search works by meaning too? [y/N] ")
|
|
182
|
+
if answer.strip().lower() == "y":
|
|
183
|
+
run([program, "pull", "nomic-embed-text"], env={**os.environ, "OLLAMA_NO_CLOUD": "1"})
|
|
184
|
+
for line in extras():
|
|
185
|
+
output(line)
|
|
186
|
+
command = "codehaven --gui --start-ollama" + (f" --model {wanted}" if wanted != MODEL else "")
|
|
187
|
+
output(f"Ready. From now on everything works offline. Start with: {command}")
|
|
188
|
+
return 0
|
|
189
|
+
finally:
|
|
190
|
+
stop_ollama(server)
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Read a Jupyter notebook or a PDF into one text file, so it can be chatted about like any uploaded file.
|
|
2
|
+
|
|
3
|
+
Both are read on this computer and nothing leaves it. The original file is never changed: the chat is about a
|
|
4
|
+
text copy kept in the same private temporary folder as any uploaded file.
|
|
5
|
+
|
|
6
|
+
A notebook (.ipynb) is JSON. Its code and Markdown cells become one file in the "percent" layout editors
|
|
7
|
+
understand: each cell starts with a "# %%" line that carries its number, and Markdown becomes comments.
|
|
8
|
+
Outputs, pictures, and widget state are left out. A Python notebook becomes a .py file.
|
|
9
|
+
|
|
10
|
+
A PDF's text is read by pypdf when that package is installed, or else by the pdftotext program (part of
|
|
11
|
+
Poppler). Either works offline. Each page starts with a "===== Page N =====" line, so a cited line can be
|
|
12
|
+
found on its page. A scanned PDF holds pictures, not text; a screenshot of the page can be read instead.
|
|
13
|
+
|
|
14
|
+
A document longer than CodeHaven reads at once (64 KB of text) is cut at a cell or page boundary, and the
|
|
15
|
+
result says how much was kept.
|
|
16
|
+
"""
|
|
17
|
+
import io
|
|
18
|
+
import json
|
|
19
|
+
import re
|
|
20
|
+
import shutil
|
|
21
|
+
import subprocess
|
|
22
|
+
import tempfile
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
from .workspace import MAX_BYTES
|
|
26
|
+
|
|
27
|
+
DOCUMENT_BYTES = 8_000_000 # The largest notebook or PDF accepted; the text read from it is far smaller.
|
|
28
|
+
# The most pages read from one PDF, and the longest pdftotext may run.
|
|
29
|
+
PDF_PAGES, PDF_SECONDS = 300, 60
|
|
30
|
+
EXTENSIONS = {"python": ".py", "javascript": ".js", "typescript": ".ts", "r": ".r", "julia": ".jl", "ruby": ".rb",
|
|
31
|
+
"scala": ".scala", "bash": ".sh", "go": ".go", "rust": ".rs", "java": ".java", "kotlin": ".kt"}
|
|
32
|
+
PDF_HELP = ("Reading a PDF needs pypdf or pdftotext on this computer, and neither was found. Install one once while "
|
|
33
|
+
"online: `python -m pip install pypdf`, or Poppler (`brew install poppler`; Ubuntu or Debian: "
|
|
34
|
+
"`sudo apt install poppler-utils`). Everything else keeps working.")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def kind(name, data):
|
|
38
|
+
""""pdf", "notebook", or None for any other upload."""
|
|
39
|
+
if data[:1024].lstrip().startswith(b"%PDF-"):
|
|
40
|
+
return "pdf"
|
|
41
|
+
if str(name).lower().endswith(".ipynb"):
|
|
42
|
+
return "notebook"
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def stem(name):
|
|
47
|
+
"""The upload's name without .ipynb or .pdf, or "document" when nothing usable is left."""
|
|
48
|
+
base = re.sub(r"\.(?:ipynb|pdf)$", "", name, flags=re.I)
|
|
49
|
+
return base if base.strip("._") else "document"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def source(cell):
|
|
53
|
+
"""A cell's text; a notebook stores it as one string or as a list of lines."""
|
|
54
|
+
text = cell.get("source", "")
|
|
55
|
+
text = "".join(part for part in text if isinstance(part, str)) if isinstance(text, list) else text
|
|
56
|
+
return text if isinstance(text, str) else ""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def read_notebook(name, data):
|
|
60
|
+
"""Turn a notebook into one text file. Returns {"name", "text", "source", "kind", "note"}."""
|
|
61
|
+
if len(data) > DOCUMENT_BYTES:
|
|
62
|
+
raise ValueError(f"Only notebooks up to {DOCUMENT_BYTES // 1_000_000} MB can be read.")
|
|
63
|
+
try:
|
|
64
|
+
notebook = json.loads(data.decode("utf-8"))
|
|
65
|
+
cells = notebook["cells"] if isinstance(notebook, dict) else None
|
|
66
|
+
except (ValueError, KeyError, RecursionError):
|
|
67
|
+
cells = None
|
|
68
|
+
if not isinstance(cells, list):
|
|
69
|
+
raise ValueError("This does not look like a Jupyter notebook (.ipynb): it holds no list of cells.")
|
|
70
|
+
metadata = notebook.get("metadata") if isinstance(notebook.get("metadata"), dict) else {}
|
|
71
|
+
language = ""
|
|
72
|
+
# The notebook's language decides the copy's file extension and comment marker; a notebook that names none is taken as Python.
|
|
73
|
+
for section in ("kernelspec", "language_info"):
|
|
74
|
+
info = metadata.get(section)
|
|
75
|
+
if isinstance(info, dict) and isinstance(info.get("language") or info.get("name"), str):
|
|
76
|
+
language = (info.get("language") or info.get("name")).lower()
|
|
77
|
+
break
|
|
78
|
+
extension = next((ext for known, ext in EXTENSIONS.items() if language.startswith(known)), ".py" if not language else ".txt")
|
|
79
|
+
comment = "//" if extension in (".js", ".ts", ".go", ".rs", ".java", ".kt", ".scala") else "#"
|
|
80
|
+
blocks, kept, code_cells, size = [], 0, 0, 0
|
|
81
|
+
usable = [cell for cell in cells if isinstance(cell, dict) and cell.get("cell_type") in ("code", "markdown", "raw")
|
|
82
|
+
and source(cell).strip()]
|
|
83
|
+
for number, cell in enumerate(usable, 1):
|
|
84
|
+
body = source(cell).rstrip("\n")
|
|
85
|
+
if cell["cell_type"] == "code":
|
|
86
|
+
# IPython magics and shell lines are not valid code in the file, so they are kept as comments.
|
|
87
|
+
body = "\n".join(f"{comment} {line}" if re.match(r"\s*[%!]", line) else line for line in body.splitlines())
|
|
88
|
+
block = f"{comment} %% Cell {number}\n{body}\n"
|
|
89
|
+
else:
|
|
90
|
+
block = (f"{comment} %% [markdown] Cell {number}\n"
|
|
91
|
+
+ "\n".join(f"{comment} {line}".rstrip() for line in body.splitlines()) + "\n")
|
|
92
|
+
if size + len(block.encode()) + 1 > MAX_BYTES:
|
|
93
|
+
break
|
|
94
|
+
blocks.append(block)
|
|
95
|
+
size += len(block.encode()) + 1
|
|
96
|
+
kept += 1
|
|
97
|
+
code_cells += cell["cell_type"] == "code"
|
|
98
|
+
if not blocks:
|
|
99
|
+
raise ValueError("This notebook has no code or text cells to read."
|
|
100
|
+
if not usable else f"The notebook's first cell alone is over {MAX_BYTES // 1000} KB, more than CodeHaven reads.")
|
|
101
|
+
note = (f"Read {kept} cell{'s' if kept != 1 else ''} ({code_cells} with code) from the notebook {name}. "
|
|
102
|
+
"Outputs and pictures are left out; each cell starts with a line naming its number.")
|
|
103
|
+
if kept < len(usable):
|
|
104
|
+
note += f" Only cells 1-{kept} of {len(usable)} fit in the {MAX_BYTES // 1000} KB CodeHaven reads at once."
|
|
105
|
+
return {"name": stem(name) + extension, "text": "\n".join(blocks), "source": name, "kind": "notebook", "note": note}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def pdf_pages(data):
|
|
109
|
+
"""The text of each page, in order, read by pypdf when installed and otherwise by pdftotext."""
|
|
110
|
+
try:
|
|
111
|
+
from pypdf import PdfReader
|
|
112
|
+
except ImportError:
|
|
113
|
+
PdfReader = None
|
|
114
|
+
if PdfReader is not None:
|
|
115
|
+
try:
|
|
116
|
+
reader = PdfReader(io.BytesIO(data))
|
|
117
|
+
if reader.is_encrypted and not reader.decrypt(""):
|
|
118
|
+
raise ValueError("This PDF is protected by a password, so its text cannot be read.")
|
|
119
|
+
pages = []
|
|
120
|
+
for page in reader.pages[:PDF_PAGES]:
|
|
121
|
+
try:
|
|
122
|
+
pages.append(page.extract_text(extraction_mode="layout") or "")
|
|
123
|
+
except Exception: # One odd page should not lose the document.
|
|
124
|
+
pages.append(page.extract_text() or "")
|
|
125
|
+
return pages, len(reader.pages)
|
|
126
|
+
except ValueError:
|
|
127
|
+
raise
|
|
128
|
+
except Exception as exc:
|
|
129
|
+
raise ValueError(f"This PDF could not be read: {str(exc)[:160] or type(exc).__name__}") from exc
|
|
130
|
+
program = shutil.which("pdftotext")
|
|
131
|
+
if program is None:
|
|
132
|
+
raise ValueError(PDF_HELP)
|
|
133
|
+
with tempfile.TemporaryDirectory(prefix="codehaven-pdf-") as folder: # Readable by this user only; deleted after.
|
|
134
|
+
copy = Path(folder, "document.pdf")
|
|
135
|
+
copy.write_bytes(data)
|
|
136
|
+
try:
|
|
137
|
+
# -layout keeps columns and indentation, -l stops after PDF_PAGES pages, and the final "-" writes to standard output.
|
|
138
|
+
done = subprocess.run([program, "-layout", "-enc", "UTF-8", "-l", str(PDF_PAGES), str(copy), "-"],
|
|
139
|
+
capture_output=True, stdin=subprocess.DEVNULL, timeout=PDF_SECONDS)
|
|
140
|
+
except subprocess.TimeoutExpired as exc:
|
|
141
|
+
raise ValueError("Reading this PDF took too long and was stopped.") from exc
|
|
142
|
+
except OSError as exc:
|
|
143
|
+
raise ValueError(f"pdftotext could not be started: {exc}") from exc
|
|
144
|
+
if done.returncode != 0:
|
|
145
|
+
last = [line.strip() for line in done.stderr.decode("utf-8", "replace").splitlines() if line.strip()]
|
|
146
|
+
raise ValueError("This PDF could not be read" + (f": {last[-1][:160]}" if last else "."))
|
|
147
|
+
pages = done.stdout.decode("utf-8", "replace").split("\f")
|
|
148
|
+
if pages and not pages[-1].strip():
|
|
149
|
+
pages.pop() # pdftotext ends every page, the last one too, with a form feed.
|
|
150
|
+
return pages, len(pages)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def read_pdf(name, data):
|
|
154
|
+
"""Turn a PDF's text into one text file. Returns {"name", "text", "source", "kind", "note"}."""
|
|
155
|
+
if len(data) > DOCUMENT_BYTES:
|
|
156
|
+
raise ValueError(f"Only PDFs up to {DOCUMENT_BYTES // 1_000_000} MB can be read.")
|
|
157
|
+
pages, total = pdf_pages(data)
|
|
158
|
+
blocks, kept, size = [], 0, 0
|
|
159
|
+
for number, page in enumerate(pages, 1):
|
|
160
|
+
lines = [line.rstrip() for line in page.replace("\0", "").splitlines()]
|
|
161
|
+
while lines and not lines[-1]:
|
|
162
|
+
lines.pop()
|
|
163
|
+
while lines and not lines[0]:
|
|
164
|
+
lines.pop(0)
|
|
165
|
+
# Layout mode pads every line alike; drop the shared margin but keep the indentation code depends on.
|
|
166
|
+
margin = min((len(line) - len(line.lstrip()) for line in lines if line.strip()), default=0)
|
|
167
|
+
block = f"===== Page {number} =====\n" + "\n".join(line[margin:] if line.strip() else "" for line in lines) + "\n"
|
|
168
|
+
if size + len(block.encode()) + 1 > MAX_BYTES:
|
|
169
|
+
break
|
|
170
|
+
blocks.append(block)
|
|
171
|
+
size += len(block.encode()) + 1
|
|
172
|
+
kept += 1
|
|
173
|
+
if not any(block.split("\n", 1)[1].strip() for block in blocks):
|
|
174
|
+
raise ValueError("No text was found in this PDF. It may be scanned pages, which are pictures: attach a "
|
|
175
|
+
"screenshot of the page instead and CodeHaven reads the code in it."
|
|
176
|
+
if pages else "This PDF has no pages to read.")
|
|
177
|
+
note = (f"Read {kept} page{'s' if kept != 1 else ''} of text from the PDF {name}. Each page starts with a line naming "
|
|
178
|
+
"its number. Columns, tables, and code can lose their layout, so check anything that matters against the PDF.")
|
|
179
|
+
if kept < total:
|
|
180
|
+
note += f" Only pages 1-{kept} of {total} fit in the {MAX_BYTES // 1000} KB CodeHaven reads at once."
|
|
181
|
+
return {"name": stem(name) + ".txt", "text": "\n".join(blocks), "source": name, "kind": "pdf", "note": note}
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def read_document(name, data):
|
|
185
|
+
"""Read an uploaded notebook or PDF, whichever kind() finds. ValueError for any other file."""
|
|
186
|
+
found = kind(name, data)
|
|
187
|
+
if found is None:
|
|
188
|
+
raise ValueError("Only notebooks (.ipynb) and PDFs can be read as documents.")
|
|
189
|
+
return read_pdf(name, data) if found == "pdf" else read_notebook(name, data)
|