Elffuss BraidHub

kikocis/lancedb public

main · 2.6 KiB · executableRawPermalink
1#!/usr/bin/env python3
2
3import glob
4from typing import Iterator, List
5from pathlib import Path
6
7glob_string = "../src/**/*.md"
8excluded_globs = [
9 "../src/fts.md",
10 "../src/embedding.md",
11 "../src/examples/*.md",
12 "../src/integrations/*.md",
13 "../src/guides/tables.md",
14 "../src/python/duckdb.md",
15 "../src/embeddings/*.md",
16 "../src/concepts/*.md",
17 "../src/ann_indexes.md",
18 "../src/basic.md",
19 "../src/hybrid_search/hybrid_search.md",
20 "../src/reranking/*.md",
21 "../src/guides/tuning_retrievers/*.md",
22 "../src/embeddings/available_embedding_models/text_embedding_functions/*.md",
23 "../src/embeddings/available_embedding_models/multimodal_embedding_functions/*.md",
24 "../src/rag/*.md",
25 "../src/rag/advanced_techniques/*.md"
26
27
28]
29
30python_prefix = "py"
31python_file = ".py"
32python_folder = "python"
33
34files = glob.glob(glob_string, recursive=True)
35excluded_files = [
36 f
37 for excluded_glob in excluded_globs
38 for f in glob.glob(excluded_glob, recursive=True)
39]
40
41
42def yield_lines(lines: Iterator[str], prefix: str, suffix: str):
43 in_code_block = False
44 # Python code has strict indentation
45 strip_length = 0
46 skip_test = False
47 for line in lines:
48 if "skip-test" in line:
49 skip_test = True
50 if line.strip().startswith(prefix + python_prefix):
51 in_code_block = True
52 strip_length = len(line) - len(line.lstrip())
53 elif in_code_block and line.strip().startswith(suffix):
54 in_code_block = False
55 if not skip_test:
56 yield "\n"
57 skip_test = False
58 elif in_code_block:
59 if not skip_test:
60 yield line[strip_length:]
61
62
63def wrap_async(lines: List[str]) -> List[str]:
64 # Indent all the lines
65 lines = [" " + line for line in lines]
66 # Put all lines in `async def main():`
67 lines = ["async def main():\n"] + lines
68 # Put `import asyncio\n asyncio.run(main())` at the end
69 lines = lines + ["\n", "import asyncio\n", "asyncio.run(main())\n"]
70 return lines
71
72
73for file in filter(lambda file: file not in excluded_files, files):
74 with open(file, "r") as f:
75 lines = list(yield_lines(iter(f), "```", "```"))
76
77 if len(lines) > 0:
78 if any("await" in line for line in lines):
79 lines = wrap_async(lines)
80
81 print(lines)
82 out_path = (
83 Path(python_folder)
84 / Path(file).name.strip(".md")
85 / (Path(file).name.strip(".md") + python_file)
86 )
87 print(out_path)
88 out_path.parent.mkdir(exist_ok=True, parents=True)
89 with open(out_path, "w") as out:
90 out.writelines(lines)