Elffuss BraidHub

kikocis/lancedb public

bbc8a2ecbe2c · 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]
25
26python_prefix = "py"
27python_file = ".py"
28python_folder = "python"
29
30files = glob.glob(glob_string, recursive=True)
31excluded_files = [
32 f
33 for excluded_glob in excluded_globs
34 for f in glob.glob(excluded_glob, recursive=True)
35]
36
37
38def yield_lines(lines: Iterator[str], prefix: str, suffix: str):
39 in_code_block = False
40 # Python code has strict indentation
41 strip_length = 0
42 skip_test = False
43 for line in lines:
44 if "skip-test" in line:
45 skip_test = True
46 if line.strip().startswith(prefix + python_prefix):
47 in_code_block = True
48 strip_length = len(line) - len(line.lstrip())
49 elif in_code_block and line.strip().startswith(suffix):
50 in_code_block = False
51 if not skip_test:
52 yield "\n"
53 skip_test = False
54 elif in_code_block:
55 if not skip_test:
56 yield line[strip_length:]
57
58
59def wrap_async(lines: List[str]) -> List[str]:
60 # Indent all the lines
61 lines = [" " + line for line in lines]
62 # Put all lines in `async def main():`
63 lines = ["async def main():\n"] + lines
64 # Put `import asyncio\n asyncio.run(main())` at the end
65 lines = lines + ["\n", "import asyncio\n", "asyncio.run(main())\n"]
66 return lines
67
68
69for file in filter(lambda file: file not in excluded_files, files):
70 with open(file, "r") as f:
71 lines = list(yield_lines(iter(f), "```", "```"))
72
73 if len(lines) > 0:
74 if any("await" in line for line in lines):
75 lines = wrap_async(lines)
76
77 print(lines)
78 out_path = (
79 Path(python_folder)
80 / Path(file).name.strip(".md")
81 / (Path(file).name.strip(".md") + python_file)
82 )
83 print(out_path)
84 out_path.parent.mkdir(exist_ok=True, parents=True)
85 with open(out_path, "w") as out:
86 out.writelines(lines)