pseek 2.4.0__tar.gz → 2.5.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pseek
3
- Version: 2.4.0
3
+ Version: 2.5.0
4
4
  Summary: Pseek is a Python library to search files, folders, and text
5
5
  Author-email: Arian <ariannasiri86@gmail.com>
6
6
  License-Expression: MIT
@@ -12,6 +12,7 @@ Requires-Dist: click==8.1.8
12
12
  Requires-Dist: lark==1.2.2
13
13
  Requires-Dist: py7zr==1.0.0
14
14
  Requires-Dist: rarfile==4.2
15
+ Requires-Dist: rapidfuzz==3.13.0
15
16
  Dynamic: license-file
16
17
 
17
18
  # Pseek
@@ -95,6 +96,8 @@ pseek "error\d+" --regex
95
96
  | `--word` | Match the whole word only (except when `--expr` is enabled, in which case you can make it match whole word by putting `w` before term: `w"foo"`) |
96
97
  | `--expr` | Enable to write conditions in the query. Example: `r"foo.*bar" and ("bar" or "baz") and not "qux"` (To use regex, word, and case-sensitive features, you can use the prefixes `r`, `w`, and `c` before terms. Allowed modes: `r`, `w`, `c`, `wc`, `cw`, `rc`, `cr`. Examples: `r"foo.*bar"`, `wc"Foo"`, `cr".*Foo"`, ...) |
97
98
  | `--timeout` | To stop the search after a specified period of time (Seconds) |
99
+ | `--fuzzy` | Enable fuzzy search (Highlighting and counting matches are disabled in this mode if `--word` is not enabled to prevent the program from slowing down) |
100
+ | `--fuzzy_level` | Similarity threshold from 0 to 99 for fuzzy search (default: `80`) |
98
101
  | `--max-size`, `--min-size` | Specify maximum and minimum sizes for files and directories |
99
102
  | `--archive` | Enable search within archive files (e.g. `zip`, `rar`, `7z`, `gz`, `bz2`, `xz`, `tar`, `tar.gz`, `tar.bz2`, `tar.xz`) |
100
103
  | `--arc-ext`, `--arc-ee` | Filter by file extension inside archive files |
@@ -79,6 +79,8 @@ pseek "error\d+" --regex
79
79
  | `--word` | Match the whole word only (except when `--expr` is enabled, in which case you can make it match whole word by putting `w` before term: `w"foo"`) |
80
80
  | `--expr` | Enable to write conditions in the query. Example: `r"foo.*bar" and ("bar" or "baz") and not "qux"` (To use regex, word, and case-sensitive features, you can use the prefixes `r`, `w`, and `c` before terms. Allowed modes: `r`, `w`, `c`, `wc`, `cw`, `rc`, `cr`. Examples: `r"foo.*bar"`, `wc"Foo"`, `cr".*Foo"`, ...) |
81
81
  | `--timeout` | To stop the search after a specified period of time (Seconds) |
82
+ | `--fuzzy` | Enable fuzzy search (Highlighting and counting matches are disabled in this mode if `--word` is not enabled to prevent the program from slowing down) |
83
+ | `--fuzzy_level` | Similarity threshold from 0 to 99 for fuzzy search (default: `80`) |
82
84
  | `--max-size`, `--min-size` | Specify maximum and minimum sizes for files and directories |
83
85
  | `--archive` | Enable search within archive files (e.g. `zip`, `rar`, `7z`, `gz`, `bz2`, `xz`, `tar`, `tar.gz`, `tar.bz2`, `tar.xz`) |
84
86
  | `--arc-ext`, `--arc-ee` | Filter by file extension inside archive files |
@@ -23,7 +23,6 @@ def run_search_process(file, directory, content, search_instance):
23
23
  click.echo(click.style(message, fg='red'))
24
24
 
25
25
 
26
-
27
26
  @click.command()
28
27
  @click.argument('query')
29
28
  @click.option('-p', '--path', type=click.Path(exists=True, file_okay=False, dir_okay=True),
@@ -52,6 +51,9 @@ def run_search_process(file, directory, content, search_instance):
52
51
  'Examples: r"foo.*bar", wc"Foo", cr".*Foo", ...)')
53
52
  @click.option('--timeout', type=click.INT,
54
53
  help='To stop the search after a specified period of time (Seconds)')
54
+ @click.option('--fuzzy', is_flag=True, help='Enable fuzzy search (approximate matching).')
55
+ @click.option('--fuzzy-level', type=click.IntRange(0, 99), default=80, show_default=True,
56
+ help='Similarity threshold from 0 to 99 for fuzzy search.')
55
57
  # Extension filters
56
58
  @click.option('--ext', multiple=True, type=click.STRING,
57
59
  help='Include files with these extensions. Example: --ext py --ext js')
@@ -89,12 +91,29 @@ def run_search_process(file, directory, content, search_instance):
89
91
  @click.option('--full-path', is_flag=True, help='Display full paths for results.')
90
92
  @click.option('--no-content', is_flag=True, help='Only display files path for content search.')
91
93
  def search(query, path, file, directory, content, case_sensitive, ext, exclude_ext, regex, include, exclude,
92
- re_include, re_exclude, word, expr, timeout, max_size, min_size, archive, arc_ext, arc_ee, arc_inc,
93
- arc_exc, arc_max, arc_min, rarfb, full_path, no_content):
94
+ re_include, re_exclude, word, expr, timeout, fuzzy, fuzzy_level, max_size, min_size, archive, arc_ext,
95
+ arc_ee, arc_inc, arc_exc, arc_max, arc_min, rarfb, full_path, no_content):
94
96
  """Search for files, directories, and file content based on the query."""
95
97
 
96
98
  check_rar_backend(archive, rarfb, query)
97
99
 
100
+ if not expr and fuzzy:
101
+ if not word:
102
+ click.echo(
103
+ click.style(
104
+ "Warning: Fuzzy substring highlighting and counting matches are disabled to improve performance.\n",
105
+ fg="yellow"
106
+ )
107
+ )
108
+ else:
109
+ click.echo(
110
+ click.style(
111
+ 'Warning: When using "--fuzzy" and "--word", it is better to have the query be a word and '
112
+ 'not a phrase, as this will cause errors in the results.\n',
113
+ fg="yellow"
114
+ )
115
+ )
116
+
98
117
  # If no search type is specified, search in all types.
99
118
  if not any((file, directory, content)):
100
119
  file = directory = content = True
@@ -113,6 +132,8 @@ def search(query, path, file, directory, content, case_sensitive, ext, exclude_e
113
132
  re_exclude=re_exclude,
114
133
  whole_word=word,
115
134
  expr=expr,
135
+ fuzzy=fuzzy,
136
+ fuzzy_level=fuzzy_level,
116
137
  max_size=max_size,
117
138
  min_size=min_size,
118
139
  archive=archive,
@@ -3,6 +3,7 @@ import sys
3
3
  import click
4
4
  from lark import Lark, Transformer
5
5
  from .utils import compile_regex
6
+ from rapidfuzz import fuzz
6
7
 
7
8
 
8
9
  class ExprNode:
@@ -13,31 +14,64 @@ class ExprNode:
13
14
 
14
15
  class TermNode(ExprNode):
15
16
  """Node representing a single search term"""
16
- def __init__(self, term: str, regex, whole_word, case_sensitive):
17
+ def __init__(self, term: str, regex, whole_word, case_sensitive, fuzzy, fuzzy_level):
17
18
  self.raw_term = term
18
19
  self.whole_word = whole_word
19
20
  self.case_sensitive = case_sensitive
21
+ self.fuzzy = fuzzy
22
+ self.fuzzy_level = fuzzy_level
20
23
 
21
- flags = 0 if case_sensitive else re.IGNORECASE # Adjust case sensitivity
24
+ if not fuzzy:
25
+ flags = 0 if case_sensitive else re.IGNORECASE # Adjust case sensitivity
22
26
 
23
- # Build the regex pattern
24
- if not regex:
25
- term = re.escape(term) # Escape if not regex
26
- # Apply whole-word matching only if not using regex (or if desired behavior is defined)
27
- if whole_word:
28
- term = r'\b' + term + r'\b'
27
+ # Build the regex pattern
28
+ if not regex:
29
+ term = re.escape(term) # Escape if not regex
30
+ # Apply whole-word matching only if not using regex (or if desired behavior is defined)
31
+ if whole_word:
32
+ term = r'\b' + term + r'\b'
29
33
 
30
- self.pattern = compile_regex(term, flags) # Precompile the regex pattern for performance
34
+ self.pattern = compile_regex(term, flags) # Precompile the regex pattern for performance
31
35
 
32
36
  def evaluate(self, text: str) -> bool:
33
- return bool(self.pattern.search(text))
37
+ if not self.fuzzy:
38
+ return bool(self.pattern.search(text))
39
+
40
+ # Fuzzy search mode
41
+ text_cmp = text if self.case_sensitive else text.lower()
42
+ term = self.raw_term if self.case_sensitive else self.raw_term.lower()
43
+
44
+ if self.whole_word:
45
+ words = re.findall(r'\w+', text_cmp)
46
+ return any(fuzz.ratio(term, word) >= self.fuzzy_level for word in words)
47
+ else:
48
+ # Use the correct method depending on the len of str to increase accuracy and avoid illogical matching
49
+ if len(text_cmp) > len(term):
50
+ score = fuzz.partial_ratio(term, text_cmp)
51
+ else:
52
+ score = fuzz.ratio(term, text_cmp)
53
+ return score >= self.fuzzy_level
54
+
34
55
 
35
56
  def count_matches(self, text: str) -> int:
36
- """Count how many times the pattern appears in the text"""
37
- return len(list(self.pattern.finditer(text)))
57
+ """Count how many times the pattern or fuzzy term appears in the text"""
58
+ if not self.fuzzy:
59
+ return len(list(self.pattern.finditer(text)))
60
+
61
+ text_cmp = text if self.case_sensitive else text.lower()
62
+ term = self.raw_term if self.case_sensitive else self.raw_term.lower()
63
+
64
+ if self.whole_word:
65
+ words = re.findall(r'\w+', text_cmp)
66
+ return sum(1 for word in words if fuzz.ratio(term, word) >= self.fuzzy_level)
67
+
68
+ # Optionally could implement a sliding window here, but it's expensive
69
+ return 0
38
70
 
39
71
  def get_binary_pattern(self) -> re.Pattern:
40
72
  """Return a compiled binary regex pattern"""
73
+ if self.fuzzy:
74
+ raise NotImplementedError("Binary pattern is not supported for fuzzy matching.")
41
75
  return re.compile(self.pattern.pattern.encode("utf-8"), self.pattern.flags)
42
76
 
43
77
 
@@ -99,8 +133,10 @@ PREFIXED_STRING: /(r|c|w|rc|cr|cw|wc)"([^"\\]|\\.)*"/
99
133
 
100
134
  class TreeToExpr(Transformer):
101
135
  """Transform parsed tree into expression tree (ExprNode subclasses)"""
102
- def __init__(self):
136
+ def __init__(self, fuzzy, fuzzy_level):
103
137
  super().__init__()
138
+ self.fuzzy = fuzzy
139
+ self.fuzzy_level = fuzzy_level
104
140
 
105
141
  def string(self, s):
106
142
  """ Match normal quoted string: "foo" """
@@ -109,7 +145,9 @@ class TreeToExpr(Transformer):
109
145
  term,
110
146
  False,
111
147
  False,
112
- False
148
+ False,
149
+ self.fuzzy,
150
+ self.fuzzy_level
113
151
  )
114
152
 
115
153
  def prefixed_string(self, s):
@@ -122,6 +160,8 @@ class TreeToExpr(Transformer):
122
160
  regex='r' in prefix,
123
161
  whole_word='w' in prefix,
124
162
  case_sensitive='c' in prefix,
163
+ fuzzy=self.fuzzy,
164
+ fuzzy_level=self.fuzzy_level
125
165
  )
126
166
 
127
167
  def and_expr(self, args):
@@ -134,48 +174,72 @@ class TreeToExpr(Transformer):
134
174
  return NotNode(args[0])
135
175
 
136
176
 
137
- def parse_query_expression(query: str, expr, regex, whole_word, case_sensitive) -> ExprNode:
177
+ def parse_query_expression(query: str, expr, regex, whole_word, case_sensitive, fuzzy, fuzzy_level) -> ExprNode:
138
178
  """
139
179
  Function to parse the query and return expression tree.
140
180
  If expr is False, treat the whole query as a single term.
141
181
  """
142
182
 
143
183
  if not expr:
144
- return TermNode(query, regex, whole_word, case_sensitive)
184
+ return TermNode(query, regex, whole_word, case_sensitive, fuzzy, fuzzy_level)
145
185
 
146
186
  # Otherwise, parse using Lark
147
187
  parser = Lark(query_grammar, parser="lalr")
148
188
  try:
149
189
  tree = parser.parse(query)
150
- return TreeToExpr().transform(tree)
190
+ return TreeToExpr(fuzzy, fuzzy_level).transform(tree)
151
191
  except Exception as e:
152
192
  click.echo(click.style("Query parser error:\n\n", fg='red') + str(e))
153
193
  sys.exit(1)
154
194
 
155
195
 
156
- def highlight_text_safe(expr: ExprNode, text: str) -> str:
196
+ def highlight_text(expr: ExprNode, text: str, fuzzy: bool) -> str:
197
+ """
198
+ Highlight matching parts of the text.
199
+ Only highlights fuzzy matches when whole_word=True.
200
+ """
157
201
  matches = []
158
202
 
159
203
  def collect_matches(node):
160
204
  if isinstance(node, TermNode):
161
- for match in node.pattern.finditer(text):
162
- matches.append((match.start(), match.end()))
163
- elif isinstance(node, (AndNode, OrNode)):
205
+ # Skip fuzzy highlight if whole_word is False
206
+ if node.fuzzy:
207
+ if not node.whole_word:
208
+ return # skip highlighting
209
+ text_cmp = text if node.case_sensitive else text.lower()
210
+ term = node.raw_term if node.case_sensitive else node.raw_term.lower()
211
+
212
+ # collect word matches
213
+ for match in re.finditer(r'\w+', text_cmp):
214
+ word = match.group()
215
+ if fuzz.ratio(term, word) >= node.fuzzy_level:
216
+ matches.append((match.start(), match.end()))
217
+ else:
218
+ for match in node.pattern.finditer(text):
219
+ matches.append((match.start(), match.end()))
220
+ elif isinstance(node, AndNode) or isinstance(node, OrNode):
164
221
  collect_matches(node.left)
165
222
  collect_matches(node.right)
166
223
  elif isinstance(node, NotNode):
167
224
  collect_matches(node.child)
168
225
 
226
+ # If fuzzy is enabled but whole_word is False, return plain text
227
+ if fuzzy and isinstance(expr, TermNode) and not expr.whole_word:
228
+ return text
229
+
169
230
  collect_matches(expr)
170
231
 
171
- # Remove overlaps (for example, if one match was inside another match)
232
+ # Sort and merge overlapping matches (for example, if one match was inside another match)
172
233
  matches.sort() # sort by start position
173
234
  merged = []
174
235
  for start, end in matches:
175
236
  if not merged or start >= merged[-1][1]: # no overlap
176
237
  merged.append((start, end))
238
+ else:
239
+ # Merge overlapping
240
+ merged[-1] = (merged[-1][0], max(merged[-1][1], end))
177
241
 
178
- # Create the final text with highlight
242
+ # Build highlighted text
179
243
  result = []
180
244
  last = 0
181
245
  for start, end in merged:
@@ -2,7 +2,7 @@ import mmap
2
2
  import click
3
3
  from pathlib import Path
4
4
  from .utils import compile_regex, get_archive_path_size, try_decode
5
- from .parser import parse_query_expression, TermNode, highlight_text_safe
5
+ from .parser import parse_query_expression, TermNode, highlight_text
6
6
  from concurrent.futures import ThreadPoolExecutor
7
7
  import zipfile
8
8
  import py7zr
@@ -30,8 +30,8 @@ EXCLUDED_EXTENSIONS = (
30
30
 
31
31
  class Search:
32
32
  def __init__(self, base_path, query, case_sensitive, ext, exclude_ext, regex, include, exclude, re_include,
33
- re_exclude, whole_word, expr, max_size, min_size, archive, arc_ext, arc_ee, arc_inc, arc_exc,
34
- arc_max, arc_min, full_path, no_content):
33
+ re_exclude, whole_word, expr, fuzzy, fuzzy_level, max_size, min_size, archive, arc_ext, arc_ee,
34
+ arc_inc, arc_exc, arc_max, arc_min, full_path, no_content):
35
35
  """Initialize search parameters"""
36
36
  self.base_path = Path(base_path)
37
37
  self.query = query
@@ -45,6 +45,8 @@ class Search:
45
45
  self.re_exclude = compile_regex(re_exclude)
46
46
  self.whole_word = whole_word
47
47
  self.expr = expr
48
+ self.fuzzy = fuzzy
49
+ self.fuzzy_level = fuzzy_level
48
50
  self.max_size = max_size
49
51
  self.min_size = min_size
50
52
  self.archive = archive
@@ -301,7 +303,8 @@ class Search:
301
303
 
302
304
  def search(self, search_type: str):
303
305
  """Main search function. search_type can be 'file', 'directory' or 'content'"""
304
- pattern = parse_query_expression(self.query, self.expr, self.regex, self.whole_word, self.case_sensitive)
306
+ pattern = parse_query_expression(self.query, self.expr, self.regex, self.whole_word, self.case_sensitive,
307
+ self.fuzzy, self.fuzzy_level)
305
308
 
306
309
  if search_type in ('file', 'directory'):
307
310
  matches = []
@@ -320,14 +323,14 @@ class Search:
320
323
 
321
324
  if pattern.evaluate(p.name) and not (search_type == 'directory' and p_resolved.is_file()):
322
325
  # Highlight matched query in the name
323
- highlighted_name = highlight_text_safe(pattern, p.name)
326
+ highlighted_name = highlight_text(pattern, p.name, self.fuzzy)
324
327
  matches.append(f'{p_parent}\\{highlighted_name}')
325
328
 
326
329
  # Search for files and directories name inside archive files if archive is active
327
330
  if self.archive and p_ext in ('zip', 'rar', '7z', 'tar', 'tar.gz', 'tar.bz2', 'tar.xz'):
328
331
  for name in self.extract_names_from_archive(p_resolved, search_type):
329
332
  if pattern.evaluate(name.name):
330
- highlighted_name = highlight_text_safe(pattern, name.name)
333
+ highlighted_name = highlight_text(pattern, name.name, self.fuzzy)
331
334
  matches.append(f'{p_parent}\\{p.name}::{name.parent}\\{highlighted_name}')
332
335
  else: # content search
333
336
  # Use dictionary: key: file path (colored), value: list of line matches
@@ -375,7 +378,7 @@ class Search:
375
378
 
376
379
  count = pattern.count_matches(line) if isinstance(pattern, TermNode) else 0
377
380
  # Highlight the matching parts in green
378
- highlighted = highlight_text_safe(pattern, line)
381
+ highlighted = highlight_text(pattern, line, self.fuzzy)
379
382
  # Show a note if the pattern repeats 3 or more times
380
383
  count_query = f' - Repeated {count} times' if count >= 3 else ''
381
384
  # Format the output line with line number and highlighted matches
@@ -427,7 +430,7 @@ class Search:
427
430
  return
428
431
  count = pattern.count_matches(line_decoded) if isinstance(pattern, TermNode) else 0
429
432
  # Highlight the matching parts in green
430
- highlighted = highlight_text_safe(pattern, line_decoded)
433
+ highlighted = highlight_text(pattern, line_decoded, self.fuzzy)
431
434
  # Show a note if the pattern repeats 3 or more times
432
435
  count_query = f' - Repeated {count} times' if count >= 3 else ''
433
436
  # Format the output line with line number and highlighted matches
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pseek
3
- Version: 2.4.0
3
+ Version: 2.5.0
4
4
  Summary: Pseek is a Python library to search files, folders, and text
5
5
  Author-email: Arian <ariannasiri86@gmail.com>
6
6
  License-Expression: MIT
@@ -12,6 +12,7 @@ Requires-Dist: click==8.1.8
12
12
  Requires-Dist: lark==1.2.2
13
13
  Requires-Dist: py7zr==1.0.0
14
14
  Requires-Dist: rarfile==4.2
15
+ Requires-Dist: rapidfuzz==3.13.0
15
16
  Dynamic: license-file
16
17
 
17
18
  # Pseek
@@ -95,6 +96,8 @@ pseek "error\d+" --regex
95
96
  | `--word` | Match the whole word only (except when `--expr` is enabled, in which case you can make it match whole word by putting `w` before term: `w"foo"`) |
96
97
  | `--expr` | Enable to write conditions in the query. Example: `r"foo.*bar" and ("bar" or "baz") and not "qux"` (To use regex, word, and case-sensitive features, you can use the prefixes `r`, `w`, and `c` before terms. Allowed modes: `r`, `w`, `c`, `wc`, `cw`, `rc`, `cr`. Examples: `r"foo.*bar"`, `wc"Foo"`, `cr".*Foo"`, ...) |
97
98
  | `--timeout` | To stop the search after a specified period of time (Seconds) |
99
+ | `--fuzzy` | Enable fuzzy search (Highlighting and counting matches are disabled in this mode if `--word` is not enabled to prevent the program from slowing down) |
100
+ | `--fuzzy_level` | Similarity threshold from 0 to 99 for fuzzy search (default: `80`) |
98
101
  | `--max-size`, `--min-size` | Specify maximum and minimum sizes for files and directories |
99
102
  | `--archive` | Enable search within archive files (e.g. `zip`, `rar`, `7z`, `gz`, `bz2`, `xz`, `tar`, `tar.gz`, `tar.bz2`, `tar.xz`) |
100
103
  | `--arc-ext`, `--arc-ee` | Filter by file extension inside archive files |
@@ -2,3 +2,4 @@ click==8.1.8
2
2
  lark==1.2.2
3
3
  py7zr==1.0.0
4
4
  rarfile==4.2
5
+ rapidfuzz==3.13.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pseek"
7
- version = "2.4.0"
7
+ version = "2.5.0"
8
8
  description = "Pseek is a Python library to search files, folders, and text"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -17,7 +17,8 @@ dependencies = [
17
17
  "click==8.1.8",
18
18
  "lark==1.2.2",
19
19
  "py7zr==1.0.0",
20
- "rarfile==4.2"
20
+ "rarfile==4.2",
21
+ "rapidfuzz==3.13.0"
21
22
  ]
22
23
  urls = {Homepage = "https://github.com/ArianN8610/pysearch"}
23
24
 
File without changes
File without changes
File without changes
File without changes
File without changes