-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlib.rs
More file actions
1278 lines (1110 loc) · 34.1 KB
/
Copy pathlib.rs
File metadata and controls
1278 lines (1110 loc) · 34.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2026 vectorless developers
// SPDX-License-Identifier: Apache-2.0
//! Python bindings for vectorless.
use pyo3::prelude::*;
use pyo3::exceptions::PyException;
use pyo3_async_runtimes::tokio::future_into_py;
use std::sync::Arc;
use tokio::runtime::Runtime;
use ::vectorless::client::{
DocumentFormat, DocumentInfo, Engine, EngineBuilder, FailedItem, IndexContext, IndexItem,
IndexMode, IndexOptions, IndexResult, QueryContext, QueryResult, QueryResultItem,
};
use ::vectorless::error::Error as RustError;
use ::vectorless::metrics::IndexMetrics;
use ::vectorless::StrategyPreference;
// ============================================================
// Error Types
// ============================================================
/// Python exception for vectorless errors.
#[pyclass(extends = PyException, subclass)]
pub struct VectorlessError {
message: String,
kind: String,
}
#[pymethods]
impl VectorlessError {
#[new]
fn new_py(message: String, kind: String) -> Self {
Self { message, kind }
}
#[getter]
fn message(&self) -> &str {
&self.message
}
#[getter]
fn kind(&self) -> &str {
&self.kind
}
fn __str__(&self) -> &str {
&self.message
}
fn __repr__(&self) -> String {
format!("VectorlessError('{}', kind='{}')", self.message, self.kind)
}
}
impl VectorlessError {
fn new(message: String, kind: &str) -> Self {
Self {
message,
kind: kind.to_string(),
}
}
}
impl From<VectorlessError> for PyErr {
fn from(err: VectorlessError) -> PyErr {
PyErr::new::<VectorlessError, _>((err.message, err.kind))
}
}
/// Convert vectorless errors to Python exceptions.
fn to_py_err(e: RustError) -> PyErr {
let message = e.to_string();
let kind = match &e {
RustError::DocumentNotFound(_) => "not_found",
RustError::Parse(_) => "parse",
RustError::Config(_) => "config",
RustError::Workspace(_) => "workspace",
RustError::Llm(_) => "llm",
_ => "unknown",
};
VectorlessError::new(message, kind).into()
}
/// Parse format string to DocumentFormat.
fn parse_format(format: &str) -> PyResult<DocumentFormat> {
match format.to_lowercase().as_str() {
"markdown" | "md" => Ok(DocumentFormat::Markdown),
"pdf" => Ok(DocumentFormat::Pdf),
_ => Err(PyErr::from(VectorlessError::new(
format!("Unknown format: {}. Supported: markdown, pdf", format),
"config",
))),
}
}
// ============================================================
// IndexOptions
// ============================================================
/// Options for controlling indexing behavior.
///
/// Args:
/// mode: Indexing mode - "default", "force", or "incremental".
/// generate_summaries: Whether to generate summaries. Default: True.
/// generate_description: Whether to generate document description. Default: False.
/// include_text: Whether to include node text in the tree. Default: True.
/// generate_ids: Whether to generate node IDs. Default: True.
#[pyclass(name = "IndexOptions", skip_from_py_object)]
#[derive(Clone)]
pub struct PyIndexOptions {
inner: IndexOptions,
}
#[pymethods]
impl PyIndexOptions {
#[new]
#[pyo3(signature = (mode="default", generate_summaries=true, generate_description=false, include_text=true, generate_ids=true))]
fn new(
mode: &str,
generate_summaries: bool,
generate_description: bool,
include_text: bool,
generate_ids: bool,
) -> PyResult<Self> {
let mut opts = IndexOptions::new();
match mode {
"default" => {}
"force" => opts = opts.with_mode(IndexMode::Force),
"incremental" => opts = opts.with_mode(IndexMode::Incremental),
_ => {
return Err(PyErr::from(VectorlessError::new(
format!("Unknown mode: {}. Supported: default, force, incremental", mode),
"config",
)))
}
}
opts.generate_summaries = generate_summaries;
opts.generate_description = generate_description;
opts.include_text = include_text;
opts.generate_ids = generate_ids;
Ok(Self { inner: opts })
}
fn __repr__(&self) -> String {
format!(
"IndexOptions(mode='{}', generate_summaries={}, generate_description={}, include_text={}, generate_ids={})",
match self.inner.mode {
IndexMode::Default => "default",
IndexMode::Force => "force",
IndexMode::Incremental => "incremental",
},
self.inner.generate_summaries,
self.inner.generate_description,
self.inner.include_text,
self.inner.generate_ids,
)
}
}
// ============================================================
// IndexContext
// ============================================================
/// Context for indexing a document.
///
/// Create using the static methods:
///
/// ```python
/// from vectorless import IndexContext
///
/// # Single file
/// ctx = IndexContext.from_path("./document.pdf")
///
/// # Multiple files
/// ctx = IndexContext.from_paths(["./a.pdf", "./b.md"])
///
/// # Directory
/// ctx = IndexContext.from_dir("./docs/")
///
/// # From text
/// ctx = IndexContext.from_content("# Title\\nContent...", "markdown").with_name("doc")
///
/// # From bytes
/// ctx = IndexContext.from_bytes(data, "pdf").with_name("doc")
/// ```
#[pyclass(name = "IndexContext")]
pub struct PyIndexContext {
inner: IndexContext,
}
#[pymethods]
impl PyIndexContext {
/// Create an IndexContext from a single file path.
#[staticmethod]
fn from_path(path: String) -> Self {
Self {
inner: IndexContext::from_path(&path),
}
}
/// Create an IndexContext from multiple file paths.
#[staticmethod]
fn from_paths(paths: Vec<String>) -> Self {
Self {
inner: IndexContext::from_paths(&paths),
}
}
/// Create an IndexContext from all supported files in a directory.
#[staticmethod]
fn from_dir(path: String) -> Self {
Self {
inner: IndexContext::from_dir(&path),
}
}
/// Create an IndexContext from text content.
#[staticmethod]
#[pyo3(signature = (content, format="markdown"))]
fn from_content(content: String, format: &str) -> PyResult<Self> {
let doc_format = parse_format(format)?;
let ctx = IndexContext::from_content(&content, doc_format);
Ok(Self { inner: ctx })
}
/// Create an IndexContext from binary data.
#[staticmethod]
fn from_bytes(data: Vec<u8>, format: &str) -> PyResult<Self> {
let doc_format = parse_format(format)?;
let ctx = IndexContext::from_bytes(data, doc_format);
Ok(Self { inner: ctx })
}
/// Set the document name (single-source only).
fn with_name(&self, name: String) -> Self {
let ctx = self.inner.clone().with_name(&name);
Self { inner: ctx }
}
/// Apply indexing options.
fn with_options(&self, options: &PyIndexOptions) -> Self {
let ctx = self.inner.clone().with_options(options.inner.clone());
Self { inner: ctx }
}
/// Set indexing mode.
fn with_mode(&self, mode: &str) -> PyResult<Self> {
let m = match mode {
"default" => IndexMode::Default,
"force" => IndexMode::Force,
"incremental" => IndexMode::Incremental,
_ => {
return Err(PyErr::from(VectorlessError::new(
format!("Unknown mode: {}. Supported: default, force, incremental", mode),
"config",
)))
}
};
let ctx = self.inner.clone().with_mode(m);
Ok(Self { inner: ctx })
}
fn __repr__(&self) -> String {
"IndexContext(...)".to_string()
}
}
// ============================================================
// StrategyPreference
// ============================================================
/// Retrieval strategy preference.
///
/// Controls how the engine searches the document tree.
///
/// ```python
/// from vectorless import QueryContext, StrategyPreference
///
/// # Force keyword-only (fastest, no LLM calls during search)
/// ctx = QueryContext("revenue").with_doc_id(doc_id).with_strategy(StrategyPreference.KEYWORD)
///
/// # Force LLM-guided navigation (most accurate, uses more tokens)
/// ctx = QueryContext("explain the architecture").with_doc_id(doc_id).with_strategy(StrategyPreference.LLM)
///
/// # Force hybrid (BM25 + LLM refinement)
/// ctx = QueryContext("growth trends").with_doc_id(doc_id).with_strategy(StrategyPreference.HYBRID)
/// ```
#[pyclass(name = "StrategyPreference", skip_from_py_object)]
#[derive(Clone)]
pub struct PyStrategyPreference {
inner: StrategyPreference,
}
#[pymethods]
impl PyStrategyPreference {
/// Auto-select based on query complexity (default).
#[classattr]
const AUTO: PyStrategyPreference = PyStrategyPreference {
inner: StrategyPreference::Auto,
};
/// Force keyword-based strategy (fast, no LLM during search).
#[classattr]
const KEYWORD: PyStrategyPreference = PyStrategyPreference {
inner: StrategyPreference::ForceKeyword,
};
/// Force LLM-guided navigation (deep reasoning).
#[classattr]
const LLM: PyStrategyPreference = PyStrategyPreference {
inner: StrategyPreference::ForceLlm,
};
/// Force hybrid strategy (BM25 + LLM refinement).
#[classattr]
const HYBRID: PyStrategyPreference = PyStrategyPreference {
inner: StrategyPreference::ForceHybrid,
};
/// Force cross-document strategy (multi-document retrieval).
#[classattr]
const CROSS_DOCUMENT: PyStrategyPreference = PyStrategyPreference {
inner: StrategyPreference::ForceCrossDocument,
};
/// Force page-range strategy (filter by page range).
#[classattr]
const PAGE_RANGE: PyStrategyPreference = PyStrategyPreference {
inner: StrategyPreference::ForcePageRange,
};
fn __repr__(&self) -> String {
let name = match self.inner {
StrategyPreference::Auto => "AUTO",
StrategyPreference::ForceKeyword => "KEYWORD",
StrategyPreference::ForceLlm => "LLM",
StrategyPreference::ForceHybrid => "HYBRID",
StrategyPreference::ForceCrossDocument => "CROSS_DOCUMENT",
StrategyPreference::ForcePageRange => "PAGE_RANGE",
};
format!("StrategyPreference.{}", name)
}
}
// ============================================================
// QueryContext
// ============================================================
/// Context for a query operation.
///
/// ```python
/// from vectorless import QueryContext
///
/// # Query a single document
/// ctx = QueryContext("What is the total revenue?").with_doc_id(doc_id)
///
/// # Query multiple documents
/// ctx = QueryContext("What is the architecture?").with_doc_ids(["doc-1", "doc-2"])
///
/// # Query entire workspace
/// ctx = QueryContext("Explain the algorithm")
/// ```
#[pyclass(name = "QueryContext")]
pub struct PyQueryContext {
inner: QueryContext,
}
#[pymethods]
impl PyQueryContext {
/// Create a new query context (defaults to workspace scope).
#[new]
fn new(query: String) -> Self {
Self {
inner: QueryContext::new(&query),
}
}
/// Set scope to a single document.
fn with_doc_id(&self, doc_id: String) -> Self {
let ctx = self.inner.clone().with_doc_id(&doc_id);
Self { inner: ctx }
}
/// Set scope to multiple documents.
fn with_doc_ids(&self, doc_ids: Vec<String>) -> Self {
let ctx = self.inner.clone().with_doc_ids(doc_ids);
Self { inner: ctx }
}
/// Set scope to entire workspace.
fn with_workspace(&self) -> Self {
let ctx = self.inner.clone().with_workspace();
Self { inner: ctx }
}
/// Set the maximum tokens for the result content.
fn with_max_tokens(&self, tokens: usize) -> Self {
let ctx = self.inner.clone().with_max_tokens(tokens);
Self { inner: ctx }
}
/// Set whether to include the reasoning chain.
fn with_include_reasoning(&self, include: bool) -> Self {
let ctx = self.inner.clone().with_include_reasoning(include);
Self { inner: ctx }
}
/// Set the maximum tree traversal depth.
fn with_depth_limit(&self, depth: usize) -> Self {
let ctx = self.inner.clone().with_depth_limit(depth);
Self { inner: ctx }
}
/// Set the retrieval strategy.
///
/// Args:
/// strategy: A StrategyPreference constant, e.g. StrategyPreference.LLM.
fn with_strategy(&self, strategy: &PyStrategyPreference) -> Self {
let ctx = self.inner.clone().with_strategy(strategy.inner);
Self { inner: ctx }
}
fn __repr__(&self) -> String {
"QueryContext(...)".to_string()
}
}
// ============================================================
// QueryResultItem
// ============================================================
/// A single document's query result.
#[pyclass(name = "QueryResultItem")]
pub struct PyQueryResultItem {
inner: QueryResultItem,
}
#[pymethods]
impl PyQueryResultItem {
/// The document ID.
#[getter]
fn doc_id(&self) -> &str {
&self.inner.doc_id
}
/// The retrieved content.
#[getter]
fn content(&self) -> &str {
&self.inner.content
}
/// Relevance score (0.0 to 1.0).
#[getter]
fn score(&self) -> f32 {
self.inner.score
}
/// Node IDs that matched.
#[getter]
fn node_ids(&self) -> Vec<String> {
self.inner.node_ids.clone()
}
fn __repr__(&self) -> String {
format!(
"QueryResultItem(doc_id='{}', score={:.2}, content_len={})",
self.inner.doc_id,
self.inner.score,
self.inner.content.len()
)
}
}
// ============================================================
// FailedItem
// ============================================================
/// A failed item in a batch operation.
#[pyclass(name = "FailedItem")]
pub struct PyFailedItem {
inner: FailedItem,
}
#[pymethods]
impl PyFailedItem {
/// Source description.
#[getter]
fn source(&self) -> &str {
&self.inner.source
}
/// Error message.
#[getter]
fn error(&self) -> &str {
&self.inner.error
}
fn __repr__(&self) -> String {
format!(
"FailedItem(source='{}', error='{}')",
self.inner.source, self.inner.error
)
}
}
// ============================================================
// QueryResult
// ============================================================
/// Result of a document query.
#[pyclass(name = "QueryResult")]
pub struct PyQueryResult {
inner: QueryResult,
}
#[pymethods]
impl PyQueryResult {
/// Result items (one per document).
#[getter]
fn items(&self) -> Vec<PyQueryResultItem> {
self.inner
.items
.iter()
.map(|i| PyQueryResultItem {
inner: i.clone(),
})
.collect()
}
/// Get the first (single-doc) result item.
fn single(&self) -> Option<PyQueryResultItem> {
self.inner.single().map(|i| PyQueryResultItem {
inner: i.clone(),
})
}
/// Number of result items.
fn __len__(&self) -> usize {
self.inner.len()
}
/// Whether any documents failed.
fn has_failures(&self) -> bool {
self.inner.has_failures()
}
/// Failed items.
#[getter]
fn failed(&self) -> Vec<PyFailedItem> {
self.inner
.failed
.iter()
.map(|f| PyFailedItem { inner: f.clone() })
.collect()
}
fn __repr__(&self) -> String {
format!(
"QueryResult(items={}, failed={})",
self.inner.len(),
self.inner.failed.len()
)
}
}
// ============================================================
// IndexMetrics
// ============================================================
/// Indexing pipeline metrics.
#[pyclass(name = "IndexMetrics")]
pub struct PyIndexMetrics {
inner: IndexMetrics,
}
#[pymethods]
impl PyIndexMetrics {
/// Total indexing time (ms).
#[getter]
fn total_time_ms(&self) -> u64 {
self.inner.total_time_ms()
}
/// Parse stage duration (ms).
#[getter]
fn parse_time_ms(&self) -> u64 {
self.inner.parse_time_ms
}
/// Build stage duration (ms).
#[getter]
fn build_time_ms(&self) -> u64 {
self.inner.build_time_ms
}
/// Enhance (summary) stage duration (ms).
#[getter]
fn enhance_time_ms(&self) -> u64 {
self.inner.enhance_time_ms
}
/// Number of nodes processed.
#[getter]
fn nodes_processed(&self) -> usize {
self.inner.nodes_processed
}
/// Number of summaries successfully generated.
#[getter]
fn summaries_generated(&self) -> usize {
self.inner.summaries_generated
}
/// Number of summaries that failed to generate.
#[getter]
fn summaries_failed(&self) -> usize {
self.inner.summaries_failed
}
/// Number of LLM calls made.
#[getter]
fn llm_calls(&self) -> usize {
self.inner.llm_calls
}
/// Total tokens generated by LLM.
#[getter]
fn total_tokens_generated(&self) -> usize {
self.inner.total_tokens_generated
}
/// Number of topics in reasoning index.
#[getter]
fn topics_indexed(&self) -> usize {
self.inner.topics_indexed
}
/// Number of keywords in reasoning index.
#[getter]
fn keywords_indexed(&self) -> usize {
self.inner.keywords_indexed
}
fn __repr__(&self) -> String {
format!(
"IndexMetrics(total={}ms, summaries={}, failed={}, llm_calls={})",
self.inner.total_time_ms(),
self.inner.summaries_generated,
self.inner.summaries_failed,
self.inner.llm_calls,
)
}
}
// ============================================================
// IndexItem / IndexResult
// ============================================================
/// A single indexed document item.
#[pyclass(name = "IndexItem")]
pub struct PyIndexItem {
inner: IndexItem,
}
#[pymethods]
impl PyIndexItem {
#[getter]
fn doc_id(&self) -> &str {
&self.inner.doc_id
}
#[getter]
fn name(&self) -> &str {
&self.inner.name
}
#[getter]
fn format(&self) -> String {
format!("{:?}", self.inner.format).to_lowercase()
}
#[getter]
fn description(&self) -> Option<&str> {
self.inner.description.as_deref()
}
#[getter]
fn page_count(&self) -> Option<usize> {
self.inner.page_count
}
/// Indexing pipeline metrics (timing, LLM usage, etc.).
#[getter]
fn metrics(&self) -> Option<PyIndexMetrics> {
self.inner.metrics.as_ref().map(|m| PyIndexMetrics { inner: m.clone() })
}
fn __repr__(&self) -> String {
format!(
"IndexItem(doc_id='{}', name='{}')",
self.inner.doc_id, self.inner.name
)
}
}
/// Result of a document indexing operation.
#[pyclass(name = "IndexResult")]
pub struct PyIndexResult {
inner: IndexResult,
}
#[pymethods]
impl PyIndexResult {
/// The document ID (convenience for single-document indexing).
#[getter]
fn doc_id(&self) -> Option<String> {
self.inner.doc_id().map(|s| s.to_string())
}
/// All indexed items.
#[getter]
fn items(&self) -> Vec<PyIndexItem> {
self.inner
.items
.iter()
.map(|i| PyIndexItem { inner: i.clone() })
.collect()
}
/// Failed items.
#[getter]
fn failed(&self) -> Vec<PyFailedItem> {
self.inner
.failed
.iter()
.map(|f| PyFailedItem { inner: f.clone() })
.collect()
}
/// Whether any items failed.
fn has_failures(&self) -> bool {
self.inner.has_failures()
}
/// Total number of items (successful + failed).
fn total(&self) -> usize {
self.inner.total()
}
fn __len__(&self) -> usize {
self.inner.len()
}
fn __repr__(&self) -> String {
format!(
"IndexResult(doc_id={:?}, count={}, failed={})",
self.inner.doc_id(),
self.inner.items.len(),
self.inner.failed.len()
)
}
}
// ============================================================
// DocumentInfo
// ============================================================
/// Information about an indexed document.
#[pyclass(name = "DocumentInfo")]
pub struct PyDocumentInfo {
inner: DocumentInfo,
}
#[pymethods]
impl PyDocumentInfo {
#[getter]
fn id(&self) -> &str {
&self.inner.id
}
#[getter]
fn name(&self) -> &str {
&self.inner.name
}
#[getter]
fn format(&self) -> &str {
&self.inner.format
}
#[getter]
fn description(&self) -> Option<&str> {
self.inner.description.as_deref()
}
#[getter]
fn page_count(&self) -> Option<usize> {
self.inner.page_count
}
#[getter]
fn line_count(&self) -> Option<usize> {
self.inner.line_count
}
fn __repr__(&self) -> String {
format!(
"DocumentInfo(id='{}', name='{}', format='{}')",
self.inner.id, self.inner.name, self.inner.format
)
}
}
// ============================================================
// DocumentGraph types
// ============================================================
use ::vectorless::graph::{DocumentGraph, DocumentGraphNode, EdgeEvidence, GraphEdge, WeightedKeyword};
/// A keyword with weight from document analysis.
#[pyclass(name = "WeightedKeyword")]
pub struct PyWeightedKeyword {
inner: WeightedKeyword,
}
#[pymethods]
impl PyWeightedKeyword {
#[getter]
fn keyword(&self) -> &str {
&self.inner.keyword
}
#[getter]
fn weight(&self) -> f32 {
self.inner.weight
}
fn __repr__(&self) -> String {
format!("WeightedKeyword('{}', weight={:.2})", self.inner.keyword, self.inner.weight)
}
}
/// Evidence for a cross-document connection.
#[pyclass(name = "EdgeEvidence")]
pub struct PyEdgeEvidence {
inner: EdgeEvidence,
}
#[pymethods]
impl PyEdgeEvidence {
/// Number of shared keywords.
#[getter]
fn shared_keyword_count(&self) -> usize {
self.inner.shared_keyword_count
}
/// Jaccard similarity of keyword sets.
#[getter]
fn keyword_jaccard(&self) -> f32 {
self.inner.keyword_jaccard
}
/// Shared keywords with weights.
#[getter]
fn shared_keywords(&self) -> Vec<(String, f32, f32)> {
self.inner
.shared_keywords
.iter()
.map(|sk| (sk.keyword.clone(), sk.source_weight, sk.target_weight))
.collect()
}
fn __repr__(&self) -> String {
format!(
"EdgeEvidence(shared={}, jaccard={:.2})",
self.inner.shared_keyword_count, self.inner.keyword_jaccard
)
}
}
/// An edge representing a relationship between two documents.
#[pyclass(name = "GraphEdge")]
pub struct PyGraphEdge {
inner: GraphEdge,
}
#[pymethods]
impl PyGraphEdge {
/// Target document ID.
#[getter]
fn target_doc_id(&self) -> &str {
&self.inner.target_doc_id
}
/// Edge weight (connection strength).
#[getter]
fn weight(&self) -> f32 {
self.inner.weight
}
/// Evidence for this connection.
#[getter]
fn evidence(&self) -> PyEdgeEvidence {
PyEdgeEvidence {
inner: self.inner.evidence.clone(),
}
}
fn __repr__(&self) -> String {
format!(
"GraphEdge(target='{}', weight={:.2})",
self.inner.target_doc_id, self.inner.weight
)
}
}
/// A node in the document graph representing an indexed document.
#[pyclass(name = "DocumentGraphNode")]
pub struct PyDocumentGraphNode {
inner: DocumentGraphNode,
}
#[pymethods]
impl PyDocumentGraphNode {
#[getter]
fn doc_id(&self) -> &str {
&self.inner.doc_id
}
#[getter]
fn title(&self) -> &str {
&self.inner.title
}
#[getter]
fn format(&self) -> &str {
&self.inner.format
}
#[getter]
fn node_count(&self) -> usize {
self.inner.node_count
}
/// Top keywords extracted from the document.
#[getter]
fn top_keywords(&self) -> Vec<PyWeightedKeyword> {
self.inner
.top_keywords
.iter()
.map(|kw| PyWeightedKeyword {
inner: kw.clone(),
})
.collect()
}
fn __repr__(&self) -> String {
format!(
"DocumentGraphNode(doc_id='{}', title='{}')",
self.inner.doc_id, self.inner.title
)
}
}
/// Cross-document relationship graph.
///
/// Automatically rebuilt after indexing. Connects documents
/// that share keywords via Jaccard similarity.
#[pyclass(name = "DocumentGraph")]
pub struct PyDocumentGraph {
inner: DocumentGraph,
}
#[pymethods]
impl PyDocumentGraph {
/// Number of document nodes.
fn node_count(&self) -> usize {
self.inner.node_count()
}
/// Number of relationship edges.
fn edge_count(&self) -> usize {
self.inner.edge_count()
}
/// Get a document node by ID.
fn get_node(&self, doc_id: String) -> Option<PyDocumentGraphNode> {
self.inner.get_node(&doc_id).map(|n| PyDocumentGraphNode {
inner: n.clone(),
})
}
/// Get all document IDs in the graph.
fn doc_ids(&self) -> Vec<String> {
self.inner.doc_ids().map(|s| s.to_string()).collect()
}
/// Get edges (neighbors) for a document.