any2llm 0.2.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.
- any2llm/__init__.py +0 -0
- any2llm/__main__.py +6 -0
- any2llm/cleaner.py +38 -0
- any2llm/cli.py +361 -0
- any2llm/clipboard.py +28 -0
- any2llm/config.py +87 -0
- any2llm/demo.py +18 -0
- any2llm/demo_assets/en/measurement-and-bias.pptx +0 -0
- any2llm/demo_assets/en/measurement-plan.xlsx +0 -0
- any2llm/demo_assets/en/research-designs.pdf +0 -0
- any2llm/demo_assets/en/study-checklist.docx +0 -0
- any2llm/demo_assets/tr/ara/305/237t/304/261rma-desenleri.pdf +0 -0
- any2llm/demo_assets/tr//303/247al/304/261/305/237ma-listesi.docx +0 -0
- any2llm/demo_assets/tr//303/266l/303/247/303/274m-plan/304/261.xlsx +0 -0
- any2llm/demo_assets/tr//303/266l/303/247/303/274m-ve-yanl/304/261l/304/261k.pptx +0 -0
- any2llm/ignore.py +66 -0
- any2llm/languages.py +49 -0
- any2llm/locales/ar.json +128 -0
- any2llm/locales/bn.json +129 -0
- any2llm/locales/en.json +128 -0
- any2llm/locales/es.json +128 -0
- any2llm/locales/fr.json +128 -0
- any2llm/locales/hi.json +129 -0
- any2llm/locales/pt.json +128 -0
- any2llm/locales/ru.json +128 -0
- any2llm/locales/tr.json +128 -0
- any2llm/locales/ur.json +128 -0
- any2llm/locales/zh.json +128 -0
- any2llm/messages.py +23 -0
- any2llm/ocr.py +47 -0
- any2llm/output.py +131 -0
- any2llm/packer.py +224 -0
- any2llm/parse_worker.py +75 -0
- any2llm/parsers.py +340 -0
- any2llm/prompts.py +32 -0
- any2llm/scanner.py +122 -0
- any2llm/secrets.py +19 -0
- any2llm/terminal.py +228 -0
- any2llm/tokenizer.py +21 -0
- any2llm/tools.py +32 -0
- any2llm-0.2.0.dist-info/METADATA +49 -0
- any2llm-0.2.0.dist-info/RECORD +46 -0
- any2llm-0.2.0.dist-info/WHEEL +5 -0
- any2llm-0.2.0.dist-info/entry_points.txt +2 -0
- any2llm-0.2.0.dist-info/licenses/LICENSE +21 -0
- any2llm-0.2.0.dist-info/top_level.txt +1 -0
any2llm/__init__.py
ADDED
|
File without changes
|
any2llm/__main__.py
ADDED
any2llm/cleaner.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Normalize prose and remove repeated PDF page margins."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from collections import Counter
|
|
5
|
+
|
|
6
|
+
_PAGE_NUMBER = re.compile(r"page\s+\d+(?:\s*(?:of|/)\s*\d+)?", re.IGNORECASE)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def clean_text(text: str) -> str:
|
|
10
|
+
"""Trim trailing whitespace and collapse blank lines, preserving indentation."""
|
|
11
|
+
lines = [line.rstrip() for line in text.splitlines()]
|
|
12
|
+
return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip("\n")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def clean_pages(pages: list[str]) -> list[str]:
|
|
16
|
+
"""Clean PDF margins while retaining a slot for every physical page."""
|
|
17
|
+
bodies = []
|
|
18
|
+
for number, page in enumerate(pages, 1):
|
|
19
|
+
lines = clean_text(page).splitlines()
|
|
20
|
+
for edge in (-1, 0):
|
|
21
|
+
if lines:
|
|
22
|
+
margin = lines[edge].strip()
|
|
23
|
+
if margin == str(number) or _PAGE_NUMBER.fullmatch(margin):
|
|
24
|
+
lines.pop(edge)
|
|
25
|
+
lines = "\n".join(lines).strip("\n").splitlines()
|
|
26
|
+
bodies.append(lines)
|
|
27
|
+
|
|
28
|
+
headers = Counter(lines[0] for lines in bodies if len(lines) > 1)
|
|
29
|
+
footers = Counter(lines[-1] for lines in bodies if len(lines) > 1)
|
|
30
|
+
threshold = max(2, sum(bool(lines) for lines in bodies) // 2 + 1)
|
|
31
|
+
cleaned = []
|
|
32
|
+
for lines in bodies:
|
|
33
|
+
if len(lines) > 1 and headers[lines[0]] >= threshold:
|
|
34
|
+
lines = lines[1:]
|
|
35
|
+
if len(lines) > 1 and footers[lines[-1]] >= threshold:
|
|
36
|
+
lines = lines[:-1]
|
|
37
|
+
cleaned.append(clean_text("\n".join(lines)))
|
|
38
|
+
return cleaned
|
any2llm/cli.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"""Select files and write a pack with one master prompt."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import io
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from collections import Counter
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from dataclasses import replace
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from tempfile import TemporaryDirectory, mkdtemp
|
|
13
|
+
|
|
14
|
+
from . import demo, ocr, tokenizer
|
|
15
|
+
from .clipboard import copy_prompt
|
|
16
|
+
from .config import Settings, load_config, save_config, setup
|
|
17
|
+
from .languages import LANGUAGE_NAMES, system_language
|
|
18
|
+
from .messages import MESSAGES, help_text
|
|
19
|
+
from .output import OutputBusy, OutputConflict, write_pack
|
|
20
|
+
from .packer import PRESETS, build_batches
|
|
21
|
+
from .parse_worker import parse_selected
|
|
22
|
+
from .parsers import SkippedFile
|
|
23
|
+
from .prompts import master_prompt
|
|
24
|
+
from .scanner import scan_folder
|
|
25
|
+
from .secrets import finding_types
|
|
26
|
+
from .terminal import Terminal, display_count, display_page_ranges, display_path, display_size, select_files
|
|
27
|
+
|
|
28
|
+
# Older --ui-lang values remain accepted for command-line compatibility.
|
|
29
|
+
_LEGACY_LANGUAGES = (*LANGUAGE_NAMES, "id")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ArgumentError(ValueError):
|
|
33
|
+
def __init__(self, key: str, option: str = ""):
|
|
34
|
+
self.key = key
|
|
35
|
+
self.option = option
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _arguments(argv: list[str]) -> argparse.Namespace:
|
|
39
|
+
parser = argparse.ArgumentParser(
|
|
40
|
+
prog="any2llm", add_help=False, allow_abbrev=False, exit_on_error=False,
|
|
41
|
+
)
|
|
42
|
+
parser.add_argument("folder", nargs="?", default=".")
|
|
43
|
+
parser.add_argument("-r", "--recursive", action="store_true")
|
|
44
|
+
parser.add_argument("--max-tokens", type=int)
|
|
45
|
+
parser.add_argument("--lang", choices=LANGUAGE_NAMES)
|
|
46
|
+
parser.add_argument("--task", default="")
|
|
47
|
+
parser.add_argument("--ocr", action="store_true")
|
|
48
|
+
parser.add_argument("--ocr-lang", metavar="LANG")
|
|
49
|
+
parser.add_argument("--config", action="store_true")
|
|
50
|
+
parser.add_argument("--no-open", action="store_true")
|
|
51
|
+
parser.add_argument("--plain", action="store_true")
|
|
52
|
+
parser.add_argument("--details", action="store_true")
|
|
53
|
+
parser.add_argument("--include-sensitive", action="store_true")
|
|
54
|
+
parser.add_argument("--exclude", action="append", default=[], metavar="GLOB")
|
|
55
|
+
parser.add_argument("-o", "--output", type=Path)
|
|
56
|
+
parser.add_argument("-y", "--yes", action="store_true")
|
|
57
|
+
parser.add_argument("--ui-lang", choices=_LEGACY_LANGUAGES)
|
|
58
|
+
parser.add_argument("-h", "--help", action="store_true")
|
|
59
|
+
try:
|
|
60
|
+
args, unknown = parser.parse_known_args(argv)
|
|
61
|
+
except argparse.ArgumentError as exc:
|
|
62
|
+
key = "invalid_limit" if exc.argument_name == "--max-tokens" else "invalid_option"
|
|
63
|
+
raise ArgumentError(key, exc.argument_name or "") from exc
|
|
64
|
+
if unknown:
|
|
65
|
+
raise ArgumentError("unknown_option", unknown[0])
|
|
66
|
+
if args.max_tokens is not None and args.max_tokens < 1:
|
|
67
|
+
raise ArgumentError("invalid_limit")
|
|
68
|
+
return args
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _error_language(argv: list[str], default: str) -> str:
|
|
72
|
+
# Parse only the language flags to report errors in the requested language.
|
|
73
|
+
parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False, exit_on_error=False)
|
|
74
|
+
parser.add_argument("--lang", nargs="?")
|
|
75
|
+
parser.add_argument("--ui-lang", nargs="?")
|
|
76
|
+
args, _ = parser.parse_known_args(argv)
|
|
77
|
+
if args.lang in LANGUAGE_NAMES:
|
|
78
|
+
return args.lang
|
|
79
|
+
return args.ui_lang if args.ui_lang in LANGUAGE_NAMES else default
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _interactive() -> bool:
|
|
83
|
+
return sys.stdin.isatty() and sys.stdout.isatty()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _configure_output() -> None:
|
|
87
|
+
"""Configure process streams for the installed CLI and module entry points."""
|
|
88
|
+
for stream in (sys.stdout, sys.stderr):
|
|
89
|
+
if isinstance(stream, io.TextIOWrapper):
|
|
90
|
+
if stream.isatty():
|
|
91
|
+
stream.reconfigure(errors="backslashreplace")
|
|
92
|
+
else:
|
|
93
|
+
# Files and pipelines carry UTF-8 on all supported systems.
|
|
94
|
+
stream.reconfigure(encoding="utf-8", errors="backslashreplace")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def main(argv: list[str] | None = None) -> int:
|
|
98
|
+
if argv is None:
|
|
99
|
+
_configure_output()
|
|
100
|
+
argv = sys.argv[1:]
|
|
101
|
+
try:
|
|
102
|
+
saved = load_config()
|
|
103
|
+
invalid_config = False
|
|
104
|
+
except (OSError, ValueError, RuntimeError):
|
|
105
|
+
saved = None
|
|
106
|
+
invalid_config = True
|
|
107
|
+
detected_language = system_language()
|
|
108
|
+
defaults = saved or Settings(lang=detected_language)
|
|
109
|
+
try:
|
|
110
|
+
args = _arguments(argv)
|
|
111
|
+
except ArgumentError as exc:
|
|
112
|
+
msg = MESSAGES[_error_language(argv, defaults.lang)]
|
|
113
|
+
print(msg[exc.key].format(option=display_path(exc.option)), "any2llm --help", file=sys.stderr)
|
|
114
|
+
return 2
|
|
115
|
+
|
|
116
|
+
override = args.lang or (args.ui_lang if args.ui_lang in LANGUAGE_NAMES else None)
|
|
117
|
+
msg = MESSAGES[override or defaults.lang]
|
|
118
|
+
if args.help:
|
|
119
|
+
print(help_text(override or defaults.lang))
|
|
120
|
+
return 0
|
|
121
|
+
configure = args.config or args.folder == "setup"
|
|
122
|
+
run_demo = args.folder == "demo" and not configure
|
|
123
|
+
if invalid_config and not configure:
|
|
124
|
+
print(msg["config_error"], file=sys.stderr)
|
|
125
|
+
return 1
|
|
126
|
+
|
|
127
|
+
interactive = _interactive()
|
|
128
|
+
if not interactive and (configure or not (args.yes or run_demo)):
|
|
129
|
+
print(msg["no_setup_terminal" if configure else "no_terminal"], file=sys.stderr)
|
|
130
|
+
return 2
|
|
131
|
+
plain = args.plain or os.environ.get("TERM") == "dumb"
|
|
132
|
+
screen = Terminal(plain=plain)
|
|
133
|
+
try:
|
|
134
|
+
if interactive:
|
|
135
|
+
screen.logo()
|
|
136
|
+
if run_demo:
|
|
137
|
+
return _run_demo(args, defaults, override or defaults.lang, screen, plain=plain)
|
|
138
|
+
if configure or (saved is None and interactive):
|
|
139
|
+
saved = setup(defaults, menu_language=detected_language, plain=plain)
|
|
140
|
+
if saved is None:
|
|
141
|
+
return 130
|
|
142
|
+
msg = MESSAGES[saved.lang]
|
|
143
|
+
try:
|
|
144
|
+
save_config(saved)
|
|
145
|
+
except (OSError, RuntimeError):
|
|
146
|
+
print(msg["save_error"], file=sys.stderr)
|
|
147
|
+
print(msg["save_fix"], file=sys.stderr)
|
|
148
|
+
return 1
|
|
149
|
+
screen.section(msg["saved"], "bold green", icon="✓")
|
|
150
|
+
screen.line(msg["setup_again"])
|
|
151
|
+
if configure:
|
|
152
|
+
return 0
|
|
153
|
+
settings = saved or defaults
|
|
154
|
+
lang = override or settings.lang
|
|
155
|
+
msg = MESSAGES[lang]
|
|
156
|
+
return _pack(args, settings, lang, screen, plain=plain)
|
|
157
|
+
except KeyboardInterrupt:
|
|
158
|
+
print(msg["cancelled"], file=sys.stderr)
|
|
159
|
+
return 130
|
|
160
|
+
except EOFError as exc:
|
|
161
|
+
language = exc.args[0] if exc.args and exc.args[0] in LANGUAGE_NAMES else None
|
|
162
|
+
print((MESSAGES[language] if language else msg)["input_closed"], file=sys.stderr)
|
|
163
|
+
return 2
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _run_demo(args: argparse.Namespace, settings: Settings, lang: str, screen: Terminal, *, plain: bool) -> int:
|
|
167
|
+
source_lang = "tr" if lang == "tr" else "en"
|
|
168
|
+
msg = MESSAGES[lang]
|
|
169
|
+
try:
|
|
170
|
+
with TemporaryDirectory(prefix="any2llm-sources-") as source:
|
|
171
|
+
demo.copy_sources(source_lang, Path(source))
|
|
172
|
+
args.folder = source
|
|
173
|
+
args.yes = True
|
|
174
|
+
args.task = args.task or demo.QUESTIONS[source_lang]
|
|
175
|
+
working_dir = Path.cwd()
|
|
176
|
+
if args.output is None:
|
|
177
|
+
try:
|
|
178
|
+
args.output = Path(mkdtemp(prefix=f"any2llm-demo-{source_lang}-", dir=working_dir))
|
|
179
|
+
except OSError:
|
|
180
|
+
print(f'{msg["write_error"]}: {display_path(working_dir)}', file=sys.stderr)
|
|
181
|
+
print(msg["write_fix"], file=sys.stderr)
|
|
182
|
+
return 1
|
|
183
|
+
else:
|
|
184
|
+
args.output = working_dir / args.output
|
|
185
|
+
return _pack(args, replace(settings, preset="Single File"), lang, screen, plain=plain)
|
|
186
|
+
except OSError:
|
|
187
|
+
print(msg["demo_error"], file=sys.stderr)
|
|
188
|
+
return 1
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _pack(args: argparse.Namespace, settings: Settings, lang: str, screen: Terminal, *, plain: bool) -> int:
|
|
192
|
+
msg = MESSAGES[lang]
|
|
193
|
+
folder = Path(args.folder).absolute()
|
|
194
|
+
output_dir = folder / (args.output or "_llm_pack")
|
|
195
|
+
screen.section(f'{msg["scanning"]}…', "bold cyan", icon="⌕")
|
|
196
|
+
screen.line(f'{msg["folder"]}: {display_path(folder)}', flush=True)
|
|
197
|
+
examined = 0
|
|
198
|
+
|
|
199
|
+
def on_file() -> None:
|
|
200
|
+
nonlocal examined
|
|
201
|
+
examined += 1
|
|
202
|
+
if examined % 25 == 0:
|
|
203
|
+
screen.line(f'{msg["progress"]}: {display_count(examined, msg)}', flush=True)
|
|
204
|
+
|
|
205
|
+
try:
|
|
206
|
+
root = Path(os.path.realpath(folder))
|
|
207
|
+
result = scan_folder(
|
|
208
|
+
root, args.recursive, output_dir=output_dir,
|
|
209
|
+
on_file=on_file if screen.is_terminal else None,
|
|
210
|
+
include_sensitive=args.include_sensitive, exclude=args.exclude,
|
|
211
|
+
)
|
|
212
|
+
except OSError as exc:
|
|
213
|
+
key = {
|
|
214
|
+
FileNotFoundError: "no_folder", NotADirectoryError: "not_folder",
|
|
215
|
+
}.get(type(exc), "read_folder")
|
|
216
|
+
print(f'{msg[key]}: {display_path(folder)}', file=sys.stderr)
|
|
217
|
+
return 1
|
|
218
|
+
if result.skipped:
|
|
219
|
+
_report_skipped(result.skipped, msg, screen, details=args.details)
|
|
220
|
+
if not result.candidates:
|
|
221
|
+
screen.section(msg["empty"])
|
|
222
|
+
if not args.recursive and result.has_subfolders:
|
|
223
|
+
print(msg["nested"])
|
|
224
|
+
return 0
|
|
225
|
+
|
|
226
|
+
selected = result.candidates if args.yes else select_files(result.candidates, msg, plain=plain)
|
|
227
|
+
if not selected:
|
|
228
|
+
screen.section(msg["none_selected"])
|
|
229
|
+
return 0
|
|
230
|
+
ocr_lang = args.ocr_lang or ("eng" if args.ocr else None)
|
|
231
|
+
if ocr_lang is not None and (error := ocr.setup_error(ocr_lang)):
|
|
232
|
+
print(msg[error].format(lang=display_path(ocr_lang)), file=sys.stderr)
|
|
233
|
+
ocr_lang = None
|
|
234
|
+
screen.section(msg["packing"], "bold bright_blue", icon="▤", flush=True)
|
|
235
|
+
documents_to_pack = {}
|
|
236
|
+
parse_skips = {}
|
|
237
|
+
for path in selected:
|
|
238
|
+
parsed = parse_selected(root / path, ocr_lang=ocr_lang)
|
|
239
|
+
if isinstance(parsed, SkippedFile):
|
|
240
|
+
parse_skips[path] = parsed.reason
|
|
241
|
+
elif not parsed.text.strip():
|
|
242
|
+
parse_skips[path] = "empty_file"
|
|
243
|
+
else:
|
|
244
|
+
documents_to_pack[path] = parsed
|
|
245
|
+
if parse_skips:
|
|
246
|
+
_report_skipped(parse_skips, msg, screen, details=args.details)
|
|
247
|
+
if not documents_to_pack:
|
|
248
|
+
screen.section(msg["empty"])
|
|
249
|
+
return 0
|
|
250
|
+
try:
|
|
251
|
+
documents = build_batches(
|
|
252
|
+
documents_to_pack, preset=settings.preset, max_tokens=args.max_tokens,
|
|
253
|
+
)
|
|
254
|
+
except ValueError:
|
|
255
|
+
print(msg["limit_error"], file=sys.stderr)
|
|
256
|
+
return 1
|
|
257
|
+
has_ocr = any(page.ocr for document in documents_to_pack.values() for page in document.pages)
|
|
258
|
+
prompt = master_prompt(list(documents), lang, args.task, has_ocr=has_ocr)
|
|
259
|
+
try:
|
|
260
|
+
write_pack(output_dir, {**documents, "PROMPT.txt": prompt})
|
|
261
|
+
except OSError as exc:
|
|
262
|
+
key = "write_error"
|
|
263
|
+
if isinstance(exc, OutputBusy):
|
|
264
|
+
key = "busy"
|
|
265
|
+
elif isinstance(exc, OutputConflict):
|
|
266
|
+
key = "collision"
|
|
267
|
+
problem_path = exc.filename if key == "collision" else output_dir
|
|
268
|
+
print(f'{msg[key]}: {display_path(problem_path)}', file=sys.stderr)
|
|
269
|
+
print(msg["busy_fix" if key == "busy" else "write_fix"], file=sys.stderr)
|
|
270
|
+
return 1
|
|
271
|
+
findings = [(path.name, kind) for path, doc in documents_to_pack.items() for kind in finding_types(doc.text)]
|
|
272
|
+
if findings:
|
|
273
|
+
screen.section(msg["sensitive_content"], "bold yellow", icon="▲")
|
|
274
|
+
for name, kind in findings:
|
|
275
|
+
screen.line(f" {display_path(name)} — {msg[kind]}")
|
|
276
|
+
screen.line(msg["sensitive_review"], "bold yellow")
|
|
277
|
+
for path, document in documents_to_pack.items():
|
|
278
|
+
missing = [page.number for page in document.pages if page.no_text]
|
|
279
|
+
partial = [page.number for page in document.pages if page.partial and not page.no_text]
|
|
280
|
+
for key, pages in (("no_page_text", missing), ("partial", partial)):
|
|
281
|
+
if pages:
|
|
282
|
+
screen.line(msg[key].format(path=display_path(path), pages=display_page_ranges(pages, msg)),
|
|
283
|
+
"bold yellow", filenames=(display_path(path),))
|
|
284
|
+
recognized = [page.number for page in document.pages if page.ocr]
|
|
285
|
+
if recognized:
|
|
286
|
+
note = msg["ocr_pages"].format(pages=display_page_ranges(recognized, msg))
|
|
287
|
+
print(f" {display_path(path)} — {note}")
|
|
288
|
+
copied = copy_prompt(prompt)
|
|
289
|
+
limited = args.max_tokens is not None or PRESETS[settings.preset] is not None
|
|
290
|
+
_handoff(msg, output_dir, len(documents_to_pack), documents, copied, screen, limited=limited)
|
|
291
|
+
if settings.auto_open and not args.no_open and _interactive():
|
|
292
|
+
_open_folder(output_dir)
|
|
293
|
+
return 0
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _report_skipped(
|
|
297
|
+
skipped: Mapping[Path, str], msg: dict[str, str], screen: Terminal, *, details: bool,
|
|
298
|
+
) -> None:
|
|
299
|
+
reasons = sorted(Counter(skipped.values()).items())
|
|
300
|
+
summary = ", ".join(f"{display_count(count, msg)} × {msg[reason]}" for reason, count in reasons)
|
|
301
|
+
screen.section(f'{msg["skipped"]} ({display_count(len(skipped), msg)})', "bold yellow", icon="▲")
|
|
302
|
+
screen.line(f" {summary}")
|
|
303
|
+
for number, (path, reason) in enumerate(skipped.items(), 1):
|
|
304
|
+
if number > 8 and not details:
|
|
305
|
+
screen.line(msg["more_skipped"].format(count=display_count(len(skipped) - 8, msg)))
|
|
306
|
+
break
|
|
307
|
+
screen.line(f" {display_path(path)} — {msg[reason]}")
|
|
308
|
+
|
|
309
|
+
guidance: dict[str, list[str]] = {}
|
|
310
|
+
for reason, _ in reasons:
|
|
311
|
+
action = "media_help" if reason in {"image", "audio", "video"} else f"{reason}_help"
|
|
312
|
+
guidance.setdefault(action, []).append(msg[reason])
|
|
313
|
+
screen.section(msg["skipped_help"], "bold yellow", icon="▲")
|
|
314
|
+
for action, labels in guidance.items():
|
|
315
|
+
screen.line(f" {', '.join(labels)} — {msg[action]}", "bold yellow")
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _handoff(
|
|
319
|
+
msg: dict[str, str], folder: Path, selected: int, documents: Mapping[str, str],
|
|
320
|
+
copied: bool, screen: Terminal, *, limited: bool,
|
|
321
|
+
) -> None:
|
|
322
|
+
batches = list(documents)
|
|
323
|
+
count = len(batches)
|
|
324
|
+
# Match write_pack's UTF-8 encoding and include only the prepared attachments.
|
|
325
|
+
size = sum(len(document.encode("utf-8")) for document in documents.values())
|
|
326
|
+
token_method = "tokens_unlimited"
|
|
327
|
+
if limited:
|
|
328
|
+
token_method = "tokens_estimated" if tokenizer.get_encoding() is None else "tokens_cl100k"
|
|
329
|
+
summary = msg["ready"].format(
|
|
330
|
+
selected=display_count(selected, msg), batches=display_count(count, msg),
|
|
331
|
+
size=display_size(size, msg), tokens=msg[token_method],
|
|
332
|
+
)
|
|
333
|
+
screen.section(summary, "bold green", icon="✓")
|
|
334
|
+
screen.line(f'{msg["folder"]}: {display_path(folder.resolve())}')
|
|
335
|
+
if copied:
|
|
336
|
+
screen.section(msg["clipboard_copied"], "bold bright_green", icon="✓")
|
|
337
|
+
else:
|
|
338
|
+
screen.section(msg["clipboard_failed"], "bold yellow", icon="▲")
|
|
339
|
+
screen.section(msg["open_chat"], "bold bright_magenta", icon="↗")
|
|
340
|
+
if count == 1:
|
|
341
|
+
print(msg["attach_one"].format(name=batches[0]))
|
|
342
|
+
else:
|
|
343
|
+
first, last = batches[0], batches[-1]
|
|
344
|
+
screen.line(msg["attach_many"].format(first=first, last=last), "bright_white", filenames=(first, last))
|
|
345
|
+
print(msg["paste" if copied else "clipboard"])
|
|
346
|
+
if count > 1:
|
|
347
|
+
print(msg["next"])
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _open_folder(path: Path) -> None:
|
|
351
|
+
try:
|
|
352
|
+
if sys.platform == "win32":
|
|
353
|
+
os.startfile(path.resolve())
|
|
354
|
+
else:
|
|
355
|
+
command = "open" if sys.platform == "darwin" else "xdg-open"
|
|
356
|
+
subprocess.Popen(
|
|
357
|
+
[command, str(path.resolve())], stdin=subprocess.DEVNULL,
|
|
358
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True,
|
|
359
|
+
)
|
|
360
|
+
except (OSError, NotImplementedError):
|
|
361
|
+
pass
|
any2llm/clipboard.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Copy the prompt without exposing platform clipboard diagnostics."""
|
|
2
|
+
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def copy_prompt(prompt: str) -> bool:
|
|
8
|
+
# Some native backends print errors directly to stderr or wait for a display.
|
|
9
|
+
try:
|
|
10
|
+
result = subprocess.run(
|
|
11
|
+
[sys.executable, "-I", "-m", "any2llm.clipboard"], input=prompt.encode("utf-8"),
|
|
12
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5,
|
|
13
|
+
)
|
|
14
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
15
|
+
return False
|
|
16
|
+
return result.returncode == 0
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _copy_and_verify(prompt: str) -> bool:
|
|
20
|
+
import pyperclip
|
|
21
|
+
|
|
22
|
+
pyperclip.copy(prompt)
|
|
23
|
+
# Several pyperclip backends discard the native tool's exit status.
|
|
24
|
+
return pyperclip.paste() == prompt
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
if __name__ == "__main__":
|
|
28
|
+
sys.exit(0 if _copy_and_verify(sys.stdin.buffer.read().decode("utf-8")) else 1)
|
any2llm/config.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Persistent preferences and first-run setup."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
from dataclasses import asdict, dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from tempfile import TemporaryDirectory
|
|
8
|
+
|
|
9
|
+
import questionary
|
|
10
|
+
|
|
11
|
+
from .languages import LANGUAGE_NAMES
|
|
12
|
+
from .messages import MESSAGES
|
|
13
|
+
from .packer import PRESETS
|
|
14
|
+
from .terminal import Terminal, select
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Settings:
|
|
19
|
+
lang: str = "en"
|
|
20
|
+
preset: str = "Balanced"
|
|
21
|
+
auto_open: bool = True
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def config_path() -> Path:
|
|
25
|
+
return Path.home() / ".config" / "any2llm" / "config.json"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def load_config() -> Settings | None:
|
|
29
|
+
try:
|
|
30
|
+
data = json.loads(config_path().read_text(encoding="utf-8"))
|
|
31
|
+
except FileNotFoundError:
|
|
32
|
+
return None
|
|
33
|
+
if not isinstance(data, dict):
|
|
34
|
+
raise ValueError("Invalid configuration")
|
|
35
|
+
lang, preset, auto_open = (data.get(key) for key in ("lang", "preset", "auto_open"))
|
|
36
|
+
if not isinstance(lang, str) or lang not in LANGUAGE_NAMES:
|
|
37
|
+
raise ValueError("Invalid configuration language")
|
|
38
|
+
if preset not in tuple(PRESETS) or not isinstance(auto_open, bool):
|
|
39
|
+
raise ValueError("Invalid configuration")
|
|
40
|
+
return Settings(lang, preset, auto_open)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def save_config(settings: Settings) -> None:
|
|
44
|
+
path = config_path()
|
|
45
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
with TemporaryDirectory(dir=path.parent) as staging:
|
|
47
|
+
temporary = Path(staging) / path.name
|
|
48
|
+
temporary.write_text(json.dumps(asdict(settings), indent=2) + "\n", encoding="utf-8")
|
|
49
|
+
temporary.replace(path)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def setup(initial: Settings, *, menu_language: str, plain: bool = False) -> Settings | None:
|
|
53
|
+
lang = menu_language
|
|
54
|
+
msg = MESSAGES[lang]
|
|
55
|
+
screen = Terminal(plain=plain)
|
|
56
|
+
try:
|
|
57
|
+
print()
|
|
58
|
+
screen.line(msg["welcome"])
|
|
59
|
+
print()
|
|
60
|
+
screen.controls(msg["plain_keys" if plain else "arrows"])
|
|
61
|
+
print()
|
|
62
|
+
lang = select(
|
|
63
|
+
f'1/3 {msg["language"]}',
|
|
64
|
+
[questionary.Choice(name, code) for code, name in LANGUAGE_NAMES.items()],
|
|
65
|
+
initial.lang, msg["invalid_choice"], plain=plain, accent="brightcyan",
|
|
66
|
+
)
|
|
67
|
+
return _preferences(lang, initial, screen, plain=plain)
|
|
68
|
+
except KeyboardInterrupt:
|
|
69
|
+
print(MESSAGES[lang]["cancelled"], file=sys.stderr)
|
|
70
|
+
return None
|
|
71
|
+
except EOFError:
|
|
72
|
+
raise EOFError(lang) from None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _preferences(lang: str, initial: Settings, screen: Terminal, *, plain: bool) -> Settings:
|
|
76
|
+
msg = MESSAGES[lang]
|
|
77
|
+
screen.section(msg["hint"])
|
|
78
|
+
preset = select(
|
|
79
|
+
f'2/3 {msg["detail"]}', [questionary.Choice(msg[key], key) for key in PRESETS],
|
|
80
|
+
initial.preset, msg["invalid_choice"], plain=plain, accent="brightmagenta",
|
|
81
|
+
)
|
|
82
|
+
print()
|
|
83
|
+
auto_open = select(
|
|
84
|
+
f'3/3 {msg["open"]}', [questionary.Choice(msg["yes"], True), questionary.Choice(msg["no"], False)],
|
|
85
|
+
initial.auto_open, msg["invalid_choice"], plain=plain, accent="brightblue",
|
|
86
|
+
)
|
|
87
|
+
return Settings(lang, preset, auto_open)
|
any2llm/demo.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Source documents and questions for the bundled midterm demo."""
|
|
2
|
+
|
|
3
|
+
from importlib.resources import files
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
QUESTIONS = {
|
|
7
|
+
"en": "Which research design fits the measurement plan? Cite the Excel sheet for what was measured in each class "
|
|
8
|
+
"and the original PDF page for the design definition.",
|
|
9
|
+
"tr": "Ölçüm planı hangi araştırma desenine uyuyor? Her sınıfta neyin ölçüldüğünü Excel sayfasına, "
|
|
10
|
+
"desenin tanımını da orijinal PDF’in sayfasına atıf yaparak açıkla.",
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def copy_sources(lang: str, destination: Path) -> None:
|
|
15
|
+
source = files(__package__).joinpath("demo_assets", lang)
|
|
16
|
+
for resource in source.iterdir():
|
|
17
|
+
if resource.is_file():
|
|
18
|
+
(destination / resource.name).write_bytes(resource.read_bytes())
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
any2llm/ignore.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Match scan exclusions and simple root .gitignore rules."""
|
|
2
|
+
|
|
3
|
+
import stat
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from fnmatch import fnmatchcase
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class PathPattern:
|
|
11
|
+
parts: tuple[str, ...]
|
|
12
|
+
match_basename: bool
|
|
13
|
+
directories_only: bool
|
|
14
|
+
|
|
15
|
+
@classmethod
|
|
16
|
+
def parse(cls, pattern: str) -> "PathPattern":
|
|
17
|
+
parts = tuple(pattern.strip("/").split("/"))
|
|
18
|
+
return cls(parts, len(parts) == 1 and not pattern.startswith("/"), pattern.endswith("/"))
|
|
19
|
+
|
|
20
|
+
def matches(self, path: Path, *, is_dir: bool) -> bool:
|
|
21
|
+
if self.directories_only and not is_dir:
|
|
22
|
+
return False
|
|
23
|
+
if self.match_basename:
|
|
24
|
+
return fnmatchcase(path.name, self.parts[0])
|
|
25
|
+
|
|
26
|
+
parts = path.parts
|
|
27
|
+
positions: set[int] | range = {0}
|
|
28
|
+
for index, pattern in enumerate(self.parts):
|
|
29
|
+
if pattern == "**":
|
|
30
|
+
# A trailing /** matches entries inside a directory.
|
|
31
|
+
start = min(positions)
|
|
32
|
+
if index == len(self.parts) - 1:
|
|
33
|
+
start += 1
|
|
34
|
+
positions = range(start, len(parts) + 1)
|
|
35
|
+
else:
|
|
36
|
+
positions = {i + 1 for i in positions if i < len(parts) and fnmatchcase(parts[i], pattern)}
|
|
37
|
+
if not positions:
|
|
38
|
+
return False
|
|
39
|
+
return len(parts) in positions
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class IgnoreRule:
|
|
44
|
+
pattern: PathPattern
|
|
45
|
+
ignored: bool
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def read_gitignore(path: Path) -> list[IgnoreRule]:
|
|
49
|
+
try:
|
|
50
|
+
mode = path.lstat().st_mode
|
|
51
|
+
except FileNotFoundError:
|
|
52
|
+
return []
|
|
53
|
+
if not stat.S_ISREG(mode):
|
|
54
|
+
return []
|
|
55
|
+
|
|
56
|
+
rules = []
|
|
57
|
+
for line in path.read_text(encoding="utf-8-sig", errors="surrogateescape").split("\n"):
|
|
58
|
+
line = line.rstrip(" ")
|
|
59
|
+
if not line or line.startswith("#"):
|
|
60
|
+
continue
|
|
61
|
+
ignored = not line.startswith("!")
|
|
62
|
+
if not ignored or line.startswith(("\\!", "\\#")):
|
|
63
|
+
line = line[1:]
|
|
64
|
+
if line:
|
|
65
|
+
rules.append(IgnoreRule(PathPattern.parse(line), ignored))
|
|
66
|
+
return rules
|
any2llm/languages.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Supported languages and the terminal's preferred locale."""
|
|
2
|
+
|
|
3
|
+
import locale
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
LANGUAGE_NAMES = {
|
|
9
|
+
"en": "English",
|
|
10
|
+
"zh": "简体中文",
|
|
11
|
+
"hi": "हिन्दी",
|
|
12
|
+
"es": "Español",
|
|
13
|
+
"fr": "Français",
|
|
14
|
+
"ar": "العربية",
|
|
15
|
+
"bn": "বাংলা",
|
|
16
|
+
"pt": "Português",
|
|
17
|
+
"ru": "Русский",
|
|
18
|
+
"ur": "اردو",
|
|
19
|
+
"tr": "Türkçe",
|
|
20
|
+
}
|
|
21
|
+
_WINDOWS_NAMES = {
|
|
22
|
+
"english": "en", "chinese": "zh", "hindi": "hi", "spanish": "es",
|
|
23
|
+
"french": "fr", "arabic": "ar", "bengali": "bn", "bangla": "bn",
|
|
24
|
+
"portuguese": "pt", "russian": "ru", "urdu": "ur", "turkish": "tr",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _native_message_locale() -> str | None:
|
|
29
|
+
if sys.platform == "win32":
|
|
30
|
+
# The Windows display language can differ from regional number formats.
|
|
31
|
+
import ctypes
|
|
32
|
+
|
|
33
|
+
language_id = ctypes.windll.kernel32.GetUserDefaultUILanguage()
|
|
34
|
+
return locale.windows_locale.get(language_id)
|
|
35
|
+
try:
|
|
36
|
+
return locale.getlocale()[0]
|
|
37
|
+
except ValueError:
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def system_language() -> str:
|
|
42
|
+
"""Use the message locale, with English as the fallback."""
|
|
43
|
+
name = os.environ.get("LC_ALL") or os.environ.get("LC_MESSAGES") or os.environ.get("LANG")
|
|
44
|
+
if not name:
|
|
45
|
+
name = _native_message_locale()
|
|
46
|
+
language = re.split(r"[-_.@ (]", (name or "").strip().lower(), maxsplit=1)[0]
|
|
47
|
+
if language == "cmn":
|
|
48
|
+
return "zh"
|
|
49
|
+
return language if language in LANGUAGE_NAMES else _WINDOWS_NAMES.get(language, "en")
|