Masrkai commited on
Commit
5bd8526
Β·
1 Parent(s): 7d9501b

Upload 4 files

Browse files
Files changed (4) hide show
  1. .gitattributes +1 -0
  2. main.py +153 -0
  3. requirements.txt +1 -0
  4. shell.nix +38 -0
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ manuals.json filter=lfs diff=lfs merge=lfs -text
main.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ collect_manuals.py - Gather all available man pages as a JSON dataset.
4
+ NixOS compatible; relies on `manpath` and `man`.
5
+ """
6
+ import json
7
+ import os
8
+ import subprocess
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ # ----------------------------------------------------------------------
13
+ # 1. Get the man page search paths
14
+ # ----------------------------------------------------------------------
15
+ def get_manpaths():
16
+ """Return a list of directories that `man` searches for pages."""
17
+ # On NixOS, `manpath` prints the effective MANPATH, including all profile
18
+ # and store paths. Fall back to environment variable or hard-coded defaults.
19
+ try:
20
+ result = subprocess.run(["manpath", "-q"], capture_output=True, text=True, check=True)
21
+ paths = result.stdout.strip().split(":")
22
+ if paths and paths != [""]:
23
+ return paths
24
+ except (FileNotFoundError, subprocess.CalledProcessError):
25
+ pass
26
+
27
+ # Fallback: parse MANPATH environment variable
28
+ manpath_env = os.environ.get("MANPATH")
29
+ if manpath_env:
30
+ return manpath_env.split(":")
31
+
32
+ # Standard Linux defaults
33
+ return ["/usr/share/man", "/usr/local/share/man"]
34
+
35
+ # ----------------------------------------------------------------------
36
+ # 2. Find all man page files
37
+ # ----------------------------------------------------------------------
38
+ def find_man_files(manpaths):
39
+ """
40
+ Walk each manpath directory, look inside 'man<section>' subdirs,
41
+ and collect (topic_name, section, full_path).
42
+ """
43
+ # Valid extensions: compressed and raw roff
44
+ ext_list = {".gz", ".bz2", ".xz", ".Z", ".lzma"}
45
+ # Also accept files without compression suffix (e.g., "man1/bash.1")
46
+ entries = []
47
+
48
+ for base_dir in manpaths:
49
+ base = Path(base_dir)
50
+ if not base.is_dir():
51
+ continue
52
+ # All man page directories are named man1, man2, man3, manX...
53
+ for man_dir in base.glob("man*"):
54
+ if not man_dir.is_dir():
55
+ continue
56
+ # Extract section from directory name (e.g., "man1" -> "1")
57
+ section = man_dir.name[3:] # strip "man"
58
+ # Find all files inside (excluding symlinks that point outside)
59
+ for file_path in man_dir.iterdir():
60
+ if not file_path.is_file():
61
+ continue
62
+ # Resolve symlinks to avoid duplicates from different paths
63
+ real_path = file_path.resolve()
64
+ # Determine name by stripping the extension(s)
65
+ name = file_path.name
66
+ # Remove known compression extensions
67
+ while True:
68
+ stem, ext = os.path.splitext(name)
69
+ if ext.lower() in ext_list:
70
+ name = stem
71
+ else:
72
+ break
73
+ # Remove the section suffix if present (e.g., "open.2" -> "open")
74
+ # The section suffix matches the directory section, but we remove it.
75
+ if name.endswith(f".{section}"):
76
+ name = name[: -(len(section) + 1)]
77
+ # Skip directories, etc.
78
+ if not name:
79
+ continue
80
+ entries.append((name, section, real_path))
81
+ return entries
82
+
83
+ # ----------------------------------------------------------------------
84
+ # 3. Render a man page to plain text using `man -P cat`
85
+ # ----------------------------------------------------------------------
86
+ def render_man(topic, section, timeout=5):
87
+ """
88
+ Run `man -P cat <section> <topic>` and return its stdout as a string.
89
+ Returns None on failure.
90
+ """
91
+ cmd = ["man", "-P", "cat", section, topic]
92
+ try:
93
+ result = subprocess.run(
94
+ cmd,
95
+ capture_output=True,
96
+ text=True,
97
+ timeout=timeout,
98
+ # Some systems still pipe through less if MANPAGER is set;
99
+ # environment overrides it.
100
+ env={**os.environ, "MANPAGER": "cat", "PAGER": "cat"},
101
+ )
102
+ if result.returncode != 0:
103
+ # Possibly topic not found in database but file existed; skip.
104
+ return None
105
+ return result.stdout
106
+ except Exception:
107
+ return None
108
+
109
+ # ----------------------------------------------------------------------
110
+ # 4. Main
111
+ # ----------------------------------------------------------------------
112
+ def main():
113
+ # Collect paths
114
+ paths = get_manpaths()
115
+ print(f"Searching in {len(paths)} man directories...", file=sys.stderr)
116
+ entries = find_man_files(paths)
117
+ print(f"Found {len(entries)} manual page files.", file=sys.stderr)
118
+
119
+ # Remove exact duplicates (same topic + section from different paths)
120
+ # Keep the first occurrence, but we still use `man` which picks the first.
121
+ seen = set()
122
+ unique_entries = []
123
+ for name, section, filepath in entries:
124
+ key = (name, section)
125
+ if key not in seen:
126
+ seen.add(key)
127
+ unique_entries.append((name, section))
128
+ print(f"After deduplication: {len(unique_entries)} unique manuals.", file=sys.stderr)
129
+
130
+ dataset = []
131
+ # We'll write JSON Lines (one object per line) to avoid holding everything in memory.
132
+ # If you prefer a single JSON array, you can collect all objects first.
133
+ with open("manuals.jsonl", "w", encoding="utf-8") as fout:
134
+ for idx, (name, section) in enumerate(unique_entries, 1):
135
+ text = render_man(name, section)
136
+ if text is None:
137
+ # Could not render – skip or log
138
+ continue
139
+ record = {
140
+ "topic": name,
141
+ "section": section,
142
+ "manual": text,
143
+ }
144
+ # Write as JSON Lines (one per line)
145
+ fout.write(json.dumps(record, ensure_ascii=False) + "\n")
146
+
147
+ if idx % 100 == 0:
148
+ print(f"Processed {idx}/{len(unique_entries)}...", file=sys.stderr)
149
+
150
+ print("Done. Output written to manuals.jsonl", file=sys.stderr)
151
+
152
+ if __name__ == "__main__":
153
+ main()
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ pathlib
shell.nix ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ { pkgs ? import <nixpkgs> {
2
+ config = {
3
+ allowUnfree = true;
4
+ cudaSupport = true;
5
+ };
6
+ }
7
+ }:
8
+
9
+ pkgs.mkShell {
10
+ name = "LinuxAssistant";
11
+
12
+ buildInputs = with pkgs; [
13
+ # Python + uv
14
+ python312
15
+ uv
16
+
17
+ # Common native deps useful for ML/CUDA projects
18
+ stdenv.cc.cc.lib # libstdc++
19
+ zlib
20
+ libGL
21
+ ];
22
+
23
+ shellHook = ''
24
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
25
+ echo " uv version: $(uv --version)"
26
+ echo " Python: $(python --version)"
27
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
28
+
29
+ # Create venv with uv if it doesn't exist yet
30
+ if [ ! -d ".venv" ]; then
31
+ echo "β†’ Creating venv with uv..."
32
+ uv venv .venv --python python3.12
33
+ fi
34
+
35
+ # Activate it
36
+ source .venv/bin/activate
37
+ '';
38
+ }