docpilot-cli 1.0.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.
- docpilot/__init__.py +0 -0
- docpilot/chat.py +66 -0
- docpilot/cli.py +313 -0
- docpilot/embed.py +172 -0
- docpilot/scrape.py +234 -0
- docpilot/store.py +113 -0
- docpilot_cli-1.0.0.dist-info/METADATA +160 -0
- docpilot_cli-1.0.0.dist-info/RECORD +12 -0
- docpilot_cli-1.0.0.dist-info/WHEEL +5 -0
- docpilot_cli-1.0.0.dist-info/entry_points.txt +2 -0
- docpilot_cli-1.0.0.dist-info/licenses/LICENSE +21 -0
- docpilot_cli-1.0.0.dist-info/top_level.txt +1 -0
docpilot/__init__.py
ADDED
|
File without changes
|
docpilot/chat.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from langchain_ollama.llms import OllamaLLM as Ollama
|
|
2
|
+
from langchain_core.prompts import ChatPromptTemplate
|
|
3
|
+
from .embed import vectorstore
|
|
4
|
+
import os
|
|
5
|
+
from . import store
|
|
6
|
+
|
|
7
|
+
config = store.load_config()
|
|
8
|
+
retrieval_k = int(config.get("retrieval_k", 6))
|
|
9
|
+
max_context_chars = int(config.get("max_context_chars", 3500))
|
|
10
|
+
max_doc_chars = int(config.get("max_doc_chars", 700))
|
|
11
|
+
|
|
12
|
+
model = Ollama(
|
|
13
|
+
model=config.get("default_model", "deepseek-coder-v2"),
|
|
14
|
+
num_predict=int(config.get("num_predict", 192)),
|
|
15
|
+
num_ctx=int(config.get("num_ctx", 2048)),
|
|
16
|
+
num_thread=int(config.get("num_thread", max(1, (os.cpu_count() or 4) - 1))),
|
|
17
|
+
temperature=float(config.get("temperature", 0.1)),
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
retriever = vectorstore.as_retriever(search_kwargs={"k": retrieval_k})
|
|
21
|
+
template = """
|
|
22
|
+
You are an assistant for answering questions based on the following ingested documents.
|
|
23
|
+
Use the information in the documents to answer the question as best as you can.
|
|
24
|
+
If you don't know the answer, say you don't know.
|
|
25
|
+
Always use the information in the documents and never make up an answer.
|
|
26
|
+
Here are some relevant docs: {reviews}
|
|
27
|
+
Here is the question to answer: {question}
|
|
28
|
+
"""
|
|
29
|
+
prompt = ChatPromptTemplate.from_template(template)
|
|
30
|
+
|
|
31
|
+
chain = prompt | model
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _build_bounded_context(docs, max_total_chars: int = 6000, max_doc_chars: int = 1200) -> str:
|
|
35
|
+
lines = []
|
|
36
|
+
total = 0
|
|
37
|
+
for doc in docs:
|
|
38
|
+
doc_text = doc.page_content.strip()
|
|
39
|
+
if len(doc_text) > max_doc_chars:
|
|
40
|
+
doc_text = doc_text[:max_doc_chars].rsplit(" ", 1)[0].strip() or doc_text[:max_doc_chars]
|
|
41
|
+
line = f"[ID: {doc.id}] {doc_text}"
|
|
42
|
+
if total + len(line) > max_total_chars:
|
|
43
|
+
break
|
|
44
|
+
lines.append(line)
|
|
45
|
+
total += len(line)
|
|
46
|
+
return "\n".join(lines)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def askai(question):
|
|
50
|
+
rag = retriever.invoke(question)
|
|
51
|
+
rag_text = _build_bounded_context(
|
|
52
|
+
rag,
|
|
53
|
+
max_total_chars=max_context_chars,
|
|
54
|
+
max_doc_chars=max_doc_chars,
|
|
55
|
+
)
|
|
56
|
+
result = chain.invoke({"reviews": rag_text, "question": question})
|
|
57
|
+
return result
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
while True:
|
|
62
|
+
question = input("Ask a question (or type 'exit'): ")
|
|
63
|
+
if question.lower() == "exit":
|
|
64
|
+
break
|
|
65
|
+
result = askai(question)
|
|
66
|
+
print(result, "\n\n")
|
docpilot/cli.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import ollama
|
|
2
|
+
import typer
|
|
3
|
+
import importlib
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from .chat import askai
|
|
6
|
+
from .scrape import scrape_sitemap, scrape_site
|
|
7
|
+
from .embed import embed_texts
|
|
8
|
+
from . import store
|
|
9
|
+
from rich.console import Console
|
|
10
|
+
from rich.markdown import Markdown
|
|
11
|
+
from rich.panel import Panel
|
|
12
|
+
from rich.text import Text
|
|
13
|
+
from rich.align import Align
|
|
14
|
+
|
|
15
|
+
# Initialize config at startup
|
|
16
|
+
store.init_config()
|
|
17
|
+
|
|
18
|
+
# Rich console for beautiful output
|
|
19
|
+
console = Console()
|
|
20
|
+
|
|
21
|
+
app = typer.Typer()
|
|
22
|
+
|
|
23
|
+
# Project metadata
|
|
24
|
+
PROJECT_VERSION = "0.0.1"
|
|
25
|
+
PROJECT_NAME = "docpilot"
|
|
26
|
+
PROJECT_DESCRIPTION = "A local-first RAG pipeline CLI tool"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def loadpdf(file_path: Path) -> list[str]:
|
|
30
|
+
try:
|
|
31
|
+
PdfReader = importlib.import_module("pypdf").PdfReader
|
|
32
|
+
except Exception:
|
|
33
|
+
print("PDF support is unavailable. Install dependencies again to include pypdf.")
|
|
34
|
+
return []
|
|
35
|
+
reader = PdfReader(str(file_path))
|
|
36
|
+
texts: list[str] = []
|
|
37
|
+
for page in reader.pages:
|
|
38
|
+
page_text = (page.extract_text() or "").strip()
|
|
39
|
+
if page_text:
|
|
40
|
+
texts.append(page_text)
|
|
41
|
+
return texts
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def loadcsv(file_path: Path) -> list[str]:
|
|
45
|
+
import csv
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
with open(file_path, newline="", encoding="utf-8") as f:
|
|
49
|
+
sample = f.read(2048)
|
|
50
|
+
f.seek(0)
|
|
51
|
+
try:
|
|
52
|
+
dialect = csv.Sniffer().sniff(sample)
|
|
53
|
+
except csv.Error:
|
|
54
|
+
dialect = csv.excel
|
|
55
|
+
|
|
56
|
+
reader = csv.DictReader(f, dialect=dialect)
|
|
57
|
+
if not reader.fieldnames:
|
|
58
|
+
return []
|
|
59
|
+
|
|
60
|
+
texts: list[str] = []
|
|
61
|
+
for row in reader:
|
|
62
|
+
row_text = " | ".join(f"{col}: {val if val else ''}" for col, val in row.items() if col)
|
|
63
|
+
if row_text.strip():
|
|
64
|
+
texts.append(row_text)
|
|
65
|
+
return texts
|
|
66
|
+
except Exception as e:
|
|
67
|
+
print(f"Error reading CSV: {e}")
|
|
68
|
+
return []
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def generate_ascii_art() -> str:
|
|
72
|
+
"""Generate beautiful ASCII art for the project."""
|
|
73
|
+
try:
|
|
74
|
+
import pyfiglet
|
|
75
|
+
|
|
76
|
+
ascii_text = pyfiglet.figlet_format(PROJECT_NAME, font="banner")
|
|
77
|
+
except ImportError:
|
|
78
|
+
# Fallback to simple ASCII if pyfiglet not available
|
|
79
|
+
ascii_text = """
|
|
80
|
+
____ ____ _ _ _
|
|
81
|
+
/ __ \\___ _____/ __ \\(_) | | |
|
|
82
|
+
/ / / / _ \\/ ___/ /_/ / /| | | |
|
|
83
|
+
/ /_/ / __/ /__/ ____/ / | |___ |_|
|
|
84
|
+
/_____/\\___/\\___/_/ /_/ |_____/ (_)
|
|
85
|
+
"""
|
|
86
|
+
return ascii_text
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@app.command()
|
|
90
|
+
def show():
|
|
91
|
+
"""Display version and project information in beautiful ASCII art."""
|
|
92
|
+
ascii_art = generate_ascii_art()
|
|
93
|
+
print(ascii_art)
|
|
94
|
+
print("=" * 60)
|
|
95
|
+
print(f"Version: {PROJECT_VERSION}")
|
|
96
|
+
print(f"Description: {PROJECT_DESCRIPTION}")
|
|
97
|
+
print("=" * 60)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def parse_markdown(content: str) -> None:
|
|
101
|
+
"""Parse and render markdown content beautifully in the terminal."""
|
|
102
|
+
markdown = Markdown(content)
|
|
103
|
+
console.print(markdown)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@app.command()
|
|
107
|
+
def render(
|
|
108
|
+
source: str = typer.Argument(..., help="Path to markdown file or inline markdown text"),
|
|
109
|
+
is_file: bool = typer.Option(True, "--file/--text", "-f/-t", help="Is source a file or inline text?"),
|
|
110
|
+
):
|
|
111
|
+
"""Parse and beautifully render markdown content in the terminal."""
|
|
112
|
+
try:
|
|
113
|
+
if is_file:
|
|
114
|
+
source_path = Path(source).expanduser().resolve()
|
|
115
|
+
if not source_path.exists():
|
|
116
|
+
console.print(f"[red]Error: File not found: {source}[/red]")
|
|
117
|
+
return
|
|
118
|
+
if not source_path.is_file():
|
|
119
|
+
console.print(f"[red]Error: Not a file: {source}[/red]")
|
|
120
|
+
return
|
|
121
|
+
content = source_path.read_text()
|
|
122
|
+
else:
|
|
123
|
+
content = source
|
|
124
|
+
|
|
125
|
+
parse_markdown(content)
|
|
126
|
+
except Exception as e:
|
|
127
|
+
console.print(f"[red]Error parsing markdown: {e}[/red]")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@app.command()
|
|
131
|
+
def ingest(
|
|
132
|
+
source: str,
|
|
133
|
+
max_pages: int = typer.Option(20, "--max-pages", "-p", help="Max pages to crawl for websites."),
|
|
134
|
+
workers: int = typer.Option(16, "--workers", "-w", help="Concurrent workers for scraping."),
|
|
135
|
+
batch_size: int = typer.Option(32, "--batch-size", "-b", min=1, help="Embedding batch size for faster ingest."),
|
|
136
|
+
embed_workers: int = typer.Option(
|
|
137
|
+
0, "--embed-workers", "-e", min=0, help="Threads for chunking before embedding (0 = auto)."
|
|
138
|
+
),
|
|
139
|
+
):
|
|
140
|
+
"""Ingest a website, sitemap, PDF, or CSV by chunking and embedding content."""
|
|
141
|
+
store.check_ollama_connection()
|
|
142
|
+
if source.endswith("sitemap.xml"):
|
|
143
|
+
texts = scrape_sitemap(source, max_workers=workers)
|
|
144
|
+
elif source.startswith("http"):
|
|
145
|
+
texts = scrape_site(source, max_pages=max_pages, max_workers=workers)
|
|
146
|
+
else:
|
|
147
|
+
source_path = Path(source).expanduser().resolve()
|
|
148
|
+
if not source_path.exists() or not source_path.is_file():
|
|
149
|
+
print("Unsupported source")
|
|
150
|
+
return
|
|
151
|
+
|
|
152
|
+
suffix = source_path.suffix.lower()
|
|
153
|
+
if suffix == ".pdf":
|
|
154
|
+
texts = loadpdf(source_path)
|
|
155
|
+
elif suffix == ".csv":
|
|
156
|
+
texts = loadcsv(source_path)
|
|
157
|
+
else:
|
|
158
|
+
print("Unsupported local file type. Use .pdf or .csv")
|
|
159
|
+
return
|
|
160
|
+
|
|
161
|
+
if not texts:
|
|
162
|
+
print("No extractable text found in file.")
|
|
163
|
+
return
|
|
164
|
+
source = str(source_path)
|
|
165
|
+
|
|
166
|
+
embed_texts(texts, source=source, batch_size=batch_size, embed_workers=embed_workers)
|
|
167
|
+
print("Ingestion complete.")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@app.command()
|
|
171
|
+
def ask(question: str):
|
|
172
|
+
"""Ask a question against the ingested docs and display beautifully rendered response."""
|
|
173
|
+
store.check_ollama_connection()
|
|
174
|
+
# Question panel
|
|
175
|
+
question_text = Text(question, style="bold white")
|
|
176
|
+
question_panel = Panel(
|
|
177
|
+
question_text,
|
|
178
|
+
title="[bold cyan]❓ QUESTION[/bold cyan]",
|
|
179
|
+
border_style="cyan",
|
|
180
|
+
padding=(1, 2),
|
|
181
|
+
)
|
|
182
|
+
console.print(question_panel)
|
|
183
|
+
|
|
184
|
+
try:
|
|
185
|
+
console.print("[dim]⏳ Thinking...[/dim]\n")
|
|
186
|
+
response = askai(question)
|
|
187
|
+
|
|
188
|
+
# Response panel with markdown
|
|
189
|
+
response_markdown = Markdown(response)
|
|
190
|
+
response_panel = Panel(
|
|
191
|
+
response_markdown,
|
|
192
|
+
title="[bold green]✨ RESPONSE[/bold green]",
|
|
193
|
+
border_style="green",
|
|
194
|
+
padding=(1, 2),
|
|
195
|
+
)
|
|
196
|
+
console.print(response_panel)
|
|
197
|
+
|
|
198
|
+
# Success footer
|
|
199
|
+
footer = Align.center(Text("✓ Done", style="dim yellow"))
|
|
200
|
+
console.print(footer)
|
|
201
|
+
console.print()
|
|
202
|
+
|
|
203
|
+
except Exception as e:
|
|
204
|
+
error_panel = Panel(
|
|
205
|
+
Text(str(e), style="bold red"),
|
|
206
|
+
title="[bold red]❌ ERROR[/bold red]",
|
|
207
|
+
border_style="red",
|
|
208
|
+
padding=(1, 2),
|
|
209
|
+
)
|
|
210
|
+
console.print(error_panel)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@app.command()
|
|
214
|
+
def clear():
|
|
215
|
+
"""Clear the local vector database."""
|
|
216
|
+
config = store.load_config()
|
|
217
|
+
db_path = Path(config.get("db_path", ""))
|
|
218
|
+
|
|
219
|
+
if not db_path.exists():
|
|
220
|
+
console.print("[yellow]Database is already empty or does not exist.[/yellow]")
|
|
221
|
+
return
|
|
222
|
+
|
|
223
|
+
confirm = typer.confirm(f"Are you sure you want to delete the database at {db_path}?")
|
|
224
|
+
if not confirm:
|
|
225
|
+
console.print("Operation cancelled.")
|
|
226
|
+
return
|
|
227
|
+
|
|
228
|
+
import shutil
|
|
229
|
+
|
|
230
|
+
try:
|
|
231
|
+
shutil.rmtree(db_path)
|
|
232
|
+
console.print("[bold green]✓ Database cleared successfully![/bold green]")
|
|
233
|
+
except Exception as e:
|
|
234
|
+
console.print(f"[bold red]❌ Error clearing database: {e}[/bold red]")
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@app.command()
|
|
238
|
+
def setup():
|
|
239
|
+
"""Run the interactive model setup wizard."""
|
|
240
|
+
store.interactive_setup(first_time=False)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
@app.command()
|
|
244
|
+
def model(action: str, model_name=typer.Argument(None, help="Name of the model to set")):
|
|
245
|
+
"""List available Ollama models or set a default model for Q&A or embeddings."""
|
|
246
|
+
models = ollama.list()
|
|
247
|
+
config = store.load_config()
|
|
248
|
+
"""List available models or set a default model."""
|
|
249
|
+
if action == "list":
|
|
250
|
+
for i in models.models:
|
|
251
|
+
print(i.model)
|
|
252
|
+
elif action == "set":
|
|
253
|
+
if model_name in [m.model for m in models.models]:
|
|
254
|
+
config["default_model"] = model_name
|
|
255
|
+
store.save_config(config)
|
|
256
|
+
print(f"Model set to: {model_name}")
|
|
257
|
+
else:
|
|
258
|
+
print(f"Model '{model_name}' not found. Use 'list' to see available models.")
|
|
259
|
+
elif action == "setembed":
|
|
260
|
+
if model_name in [m.model for m in models.models]:
|
|
261
|
+
config["default_embed_model"] = model_name
|
|
262
|
+
store.save_config(config)
|
|
263
|
+
print(f"Embed model set to: {model_name}")
|
|
264
|
+
else:
|
|
265
|
+
print(f"Model '{model_name}' not found. Use 'list' to see available models.")
|
|
266
|
+
else:
|
|
267
|
+
print("Unsupported action. Use 'list' to see available models.")
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
@app.command()
|
|
271
|
+
def speed(profile: str = typer.Argument("balanced", help="fast, balanced, or quality")):
|
|
272
|
+
"""Set reply speed profile by tuning retrieval and Ollama generation settings."""
|
|
273
|
+
config = store.load_config()
|
|
274
|
+
|
|
275
|
+
profiles = {
|
|
276
|
+
"fast": {
|
|
277
|
+
"retrieval_k": 4,
|
|
278
|
+
"max_context_chars": 2200,
|
|
279
|
+
"max_doc_chars": 500,
|
|
280
|
+
"num_predict": 128,
|
|
281
|
+
"num_ctx": 1536,
|
|
282
|
+
"temperature": 0.1,
|
|
283
|
+
},
|
|
284
|
+
"balanced": {
|
|
285
|
+
"retrieval_k": 6,
|
|
286
|
+
"max_context_chars": 3500,
|
|
287
|
+
"max_doc_chars": 700,
|
|
288
|
+
"num_predict": 192,
|
|
289
|
+
"num_ctx": 2048,
|
|
290
|
+
"temperature": 0.1,
|
|
291
|
+
},
|
|
292
|
+
"quality": {
|
|
293
|
+
"retrieval_k": 10,
|
|
294
|
+
"max_context_chars": 5500,
|
|
295
|
+
"max_doc_chars": 1000,
|
|
296
|
+
"num_predict": 320,
|
|
297
|
+
"num_ctx": 4096,
|
|
298
|
+
"temperature": 0.2,
|
|
299
|
+
},
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
selected = profiles.get(profile.lower())
|
|
303
|
+
if selected is None:
|
|
304
|
+
print("Unsupported profile. Use: fast, balanced, or quality")
|
|
305
|
+
return
|
|
306
|
+
|
|
307
|
+
config.update(selected)
|
|
308
|
+
store.save_config(config)
|
|
309
|
+
print(f"Speed profile set to: {profile.lower()}")
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
if __name__ == "__main__":
|
|
313
|
+
app()
|
docpilot/embed.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
from langchain_chroma import Chroma
|
|
2
|
+
from langchain_core.documents import Document
|
|
3
|
+
from langchain_ollama import OllamaEmbeddings
|
|
4
|
+
import hashlib
|
|
5
|
+
import os
|
|
6
|
+
from collections import deque
|
|
7
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
8
|
+
from . import store
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _is_context_length_error(exc: Exception) -> bool:
|
|
12
|
+
msg = str(exc).lower()
|
|
13
|
+
return ("context" in msg and "length" in msg) or "input length" in msg or "too many tokens" in msg
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _split_text_by_chars(text: str, max_chars: int, overlap: int) -> list[str]:
|
|
17
|
+
text = text.strip()
|
|
18
|
+
if not text:
|
|
19
|
+
return []
|
|
20
|
+
if len(text) <= max_chars:
|
|
21
|
+
return [text]
|
|
22
|
+
|
|
23
|
+
parts: list[str] = []
|
|
24
|
+
step = max(1, max_chars - overlap)
|
|
25
|
+
start = 0
|
|
26
|
+
while start < len(text):
|
|
27
|
+
part = text[start : start + max_chars].strip()
|
|
28
|
+
if part:
|
|
29
|
+
parts.append(part)
|
|
30
|
+
start += step
|
|
31
|
+
return parts
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _safe_add_documents(batch_docs: list[Document], batch_ids: list[str]) -> tuple[int, int]:
|
|
35
|
+
"""Try batch insert first; on context overflow, split individual docs and retry."""
|
|
36
|
+
try:
|
|
37
|
+
vectorstore.add_documents(documents=batch_docs, ids=batch_ids)
|
|
38
|
+
return len(batch_docs), 0
|
|
39
|
+
except Exception as e:
|
|
40
|
+
if not _is_context_length_error(e):
|
|
41
|
+
raise
|
|
42
|
+
|
|
43
|
+
inserted = 0
|
|
44
|
+
skipped = 0
|
|
45
|
+
for doc, doc_id in zip(batch_docs, batch_ids):
|
|
46
|
+
queue: deque[tuple[str, str]] = deque([(doc.page_content, doc_id)])
|
|
47
|
+
while queue:
|
|
48
|
+
text, current_id = queue.popleft()
|
|
49
|
+
try:
|
|
50
|
+
vectorstore.add_documents(
|
|
51
|
+
documents=[Document(page_content=text, metadata=doc.metadata, id=current_id)],
|
|
52
|
+
ids=[current_id],
|
|
53
|
+
)
|
|
54
|
+
inserted += 1
|
|
55
|
+
continue
|
|
56
|
+
except Exception as inner_exc:
|
|
57
|
+
if not _is_context_length_error(inner_exc):
|
|
58
|
+
raise
|
|
59
|
+
|
|
60
|
+
# Keep splitting until chunks are small enough; skip pathological inputs.
|
|
61
|
+
if len(text) <= 220:
|
|
62
|
+
skipped += 1
|
|
63
|
+
print(f"Skipped chunk due to context limit: {current_id}")
|
|
64
|
+
continue
|
|
65
|
+
|
|
66
|
+
next_size = max(220, len(text) // 2)
|
|
67
|
+
overlap = min(80, max(20, next_size // 5))
|
|
68
|
+
sub_parts = _split_text_by_chars(text, max_chars=next_size, overlap=overlap)
|
|
69
|
+
if len(sub_parts) <= 1:
|
|
70
|
+
skipped += 1
|
|
71
|
+
print(f"Skipped chunk due to repeated overflow: {current_id}")
|
|
72
|
+
continue
|
|
73
|
+
|
|
74
|
+
for idx, sub in enumerate(sub_parts):
|
|
75
|
+
queue.append((sub, f"{current_id}-s{idx}"))
|
|
76
|
+
|
|
77
|
+
return inserted, skipped
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _print_progress(label: str, current: int, total: int, width: int = 28) -> None:
|
|
81
|
+
if total <= 0:
|
|
82
|
+
return
|
|
83
|
+
ratio = min(max(current / total, 0.0), 1.0)
|
|
84
|
+
filled = int(width * ratio)
|
|
85
|
+
bar = "#" * filled + "-" * (width - filled)
|
|
86
|
+
end = "\n" if current >= total else "\r"
|
|
87
|
+
print(f"{label}: [{bar}] {current}/{total}", end=end, flush=True)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
embeddings = OllamaEmbeddings(model=store.load_config().get("default_embed_model", "mxbai-embed-large:335m"))
|
|
91
|
+
db_location = store.path / "chroma_langchain_db"
|
|
92
|
+
|
|
93
|
+
vectorstore = Chroma(collection_name="documents", persist_directory=db_location, embedding_function=embeddings)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def chunk_text(
|
|
97
|
+
text: str,
|
|
98
|
+
chunk_size: int = 120,
|
|
99
|
+
overlap: int = 20,
|
|
100
|
+
max_chars: int = 1200,
|
|
101
|
+
) -> list[str]:
|
|
102
|
+
words = text.split()
|
|
103
|
+
chunks = []
|
|
104
|
+
i = 0
|
|
105
|
+
step = max(1, chunk_size - overlap)
|
|
106
|
+
while i < len(words):
|
|
107
|
+
chunk = " ".join(words[i : i + chunk_size]).strip()
|
|
108
|
+
if len(chunk) > max_chars:
|
|
109
|
+
chunk = chunk[:max_chars].rsplit(" ", 1)[0].strip() or chunk[:max_chars]
|
|
110
|
+
if chunk:
|
|
111
|
+
chunks.append(chunk)
|
|
112
|
+
i += step
|
|
113
|
+
return chunks
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _resolve_embed_workers(embed_workers: int, text_count: int) -> int:
|
|
117
|
+
if text_count <= 1:
|
|
118
|
+
return 1
|
|
119
|
+
if embed_workers > 0:
|
|
120
|
+
return min(embed_workers, text_count)
|
|
121
|
+
|
|
122
|
+
cpu_count = os.cpu_count() or 4
|
|
123
|
+
auto_workers = max(2, cpu_count // 2)
|
|
124
|
+
auto_workers = min(8, auto_workers)
|
|
125
|
+
return min(auto_workers, text_count)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def embed_texts(texts: list[str], source: str = "web", batch_size: int = 32, embed_workers: int = 0):
|
|
129
|
+
documents = []
|
|
130
|
+
ids = []
|
|
131
|
+
chunk_counter = 0
|
|
132
|
+
seen_chunks = set() # Track chunk content to avoid duplicates
|
|
133
|
+
|
|
134
|
+
workers = _resolve_embed_workers(embed_workers, len(texts))
|
|
135
|
+
if workers > 1:
|
|
136
|
+
with ThreadPoolExecutor(max_workers=workers) as executor:
|
|
137
|
+
chunked_texts = list(executor.map(chunk_text, texts))
|
|
138
|
+
else:
|
|
139
|
+
chunked_texts = [chunk_text(text) for text in texts]
|
|
140
|
+
|
|
141
|
+
for chunks in chunked_texts:
|
|
142
|
+
for chunk in chunks:
|
|
143
|
+
# Skip duplicate chunks
|
|
144
|
+
if chunk in seen_chunks:
|
|
145
|
+
continue
|
|
146
|
+
seen_chunks.add(chunk)
|
|
147
|
+
|
|
148
|
+
doc_id = hashlib.md5(f"{source}:{chunk_counter}:{chunk}".encode()).hexdigest()
|
|
149
|
+
doc = Document(page_content=chunk + "source" + source, metadata={"source": source}, id=doc_id)
|
|
150
|
+
documents.append(doc)
|
|
151
|
+
ids.append(doc_id)
|
|
152
|
+
chunk_counter += 1
|
|
153
|
+
|
|
154
|
+
if not documents:
|
|
155
|
+
print(f"No chunks to embed from {source}")
|
|
156
|
+
return
|
|
157
|
+
|
|
158
|
+
total_batches = (len(documents) + batch_size - 1) // batch_size
|
|
159
|
+
inserted_total = 0
|
|
160
|
+
skipped_total = 0
|
|
161
|
+
for batch_num, i in enumerate(range(0, len(documents), batch_size), start=1):
|
|
162
|
+
batch_docs = documents[i : i + batch_size]
|
|
163
|
+
batch_ids = ids[i : i + batch_size]
|
|
164
|
+
inserted, skipped = _safe_add_documents(batch_docs, batch_ids)
|
|
165
|
+
inserted_total += inserted
|
|
166
|
+
skipped_total += skipped
|
|
167
|
+
_print_progress("Embedding batches", batch_num, total_batches)
|
|
168
|
+
|
|
169
|
+
print(f"Embedded {inserted_total} chunks from {source} (skipped {skipped_total})")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
retriever = vectorstore.as_retriever(search_kwargs={"k": 20})
|
docpilot/scrape.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import httpx
|
|
2
|
+
from bs4 import BeautifulSoup
|
|
3
|
+
from urllib.parse import urljoin, urlparse
|
|
4
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
5
|
+
from collections import deque
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
REQUEST_HEADERS = {"User-Agent": "docpilot/0.0.1 (+https://github.com/foss-hack/docpilot)"}
|
|
10
|
+
MAX_RETRIES = 4
|
|
11
|
+
BACKOFF_SECONDS = 0.8
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _print_progress(label: str, current: int, total: int, width: int = 28) -> None:
|
|
15
|
+
if total <= 0:
|
|
16
|
+
return
|
|
17
|
+
ratio = min(max(current / total, 0.0), 1.0)
|
|
18
|
+
filled = int(width * ratio)
|
|
19
|
+
bar = "#" * filled + "-" * (width - filled)
|
|
20
|
+
end = "\n" if current >= total else "\r"
|
|
21
|
+
print(f"{label}: [{bar}] {current}/{total}", end=end, flush=True)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _extract_text(html: str) -> str:
|
|
25
|
+
soup = BeautifulSoup(html, "html.parser")
|
|
26
|
+
return _extract_text_from_soup(soup)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _extract_text_from_soup(soup: BeautifulSoup) -> str:
|
|
30
|
+
for tag in soup(["nav", "footer", "script", "style"]):
|
|
31
|
+
tag.decompose()
|
|
32
|
+
return soup.get_text(separator="\n", strip=True)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _normalize_url(url: str) -> str:
|
|
36
|
+
parsed = urlparse(url)
|
|
37
|
+
cleaned = parsed._replace(fragment="")
|
|
38
|
+
normalized = cleaned.geturl()
|
|
39
|
+
if normalized.endswith("/") and len(normalized) > len(f"{cleaned.scheme}://{cleaned.netloc}/"):
|
|
40
|
+
normalized = normalized.rstrip("/")
|
|
41
|
+
return normalized
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _should_skip_url(url: str) -> bool:
|
|
45
|
+
path = urlparse(url).path
|
|
46
|
+
# Skip utility/search pages and language index variants that trigger many low-value requests.
|
|
47
|
+
if "/title/Special:" in path:
|
|
48
|
+
return True
|
|
49
|
+
if "/title/Main_page_(" in path:
|
|
50
|
+
return True
|
|
51
|
+
return False
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _retry_delay_seconds(response: httpx.Response | None, attempt: int) -> float:
|
|
55
|
+
if response is not None:
|
|
56
|
+
retry_after = response.headers.get("Retry-After")
|
|
57
|
+
if retry_after:
|
|
58
|
+
try:
|
|
59
|
+
return max(0.2, float(retry_after))
|
|
60
|
+
except ValueError:
|
|
61
|
+
pass
|
|
62
|
+
return BACKOFF_SECONDS * (2**attempt)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _get_with_retries(client: httpx.Client, url: str, timeout: float) -> httpx.Response:
|
|
66
|
+
last_exc: Exception | None = None
|
|
67
|
+
for attempt in range(MAX_RETRIES):
|
|
68
|
+
try:
|
|
69
|
+
res = client.get(url, follow_redirects=True, timeout=timeout)
|
|
70
|
+
if res.status_code == 429:
|
|
71
|
+
if attempt < MAX_RETRIES - 1:
|
|
72
|
+
time.sleep(_retry_delay_seconds(res, attempt))
|
|
73
|
+
continue
|
|
74
|
+
if 500 <= res.status_code < 600 and attempt < MAX_RETRIES - 1:
|
|
75
|
+
time.sleep(_retry_delay_seconds(res, attempt))
|
|
76
|
+
continue
|
|
77
|
+
res.raise_for_status()
|
|
78
|
+
return res
|
|
79
|
+
except (httpx.ConnectError, httpx.ReadTimeout, httpx.WriteTimeout, httpx.RemoteProtocolError) as e:
|
|
80
|
+
last_exc = e
|
|
81
|
+
if attempt < MAX_RETRIES - 1:
|
|
82
|
+
time.sleep(_retry_delay_seconds(None, attempt))
|
|
83
|
+
continue
|
|
84
|
+
raise
|
|
85
|
+
except httpx.HTTPStatusError as e:
|
|
86
|
+
last_exc = e
|
|
87
|
+
if e.response.status_code in (429, 500, 502, 503, 504) and attempt < MAX_RETRIES - 1:
|
|
88
|
+
time.sleep(_retry_delay_seconds(e.response, attempt))
|
|
89
|
+
continue
|
|
90
|
+
raise
|
|
91
|
+
|
|
92
|
+
if last_exc is not None:
|
|
93
|
+
raise last_exc
|
|
94
|
+
raise RuntimeError(f"Request failed for {url}")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def scrape_url(url: str, client: httpx.Client | None = None) -> str:
|
|
98
|
+
if client is None:
|
|
99
|
+
with httpx.Client(headers=REQUEST_HEADERS) as local_client:
|
|
100
|
+
res = _get_with_retries(local_client, url, timeout=30.0)
|
|
101
|
+
else:
|
|
102
|
+
res = _get_with_retries(client, url, timeout=30.0)
|
|
103
|
+
return _extract_text(res.text)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _fetch_html(url: str, client: httpx.Client) -> tuple[str, str]:
|
|
107
|
+
res = _get_with_retries(client, url, timeout=20.0)
|
|
108
|
+
return url, res.text
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _collect_sitemap_urls(
|
|
112
|
+
sitemap_url: str,
|
|
113
|
+
seen: set[str] | None = None,
|
|
114
|
+
client: httpx.Client | None = None,
|
|
115
|
+
) -> list[str]:
|
|
116
|
+
if seen is None:
|
|
117
|
+
seen = set()
|
|
118
|
+
if sitemap_url in seen:
|
|
119
|
+
return []
|
|
120
|
+
seen.add(sitemap_url)
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
if client is None:
|
|
124
|
+
with httpx.Client(headers=REQUEST_HEADERS) as local_client:
|
|
125
|
+
res = _get_with_retries(local_client, sitemap_url, timeout=30.0)
|
|
126
|
+
else:
|
|
127
|
+
res = _get_with_retries(client, sitemap_url, timeout=30.0)
|
|
128
|
+
except httpx.HTTPStatusError as e:
|
|
129
|
+
if e.response.status_code == 404:
|
|
130
|
+
print(f"Sitemap not found (404): {sitemap_url}")
|
|
131
|
+
else:
|
|
132
|
+
print(f"Failed to fetch sitemap (HTTP {e.response.status_code}): {sitemap_url}")
|
|
133
|
+
return []
|
|
134
|
+
except Exception as e:
|
|
135
|
+
print(f"Error fetching sitemap: {sitemap_url} - {e}")
|
|
136
|
+
return []
|
|
137
|
+
|
|
138
|
+
soup = BeautifulSoup(res.text, "xml")
|
|
139
|
+
if not soup.find():
|
|
140
|
+
print(f"Invalid sitemap XML from: {sitemap_url}")
|
|
141
|
+
return []
|
|
142
|
+
|
|
143
|
+
urls: list[str] = []
|
|
144
|
+
for loc in soup.find_all("loc"):
|
|
145
|
+
if not loc.text:
|
|
146
|
+
continue
|
|
147
|
+
target = loc.text.strip()
|
|
148
|
+
if not target:
|
|
149
|
+
continue
|
|
150
|
+
if target.endswith(".xml") or target.endswith(".xml.gz"):
|
|
151
|
+
urls.extend(_collect_sitemap_urls(target, seen, client=client))
|
|
152
|
+
else:
|
|
153
|
+
urls.append(target)
|
|
154
|
+
return urls
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def scrape_sitemap(sitemap_url: str, max_workers: int = 16) -> list[str]:
|
|
158
|
+
limits = httpx.Limits(max_keepalive_connections=20, max_connections=100)
|
|
159
|
+
with httpx.Client(limits=limits, headers=REQUEST_HEADERS) as client:
|
|
160
|
+
urls = _collect_sitemap_urls(sitemap_url, client=client)
|
|
161
|
+
texts: list[str] = []
|
|
162
|
+
total = len(urls)
|
|
163
|
+
if total == 0:
|
|
164
|
+
return texts
|
|
165
|
+
|
|
166
|
+
workers = max(1, min(max_workers, total))
|
|
167
|
+
with httpx.Client(limits=limits, headers=REQUEST_HEADERS) as client:
|
|
168
|
+
with ThreadPoolExecutor(max_workers=workers) as executor:
|
|
169
|
+
futures = [executor.submit(scrape_url, u, client) for u in urls]
|
|
170
|
+
completed = 0
|
|
171
|
+
for future in as_completed(futures):
|
|
172
|
+
completed += 1
|
|
173
|
+
try:
|
|
174
|
+
texts.append(future.result())
|
|
175
|
+
except Exception:
|
|
176
|
+
pass
|
|
177
|
+
_print_progress("Scraping sitemap pages", completed, total)
|
|
178
|
+
return texts
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def scrape_site(base_url: str, max_pages: int = 100, max_workers: int = 16) -> list[str]:
|
|
182
|
+
base_url = _normalize_url(base_url)
|
|
183
|
+
base_netloc = urlparse(base_url).netloc
|
|
184
|
+
|
|
185
|
+
visited: set[str] = set()
|
|
186
|
+
queued: set[str] = {base_url}
|
|
187
|
+
to_visit: deque[str] = deque([base_url])
|
|
188
|
+
texts = []
|
|
189
|
+
limits = httpx.Limits(max_keepalive_connections=20, max_connections=100)
|
|
190
|
+
effective_workers = max(1, max_workers)
|
|
191
|
+
|
|
192
|
+
with httpx.Client(limits=limits, headers=REQUEST_HEADERS) as client:
|
|
193
|
+
with ThreadPoolExecutor(max_workers=effective_workers) as executor:
|
|
194
|
+
while to_visit and len(visited) < max_pages:
|
|
195
|
+
batch: list[str] = []
|
|
196
|
+
while to_visit and len(batch) < effective_workers and (len(visited) + len(batch)) < max_pages:
|
|
197
|
+
candidate = to_visit.popleft()
|
|
198
|
+
if candidate in visited:
|
|
199
|
+
continue
|
|
200
|
+
if _should_skip_url(candidate):
|
|
201
|
+
continue
|
|
202
|
+
batch.append(candidate)
|
|
203
|
+
|
|
204
|
+
futures = {executor.submit(_fetch_html, url, client): url for url in batch}
|
|
205
|
+
for future in as_completed(futures):
|
|
206
|
+
url = futures[future]
|
|
207
|
+
visited.add(url)
|
|
208
|
+
_print_progress("Crawling pages", len(visited), max_pages)
|
|
209
|
+
try:
|
|
210
|
+
_, html = future.result()
|
|
211
|
+
except httpx.HTTPStatusError as e:
|
|
212
|
+
if e.response.status_code == 404:
|
|
213
|
+
print(f" Page not found (404): {url}")
|
|
214
|
+
else:
|
|
215
|
+
print(f" HTTP error {e.response.status_code}: {url}")
|
|
216
|
+
continue
|
|
217
|
+
except Exception as e:
|
|
218
|
+
print(f" Error scraping {url}: {type(e).__name__}")
|
|
219
|
+
continue
|
|
220
|
+
|
|
221
|
+
soup = BeautifulSoup(html, "html.parser")
|
|
222
|
+
texts.append(_extract_text_from_soup(soup))
|
|
223
|
+
for a in soup.find_all("a", href=True):
|
|
224
|
+
full = _normalize_url(urljoin(url, a["href"]))
|
|
225
|
+
parsed = urlparse(full)
|
|
226
|
+
if parsed.netloc != base_netloc:
|
|
227
|
+
continue
|
|
228
|
+
if _should_skip_url(full):
|
|
229
|
+
continue
|
|
230
|
+
if full in visited or full in queued:
|
|
231
|
+
continue
|
|
232
|
+
queued.add(full)
|
|
233
|
+
to_visit.append(full)
|
|
234
|
+
return texts
|
docpilot/store.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import tomllib
|
|
2
|
+
import tomli_w
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import ollama
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
path = Path.home() / ".docpilot"
|
|
8
|
+
CONFIG_PATH = path / "config.toml"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _get_available_models():
|
|
12
|
+
try:
|
|
13
|
+
models = ollama.list().models
|
|
14
|
+
return [m.model for m in models]
|
|
15
|
+
except Exception:
|
|
16
|
+
return []
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
_AVAILABLE_MODELS = _get_available_models()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
DEFAULT_CONFIG = {
|
|
23
|
+
"default_embed_model": _AVAILABLE_MODELS[0] if _AVAILABLE_MODELS else "mxbai-embed-large:335m",
|
|
24
|
+
"default_model": _AVAILABLE_MODELS[1] if len(_AVAILABLE_MODELS) > 1 else "llama2",
|
|
25
|
+
"db_path": str(path / "chroma_langchain_db"),
|
|
26
|
+
"log_level": "info",
|
|
27
|
+
"retrieval_k": 6,
|
|
28
|
+
"max_context_chars": 3500,
|
|
29
|
+
"max_doc_chars": 700,
|
|
30
|
+
"num_predict": 192,
|
|
31
|
+
"num_ctx": 2048,
|
|
32
|
+
"num_thread": max(1, (os.cpu_count() or 4) - 1),
|
|
33
|
+
"temperature": 0.1,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def check_ollama_connection():
|
|
38
|
+
try:
|
|
39
|
+
ollama.list()
|
|
40
|
+
except Exception:
|
|
41
|
+
from rich.console import Console
|
|
42
|
+
|
|
43
|
+
console = Console()
|
|
44
|
+
console.print("\n[bold red]❌ Error: Could not connect to Ollama.[/bold red]")
|
|
45
|
+
console.print("[yellow]Please ensure the Ollama application is running and try again.[/yellow]\n")
|
|
46
|
+
import sys
|
|
47
|
+
|
|
48
|
+
sys.exit(1)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def init_config():
|
|
52
|
+
"""Initialize config file with defaults if it doesn't exist."""
|
|
53
|
+
if not CONFIG_PATH.exists():
|
|
54
|
+
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
55
|
+
interactive_setup(first_time=True)
|
|
56
|
+
return load_config()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def interactive_setup(first_time=False):
|
|
60
|
+
from rich.console import Console
|
|
61
|
+
from rich.prompt import Prompt
|
|
62
|
+
|
|
63
|
+
console = Console()
|
|
64
|
+
|
|
65
|
+
if first_time:
|
|
66
|
+
console.print("\n[bold cyan]🚀 Welcome to Docpilot! Let's do a quick setup.[/bold cyan]")
|
|
67
|
+
else:
|
|
68
|
+
console.print("\n[bold cyan]⚙️ Docpilot Model Setup[/bold cyan]")
|
|
69
|
+
|
|
70
|
+
models = _get_available_models()
|
|
71
|
+
if not models:
|
|
72
|
+
console.print("[yellow]No local Ollama models found! Using default fallbacks.[/yellow]")
|
|
73
|
+
console.print("Please remember to run `ollama pull mxbai-embed-large` and `ollama pull qwen2.5:latest` later.")
|
|
74
|
+
embed_model = Prompt.ask("Enter embedding model name", default="mxbai-embed-large:335m")
|
|
75
|
+
chat_model = Prompt.ask("Enter chat model name", default="qwen2.5:latest")
|
|
76
|
+
else:
|
|
77
|
+
# Smart defaults based on names
|
|
78
|
+
embed_guess = next((m for m in models if "embed" in m.lower()), models[0])
|
|
79
|
+
chat_guess = next((m for m in models if "embed" not in m.lower()), models[1] if len(models) > 1 else models[0])
|
|
80
|
+
|
|
81
|
+
embed_model = Prompt.ask(
|
|
82
|
+
"Select your [bold green]embedding model[/bold green]", choices=models, default=embed_guess
|
|
83
|
+
)
|
|
84
|
+
chat_model = Prompt.ask("Select your [bold blue]chat model[/bold blue]", choices=models, default=chat_guess)
|
|
85
|
+
|
|
86
|
+
config = load_config() if not first_time else DEFAULT_CONFIG.copy()
|
|
87
|
+
config["default_embed_model"] = embed_model
|
|
88
|
+
config["default_model"] = chat_model
|
|
89
|
+
save_config(config)
|
|
90
|
+
console.print(f"[bold green]✓ Configuration saved to {CONFIG_PATH}[/bold green]\n")
|
|
91
|
+
return load_config()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def load_config():
|
|
95
|
+
if not CONFIG_PATH.exists():
|
|
96
|
+
return DEFAULT_CONFIG.copy()
|
|
97
|
+
try:
|
|
98
|
+
with open(CONFIG_PATH, "rb") as f:
|
|
99
|
+
loaded = tomllib.load(f)
|
|
100
|
+
except tomllib.TOMLDecodeError:
|
|
101
|
+
print(f"Invalid config at {CONFIG_PATH}. Recreating with defaults.")
|
|
102
|
+
save_config(DEFAULT_CONFIG.copy())
|
|
103
|
+
return DEFAULT_CONFIG.copy()
|
|
104
|
+
|
|
105
|
+
merged = DEFAULT_CONFIG.copy()
|
|
106
|
+
merged.update(loaded)
|
|
107
|
+
return merged
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def save_config(config: dict):
|
|
111
|
+
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
112
|
+
with open(CONFIG_PATH, "wb") as f:
|
|
113
|
+
tomli_w.dump(config, f)
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: docpilot-cli
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A local-first RAG pipeline CLI tool
|
|
5
|
+
Requires-Python: >=3.12
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: bs4>=0.0.2
|
|
9
|
+
Requires-Dist: beautifulsoup4>=4.12.0
|
|
10
|
+
Requires-Dist: langchain>=0.2.0
|
|
11
|
+
Requires-Dist: langchain-chroma>=0.1.0
|
|
12
|
+
Requires-Dist: langchain-ollama>=0.1.0
|
|
13
|
+
Requires-Dist: ollama>=0.2.0
|
|
14
|
+
Requires-Dist: pandas>=2.0.0
|
|
15
|
+
Requires-Dist: typer>=0.12.0
|
|
16
|
+
Requires-Dist: httpx>=0.27.0
|
|
17
|
+
Requires-Dist: tomli-w>=1.0.0
|
|
18
|
+
Requires-Dist: pypdf>=5.0.0
|
|
19
|
+
Requires-Dist: pyfiglet>=0.8.0
|
|
20
|
+
Requires-Dist: rich>=13.0.0
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# 🚀 DocPilot CLI
|
|
24
|
+
|
|
25
|
+

|
|
26
|
+

|
|
27
|
+

|
|
28
|
+
|
|
29
|
+
**DocPilot** is a lightning-fast, local-first CLI for document ingestion and interactive question-answering. Powered by [Ollama](https://ollama.com/) and Chroma, it allows you to ingest websites, PDFs, and CSVs directly from your terminal and chat with your documents—keeping 100% of your data safely on your own machine.
|
|
30
|
+
|
|
31
|
+
It’s built for practical developer workflows: crawl sites concurrently, prepare chunks with multi-threading, and iterate rapidly without ever paying for a cloud API.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## ✨ Features
|
|
36
|
+
|
|
37
|
+
- **🔒 100% Local**: No data ever leaves your machine. Powered by Ollama.
|
|
38
|
+
- **⚡ Interactive Setup Wizard**: Get up and running instantly with smart model auto-detection.
|
|
39
|
+
- **🌐 Universal Ingestion**: Seamlessly ingest Website URLs, XML Sitemaps, PDFs, and CSVs.
|
|
40
|
+
- **🚀 Concurrent Processing**: Lightning-fast crawling and multi-threaded document chunking.
|
|
41
|
+
- **🎛️ Performance Profiles**: Switch between `fast`, `balanced`, and `quality` inference speeds on the fly.
|
|
42
|
+
- **🎨 Beautiful Terminal UI**: Rich markdown rendering, ASCII art, and intuitive progress bars.
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## 📦 Installation
|
|
47
|
+
|
|
48
|
+
DocPilot is available on PyPI! You can install it globally using `pip`, `uv`, or `pipx`.
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
# Recommended: Install using uv or pipx
|
|
52
|
+
uv tool install docpilot-cli
|
|
53
|
+
|
|
54
|
+
# Or via standard pip
|
|
55
|
+
pip install docpilot-cli
|
|
56
|
+
|
|
57
|
+
# Optional: Add PDF parsing support
|
|
58
|
+
pip install "docpilot-cli[pdf]"
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Prerequisites
|
|
62
|
+
1. **Python 3.12+**
|
|
63
|
+
2. **[Ollama](https://ollama.com/)**: Installed and running in the background.
|
|
64
|
+
3. Pull your preferred models:
|
|
65
|
+
```bash
|
|
66
|
+
ollama pull qwen2.5:latest
|
|
67
|
+
ollama pull mxbai-embed-large:335m
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## 🛠️ Quick Start
|
|
73
|
+
|
|
74
|
+
The very first time you run a DocPilot command, it will launch the **Interactive Setup Wizard** to help you configure your chat and embedding models.
|
|
75
|
+
|
|
76
|
+
### 1. Ingest Knowledge
|
|
77
|
+
Point DocPilot to any documentation site, sitemap, PDF, or CSV:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
# Crawl a website
|
|
81
|
+
docpilot ingest "https://docs.python.org/3/" --max-pages 100 --workers 16
|
|
82
|
+
|
|
83
|
+
# Ingest a local PDF
|
|
84
|
+
docpilot ingest "./docs/engineering_handbook.pdf"
|
|
85
|
+
|
|
86
|
+
# Ingest a CSV
|
|
87
|
+
docpilot ingest "./data/faq.csv"
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### 2. Ask Questions
|
|
91
|
+
Query your newly created local knowledge base:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
docpilot ask "How do I create a virtual environment?"
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
## 🧰 CLI Command Reference
|
|
100
|
+
|
|
101
|
+
Manage your configuration, models, and local database with ease.
|
|
102
|
+
|
|
103
|
+
### `docpilot setup`
|
|
104
|
+
Re-run the interactive setup wizard at any time to change your default models.
|
|
105
|
+
|
|
106
|
+
### `docpilot clear`
|
|
107
|
+
Wipe your local Chroma vector database to start fresh. Prompts for safety confirmation.
|
|
108
|
+
|
|
109
|
+
### `docpilot speed [profile]`
|
|
110
|
+
Adjust the retrieval and generation settings for your desired use case.
|
|
111
|
+
- `fast`: Lower latency, shorter context limits.
|
|
112
|
+
- `balanced`: Default trade-off.
|
|
113
|
+
- `quality`: Larger context, more comprehensive answers, slower inference.
|
|
114
|
+
|
|
115
|
+
### `docpilot model`
|
|
116
|
+
Manually manage your Ollama models without the interactive setup wizard.
|
|
117
|
+
```bash
|
|
118
|
+
docpilot model list
|
|
119
|
+
docpilot model set <chat-model>
|
|
120
|
+
docpilot model setembed <embedding-model>
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### `docpilot render`
|
|
124
|
+
Parse and beautifully render any markdown file or text string directly in your terminal.
|
|
125
|
+
|
|
126
|
+
### `docpilot show`
|
|
127
|
+
Display your current project version and configuration in beautiful ASCII art.
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
## 🏗️ Architecture Under the Hood
|
|
132
|
+
|
|
133
|
+
DocPilot employs an optimized RAG (Retrieval-Augmented Generation) pipeline:
|
|
134
|
+
|
|
135
|
+
1. **Ingestion**: Native Python extractors (BeautifulSoup4, `csv`, `pypdf`) parse the raw data.
|
|
136
|
+
2. **Chunking**: Multi-threaded chunkers slice the documents into semantically coherent pieces.
|
|
137
|
+
3. **Embedding**: `langchain-ollama` creates local vector embeddings via Ollama.
|
|
138
|
+
4. **Storage**: `chromadb` persistently stores vectors on disk at `~/.docpilot/chroma_langchain_db`.
|
|
139
|
+
5. **Retrieval**: User queries are embedded, matched via similarity search, and fed into a system prompt.
|
|
140
|
+
6. **Generation**: The designated Ollama chat model generates the final response streamed to the terminal using `rich`.
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## 🤝 Contributing
|
|
145
|
+
|
|
146
|
+
Contributions are welcome! If you are using DocPilot for your daily workflows or in a hackathon, feel free to open issues and pull requests.
|
|
147
|
+
|
|
148
|
+
To set up a local development environment:
|
|
149
|
+
```bash
|
|
150
|
+
git clone https://github.com/yourusername/docpilot.git
|
|
151
|
+
cd docpilot
|
|
152
|
+
uv pip install -e ".[dev]"
|
|
153
|
+
uv run pytest
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## 📄 License
|
|
159
|
+
|
|
160
|
+
This project is licensed under the MIT License.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
docpilot/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
docpilot/chat.py,sha256=DxNUPcPpbkjmsVNUeZDzs5PZxH2zmsr577DNYKW9UVM,2263
|
|
3
|
+
docpilot/cli.py,sha256=DB7zlVjtFlPMqvWQYTv7oQuAVAePkqcjcK5q4-DIZpo,9862
|
|
4
|
+
docpilot/embed.py,sha256=3Y-BmVi0W8Jgt2G1eEKrKdjwPBZUPZyqAls5_VGd-Mw,5948
|
|
5
|
+
docpilot/scrape.py,sha256=jNUJi1G9Jx1-kT25sTHU7v-ZxmCdC0YfNTnaz6PPpNU,8776
|
|
6
|
+
docpilot/store.py,sha256=wrYezb1lJaeRYwzs1WIl4e-rRd51wAvAbTJZeZTKzn0,3720
|
|
7
|
+
docpilot_cli-1.0.0.dist-info/licenses/LICENSE,sha256=X4mftAPvc1sAnTsGkUXLxr13OO6ieIzNTCaxpLOLgPc,1068
|
|
8
|
+
docpilot_cli-1.0.0.dist-info/METADATA,sha256=NXfGnUH0_pkZ-eYHQ9Hoq8H0TYaZYNY_SyOxJaNbmRU,5272
|
|
9
|
+
docpilot_cli-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
10
|
+
docpilot_cli-1.0.0.dist-info/entry_points.txt,sha256=4xdYvYBz1-YIujMQ466UqTOrNYDPgy7vLFZhiuhLtlw,46
|
|
11
|
+
docpilot_cli-1.0.0.dist-info/top_level.txt,sha256=kTb5lJ_m1AkLt-9BLs6UKxf-FmvQLYT9ticqTXKO3d8,9
|
|
12
|
+
docpilot_cli-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ASWIN ASHOK
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
docpilot
|