feat(core): initialize Gravitiny Manager v0.1.0 and applets migration
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
# Gravitiny - Micro-Productivity Applet Ecosystem & Manager
|
||||
|
||||
## Vision & Purpose
|
||||
Gravitiny is a lightweight, cross-platform CLI package manager, runtime orchestrator, and applet ecosystem designed for ultra-fast, keyboard-driven productivity tools.
|
||||
|
||||
---
|
||||
|
||||
## Finalized Architectural Decisions
|
||||
|
||||
1. **Storage & Dotfiles Model:**
|
||||
- User runtime directory: `~/.gravitiny/` (Linux/macOS) and `%USERPROFILE%\.gravitiny\` (Windows).
|
||||
- Local directory contains:
|
||||
- `applets/`: Downloaded and active applets.
|
||||
- `bin/`: Generated shims and executables added to system PATH.
|
||||
- `data/`: Persistent applet databases, user configs, and caches.
|
||||
- `venv/`: Shared lightweight Python virtual environment.
|
||||
- `registry_cache.json`: Cached remote applet catalog.
|
||||
|
||||
2. **Dual-Mode Invocation:**
|
||||
- Direct shims: `sec <args>`, `lex <args>` (fastest, left-hand ergonomic muscle memory).
|
||||
- Orchestrated execution: `gravitiny run <applet> <args>` or `gravitiny <applet> <args>`.
|
||||
- User-configurable alias management via interactive CLI.
|
||||
|
||||
3. **Shared Native Runtime:**
|
||||
- Single per-machine shared Python virtual environment created during bootstrap.
|
||||
- Applet dependencies installed natively per OS/architecture.
|
||||
|
||||
4. **State Persistence on Updates:**
|
||||
- Strict separation between immutable code (`src/`, `main.py`, `manifest.json`) and stateful user storage (`data/`, `cache.db`, `lex.db`).
|
||||
- Updates update the code layer without touching user data or custom configurations.
|
||||
|
||||
5. **Language-Agnostic Applet Specification:**
|
||||
- Applets declare their runtime in `manifest.json` (`python`, `binary`, `shell`, `node`).
|
||||
- Standard flags (`-h`, `--help`, `-V`, `--version`) and standard exit codes (`0` for success).
|
||||
|
||||
6. **Online Registry & Distribution:**
|
||||
- GitHub-backed centralized JSON catalog (`registry.json`) with release zip archives and SHA-256 verification.
|
||||
- CLI commands: `gravitiny search`, `gravitiny install`, `gravitiny list`, `gravitiny update`, `gravitiny remove`.
|
||||
|
||||
---
|
||||
|
||||
## Roadmap & Milestone 1: Online Infrastructure
|
||||
- [ ] **1.1. Remote Registry Specification:** Schema definition for `registry.json`.
|
||||
- [ ] **1.2. Applet Packaging Format:** Standard packaging scripts to generate versioned zip releases and SHA-256 hashes.
|
||||
- [ ] **1.3. Registry Client Module:** Remote catalog fetching, caching, and searching in Gravitiny Core.
|
||||
- [ ] **1.4. Applet Downloader & Installer:** Fetch, verify checksum, unpack, and register shims.
|
||||
@@ -0,0 +1,5 @@
|
||||
import sys
|
||||
from gravitiny.src.cli import run_cli
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(run_cli())
|
||||
@@ -0,0 +1,15 @@
|
||||
# LEX - Issues & Bug Index
|
||||
|
||||
This file tracks reported bugs, edge cases, and behavior issues. Each issue has a unique ID, description, reproduction steps, and status (`[ ] Open`, `[x] Resolved`).
|
||||
|
||||
---
|
||||
|
||||
## Issue List
|
||||
|
||||
### ISSUE-001: Multi-word query causes unrecognized arguments error
|
||||
- **Status:** [x] Resolved
|
||||
- **Reported:** 2026-10-02
|
||||
- **Resolved:** 2026-10-02
|
||||
- **Description:** When running a query with two or more words without quotes (e.g., `lex Alexander Bell` or `lex silver spoon`), the CLI raises an `argparse` error: `lex: error: unrecognized arguments: Bell`.
|
||||
- **Resolution:** Updated `cli.py` to accept `nargs="*"` and join positional arguments with space. Multi-word phrases and idioms are now looked up seamlessly.
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# LEX - Offline CLI Dictionary & Context Assistant
|
||||
|
||||
## Project Purpose
|
||||
A lightweight, fast, offline CLI tool to look up English words, nuances, contexts, and example sentences backed by SQLite and fuzzy search.
|
||||
|
||||
---
|
||||
|
||||
## Architectural Decisions
|
||||
1. **Architecture & Storage:** Local SQLite database.
|
||||
2. **Fuzzy Search:** Approximate string matching with similarity percentage threshold for typo tolerance.
|
||||
3. **Data Source:** Rich English-English dictionary dataset (definitions, nuances, part of speech, usage examples, collocations, antonyms/synonyms).
|
||||
4. **Modularity:** An isolated, standalone utility (`lex`) within the `gravitiny` workspace.
|
||||
5. **Language & Stack:** Python 3 (`rich` for terminal UI, standard `sqlite3`, `rapidfuzz`/`difflib` for similarity calculation).
|
||||
6. **Primary Mode (Quick Mode):** Called directly via `lex <word>`. Returns a clean, concise summary card. If not found, outputs a standardized catalog message.
|
||||
7. **Centralized UI/String Catalog:** All UI labels, headers, formatted layouts, prompts, and error/status messages stored in a centralized JSON file (`strings.json`). No hardcoded UI strings in code.
|
||||
8. **Code Standards:** Professional English in all code, comments, catalogs, and documentation. No emojis in terminal UI or codebase.
|
||||
|
||||
---
|
||||
|
||||
## Pending Topics & Decisions
|
||||
- [x] **4. Database Population / Seeding:** Implemented via Princeton WordNet 3.0 SQLite seeder and Kaikki Turkish-to-English dataset (206k English + 45.8k Turkish entries).
|
||||
- [x] **5. Fuzzy Search Engine:** 3-stage candidate pruning (SQLite index filter -> sequence matcher ratio >= 75%). Handles character substitutions, omissions, common spelling typos, and Turkish diacritic normalization (`ç/c`, `ş/s`, `ğ/g`, `ı/i`, `ö/o`, `ü/u`).
|
||||
- [x] **12. Sub-millisecond Bilingual Auto-Routing:** Automatically detects Turkish and English queries without manual mode switching; routes to appropriate card renderer.
|
||||
|
||||
- [x] **3. Quick Mode Card Layout & Styling:** Implemented via `lex/src/renderer.py` and `rich.Panel`. All UI labels, templates, and statuses centralized in `lex/catalog/strings.json`.
|
||||
- [ ] **7. Standalone GUI Installer & Uninstaller:** Source code developed; binary installer generation deferred until feature milestones are completed.
|
||||
|
||||
|
||||
- [ ] **1. Advanced Modes & Detailed Views:** Extended views (e.g., `lex <word> --full`, etymology, full senses).
|
||||
- [ ] **2. Interactivity & TUI:** Interactive terminal navigation (e.g., arrow key sense browsing, list saving, filtering).
|
||||
- [ ] **6. Advanced Fuzzy Enhancements:** Future phonetic (Metaphone) and keyboard distance / QWERTY layout proximity scoring.
|
||||
- [ ] **8. Quick Start Guide (B1):** Concise walkthrough to get users productive within seconds.
|
||||
- [ ] **9. Interactive Settings Feature (C1):** Interactive configuration tool (`lex config`) to customize defaults, color themes, and fuzzy thresholds.
|
||||
- [ ] **10. Documentation, License & Changelog (C3):** Standardized repository documentation, MIT license details, and version changelog.
|
||||
- [ ] **11. Final Command Reference (B2):** Comprehensive parameter and flag reference to be finalized at the project conclusion.
|
||||
|
||||
|
||||
|
||||
## Bug & Issue Tracking
|
||||
Tracked actively in [ISSUES.md](file:///c:/Users/al3ph/Desktop/gravitiny/lex/ISSUES.md).
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
if str(PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
from lex.src.cli import run_cli
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(run_cli(sys.argv[1:]))
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"app": {
|
||||
"name": "LEX",
|
||||
"description": "Offline English Dictionary & Context Assistant",
|
||||
"version": "1.0.0",
|
||||
"publisher": "Gravitiny",
|
||||
"version_output": "{name} v{version} [{stage}] - {description}"
|
||||
},
|
||||
"status": {
|
||||
"nothing_found": "Nothing found for \"{query}\".",
|
||||
"fuzzy_notice": "Showing results for \"{matched_word}\" ({similarity}% match):",
|
||||
"db_missing": "Database file not found at: {path}. Please run seed script."
|
||||
},
|
||||
"labels": {
|
||||
"definition": "Definition",
|
||||
"examples": "Examples",
|
||||
"synonyms": "Synonyms",
|
||||
"part_of_speech": "POS",
|
||||
"tr_badge": "Turkish -> English",
|
||||
"tr_english_meanings": "English Meanings",
|
||||
"tr_synonyms": "Related Words"
|
||||
},
|
||||
"formatting": {
|
||||
"bullet_point": " - {example}",
|
||||
"synonym_separator": ", "
|
||||
},
|
||||
"gui_installer": {
|
||||
"window_title": "LEX Setup Wizard",
|
||||
"welcome_title": "Welcome to LEX Setup",
|
||||
"welcome_subtitle": "This wizard will install LEX Offline CLI Dictionary on your computer.",
|
||||
"destination_label": "Destination Folder:",
|
||||
"chk_path": "Add LEX to user PATH environment variable (Recommended)",
|
||||
"btn_install": "Install Now",
|
||||
"btn_cancel": "Cancel",
|
||||
"btn_finish": "Finish",
|
||||
"status_ready": "Ready to install.",
|
||||
"status_copying": "Copying dictionary database and application files...",
|
||||
"status_path": "Configuring user PATH environment variable...",
|
||||
"status_registry": "Registering in Windows Settings...",
|
||||
"status_complete": "Installation completed successfully.",
|
||||
"congrats_title": "Installation Complete",
|
||||
"congrats_message": "Congratulations! LEX has been successfully installed.\n\nOpen a new terminal window and type:\n lex <word>\n\nto start exploring!"
|
||||
},
|
||||
"gui_uninstaller": {
|
||||
"window_title": "LEX Uninstaller",
|
||||
"confirm_title": "Uninstall LEX",
|
||||
"confirm_subtitle": "Are you sure you want to remove LEX and all its components from your computer?",
|
||||
"btn_uninstall": "Uninstall",
|
||||
"btn_cancel": "Cancel",
|
||||
"btn_close": "Close",
|
||||
"status_removing_path": "Removing LEX from user PATH...",
|
||||
"status_removing_registry": "Cleaning up registry entries...",
|
||||
"status_removing_files": "Removing installed files and database...",
|
||||
"status_complete": "LEX has been successfully removed.",
|
||||
"success_title": "Uninstallation Complete",
|
||||
"success_message": "LEX has been completely uninstalled from your system."
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,17 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
if str(BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(BASE_DIR))
|
||||
if str(BASE_DIR.parent) not in sys.path:
|
||||
sys.path.insert(0, str(BASE_DIR.parent))
|
||||
|
||||
try:
|
||||
from lex.src.cli import run_cli
|
||||
except ImportError:
|
||||
from src.cli import run_cli
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(run_cli(sys.argv[1:]))
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"name": "Lex",
|
||||
"display_name": "LEX - Offline CLI Dictionary & Context Assistant",
|
||||
"description": "Lightweight, fast, and offline command-line bilingual English/Turkish dictionary and context assistant.",
|
||||
"version": "1.1.0",
|
||||
"stage": "Beta",
|
||||
"release_type": "Minor",
|
||||
"created_at": "2026-10-02",
|
||||
"updated_at": "2026-10-02",
|
||||
"license": "MIT",
|
||||
"author": "Gravitiny Team",
|
||||
"dependencies": [
|
||||
"rich>=13.0.0"
|
||||
],
|
||||
"features": [
|
||||
"Offline WordNet 3.0 English Lexicon (206k+ entries)",
|
||||
"Offline Wiktionary Turkish-to-English Lexicon (45k+ entries)",
|
||||
"Sub-millisecond automatic language detection (EN <-> TR)",
|
||||
"3-Stage Candidate Pruning & Fuzzy Search (Levenshtein / SequenceMatcher)",
|
||||
"Centralized JSON Message and UI Catalog",
|
||||
"Lightweight native Windows launcher and GUI installer"
|
||||
],
|
||||
"changelog": [
|
||||
{
|
||||
"version": "1.1.0",
|
||||
"date": "2026-10-02",
|
||||
"stage": "Beta",
|
||||
"type": "Minor Feature Release",
|
||||
"changes": [
|
||||
"Added comprehensive offline Turkish-to-English lexicon (45,899 entries).",
|
||||
"Implemented instant language detection with zero perceptual latency.",
|
||||
"Added distinct Turkish-to-English card renderer with nuances and examples.",
|
||||
"Added bilingual fuzzy search across English and Turkish entries."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"date": "2026-10-02",
|
||||
"stage": "Beta",
|
||||
"type": "Initial Release",
|
||||
"changes": [
|
||||
"Initial release of LEX CLI with Quick Mode card view.",
|
||||
"Integrated offline SQLite database with 206k WordNet entries.",
|
||||
"Implemented multi-word phrase queries and fuzzy search.",
|
||||
"Added standalone GUI installer and Windows Settings integration."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
import requests
|
||||
|
||||
KAIKKI_TURKISH_URL = "https://kaikki.org/dictionary/Turkish/kaikki.org-dictionary-Turkish.jsonl"
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
DATA_DIR = os.path.join(BASE_DIR, "data")
|
||||
DB_PATH = os.path.join(DATA_DIR, "lex.db")
|
||||
|
||||
|
||||
def download_and_ingest_turkish():
|
||||
print(f"Downloading Turkish lexicon from {KAIKKI_TURKISH_URL}...")
|
||||
response = requests.get(KAIKKI_TURKISH_URL, stream=True)
|
||||
response.raise_for_status()
|
||||
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
cur = conn.cursor()
|
||||
|
||||
# Create tr_entries table
|
||||
cur.execute("DROP TABLE IF EXISTS tr_entries;")
|
||||
cur.execute("""
|
||||
CREATE TABLE tr_entries (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
word TEXT NOT NULL,
|
||||
pos TEXT NOT NULL,
|
||||
glosses TEXT NOT NULL,
|
||||
examples TEXT NOT NULL,
|
||||
synonyms TEXT NOT NULL
|
||||
);
|
||||
""")
|
||||
|
||||
cur.execute("CREATE INDEX IF NOT EXISTS idx_tr_entries_word ON tr_entries (word);")
|
||||
cur.execute("CREATE INDEX IF NOT EXISTS idx_tr_entries_pos ON tr_entries (pos);")
|
||||
|
||||
insert_sql = """
|
||||
INSERT INTO tr_entries (word, pos, glosses, examples, synonyms)
|
||||
VALUES (?, ?, ?, ?, ?);
|
||||
"""
|
||||
|
||||
batch = []
|
||||
total_count = 0
|
||||
|
||||
print("Parsing and inserting Turkish entries into SQLite...")
|
||||
for line in response.iter_lines():
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
item = json.loads(line.decode("utf-8"))
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
word = item.get("word", "").strip().lower()
|
||||
pos = item.get("pos", "").strip().lower()
|
||||
if not word or not pos:
|
||||
continue
|
||||
|
||||
senses = item.get("senses", [])
|
||||
glosses = []
|
||||
examples = []
|
||||
synonyms = []
|
||||
|
||||
for s in senses:
|
||||
for g in s.get("glosses", []):
|
||||
g_clean = g.strip()
|
||||
if g_clean and g_clean not in glosses:
|
||||
glosses.append(g_clean)
|
||||
|
||||
for ex in s.get("examples", []):
|
||||
text = ex.get("text", "").strip()
|
||||
eng_trans = ex.get("english", "").strip()
|
||||
if text:
|
||||
if eng_trans:
|
||||
examples.append(f"{text} -> {eng_trans}")
|
||||
else:
|
||||
examples.append(text)
|
||||
|
||||
for syn in s.get("synonyms", []):
|
||||
syn_word = syn.get("word", "").strip()
|
||||
if syn_word and syn_word not in synonyms:
|
||||
synonyms.append(syn_word)
|
||||
|
||||
if not glosses:
|
||||
continue
|
||||
|
||||
batch.append((
|
||||
word,
|
||||
pos,
|
||||
json.dumps(glosses, ensure_ascii=False),
|
||||
json.dumps(examples, ensure_ascii=False),
|
||||
json.dumps(synonyms, ensure_ascii=False),
|
||||
))
|
||||
total_count += 1
|
||||
|
||||
if len(batch) >= 5000:
|
||||
cur.executemany(insert_sql, batch)
|
||||
conn.commit()
|
||||
batch = []
|
||||
print(f"Inserted {total_count} Turkish entries...")
|
||||
|
||||
if batch:
|
||||
cur.executemany(insert_sql, batch)
|
||||
conn.commit()
|
||||
|
||||
conn.close()
|
||||
print(f"Turkish lexicon ingestion complete. Total entries: {total_count}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
download_and_ingest_turkish()
|
||||
@@ -0,0 +1,166 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
import zipfile
|
||||
import requests
|
||||
|
||||
WORDNET_ZIP_URL = "https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages/corpora/wordnet.zip"
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
DATA_DIR = os.path.join(BASE_DIR, "data")
|
||||
DB_PATH = os.path.join(DATA_DIR, "lex.db")
|
||||
|
||||
POS_MAP = {
|
||||
"n": "noun",
|
||||
"v": "verb",
|
||||
"a": "adjective",
|
||||
"s": "adjective satellite",
|
||||
"r": "adverb"
|
||||
}
|
||||
|
||||
def ensure_directories():
|
||||
os.makedirs(DATA_DIR, exist_ok=True)
|
||||
|
||||
def download_wordnet():
|
||||
print(f"Downloading WordNet from {WORDNET_ZIP_URL}...")
|
||||
response = requests.get(WORDNET_ZIP_URL, stream=True)
|
||||
response.raise_for_status()
|
||||
total_size = int(response.headers.get("content-length", 0))
|
||||
print(f"Downloaded package size: {total_size / (1024 * 1024):.2f} MB")
|
||||
return io.BytesIO(response.content)
|
||||
|
||||
def parse_wordnet_data(zip_file):
|
||||
records = []
|
||||
with zipfile.ZipFile(zip_file) as z:
|
||||
data_files = [
|
||||
("wordnet/data.noun", "n"),
|
||||
("wordnet/data.verb", "v"),
|
||||
("wordnet/data.adj", "a"),
|
||||
("wordnet/data.adv", "r"),
|
||||
]
|
||||
|
||||
for zip_path, pos_code in data_files:
|
||||
if zip_path not in z.namelist():
|
||||
continue
|
||||
with z.open(zip_path) as f:
|
||||
for line_bytes in f:
|
||||
line = line_bytes.decode("utf-8", errors="ignore").strip()
|
||||
if not line or line.startswith(" "):
|
||||
continue
|
||||
|
||||
parts = line.split("|")
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
|
||||
gloss = parts[1].strip()
|
||||
meta_part = parts[0].strip().split()
|
||||
if len(meta_part) < 5:
|
||||
continue
|
||||
|
||||
synset_offset = meta_part[0]
|
||||
pos = POS_MAP.get(pos_code, pos_code)
|
||||
|
||||
# Extract lemmas
|
||||
try:
|
||||
w_cnt = int(meta_part[3], 16)
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
lemmas = []
|
||||
idx = 4
|
||||
for _ in range(w_cnt):
|
||||
if idx < len(meta_part):
|
||||
lemmas.append(meta_part[idx].lower().replace("_", " "))
|
||||
idx += 2
|
||||
|
||||
# Split definition and examples from gloss
|
||||
# Gloss format: "definition ; \"example 1\" ; \"example 2\""
|
||||
gloss_split = gloss.split(";")
|
||||
definition = gloss_split[0].strip()
|
||||
examples = []
|
||||
for s in gloss_split[1:]:
|
||||
s_clean = s.strip().strip('"').strip()
|
||||
if s_clean:
|
||||
examples.append(s_clean)
|
||||
|
||||
for word in lemmas:
|
||||
synonyms = [w for w in lemmas if w != word]
|
||||
records.append({
|
||||
"word": word,
|
||||
"pos": pos,
|
||||
"definition": definition,
|
||||
"examples": examples,
|
||||
"synonyms": synonyms,
|
||||
"synset_id": f"{pos_code}.{synset_offset}"
|
||||
})
|
||||
|
||||
return records
|
||||
|
||||
def create_sqlite_database(records):
|
||||
print(f"Creating SQLite database at {DB_PATH} with {len(records)} entries...")
|
||||
if os.path.exists(DB_PATH):
|
||||
os.remove(DB_PATH)
|
||||
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
cur = conn.cursor()
|
||||
|
||||
# Create tables
|
||||
cur.execute("""
|
||||
CREATE TABLE entries (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
word TEXT NOT NULL,
|
||||
pos TEXT NOT NULL,
|
||||
definition TEXT NOT NULL,
|
||||
examples TEXT NOT NULL,
|
||||
synonyms TEXT NOT NULL,
|
||||
synset_id TEXT NOT NULL
|
||||
);
|
||||
""")
|
||||
|
||||
cur.execute("CREATE INDEX idx_entries_word ON entries (word);")
|
||||
cur.execute("CREATE INDEX idx_entries_pos ON entries (pos);")
|
||||
|
||||
# FTS5 table for fast word lookups
|
||||
cur.execute("""
|
||||
CREATE VIRTUAL TABLE entries_fts USING fts5(
|
||||
word,
|
||||
tokenize='unicode61 remove_diacritics 2'
|
||||
);
|
||||
""")
|
||||
|
||||
# Batch insert
|
||||
insert_sql = """
|
||||
INSERT INTO entries (word, pos, definition, examples, synonyms, synset_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?);
|
||||
"""
|
||||
fts_sql = "INSERT INTO entries_fts (word) VALUES (?);"
|
||||
|
||||
batch = []
|
||||
fts_batch = []
|
||||
for r in records:
|
||||
batch.append((
|
||||
r["word"],
|
||||
r["pos"],
|
||||
r["definition"],
|
||||
json.dumps(r["examples"], ensure_ascii=False),
|
||||
json.dumps(r["synonyms"], ensure_ascii=False),
|
||||
r["synset_id"]
|
||||
))
|
||||
fts_batch.append((r["word"],))
|
||||
|
||||
cur.executemany(insert_sql, batch)
|
||||
cur.executemany(fts_sql, fts_batch)
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print("Database creation complete.")
|
||||
|
||||
def main():
|
||||
ensure_directories()
|
||||
zip_bytes = download_wordnet()
|
||||
records = parse_wordnet_data(zip_bytes)
|
||||
create_sqlite_database(records)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,57 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
ASSETS_DIR = BASE_DIR / "assets"
|
||||
ASSETS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
ICON_PATH = ASSETS_DIR / "lex_icon.ico"
|
||||
|
||||
|
||||
def generate_icon():
|
||||
size = 256
|
||||
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
||||
draw = ImageDraw.Draw(img)
|
||||
|
||||
# Draw rounded rectangle badge background
|
||||
pad = 16
|
||||
draw.rounded_rectangle(
|
||||
[pad, pad, size - pad, size - pad],
|
||||
radius=48,
|
||||
fill=(24, 119, 242, 255), # Modern royal blue
|
||||
outline=(200, 230, 255, 255),
|
||||
width=4,
|
||||
)
|
||||
|
||||
# Draw inner terminal / book symbol
|
||||
# Book left page
|
||||
draw.polygon(
|
||||
[(64, 80), (124, 70), (124, 180), (64, 170)],
|
||||
fill=(255, 255, 255, 240),
|
||||
)
|
||||
# Book right page
|
||||
draw.polygon(
|
||||
[(132, 70), (192, 80), (192, 170), (132, 180)],
|
||||
fill=(255, 255, 255, 240),
|
||||
)
|
||||
|
||||
# Spine separator line
|
||||
draw.line([(128, 68), (128, 182)], fill=(20, 80, 180, 255), width=3)
|
||||
|
||||
# Text / lines on pages
|
||||
draw.line([(76, 100), (114, 94)], fill=(100, 150, 220, 255), width=3)
|
||||
draw.line([(76, 120), (114, 114)], fill=(100, 150, 220, 255), width=3)
|
||||
draw.line([(76, 140), (114, 134)], fill=(100, 150, 220, 255), width=3)
|
||||
|
||||
draw.line([(142, 94), (180, 100)], fill=(100, 150, 220, 255), width=3)
|
||||
draw.line([(142, 114), (180, 120)], fill=(100, 150, 220, 255), width=3)
|
||||
draw.line([(142, 134), (180, 140)], fill=(100, 150, 220, 255), width=3)
|
||||
|
||||
# Save as multi-size ICO
|
||||
sizes = [(16, 16), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]
|
||||
img.save(ICON_PATH, format="ICO", sizes=sizes)
|
||||
print(f"Generated icon at: {ICON_PATH}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
generate_icon()
|
||||
@@ -0,0 +1 @@
|
||||
"""LEX Dictionary and Context Assistant Package."""
|
||||
@@ -0,0 +1,47 @@
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
class StringCatalog:
|
||||
"""Centralized catalog for user-facing strings and message templates."""
|
||||
|
||||
_instance = None
|
||||
_catalog: Dict[str, Any] = {}
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super(StringCatalog, cls).__new__(cls)
|
||||
cls._instance._load_catalog()
|
||||
return cls._instance
|
||||
|
||||
def _load_catalog(self) -> None:
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
catalog_path = os.path.join(base_dir, "catalog", "strings.json")
|
||||
if os.path.exists(catalog_path):
|
||||
with open(catalog_path, "r", encoding="utf-8") as f:
|
||||
self._catalog = json.load(f)
|
||||
else:
|
||||
self._catalog = {}
|
||||
|
||||
def get(self, key_path: str, default: str = "") -> str:
|
||||
"""Retrieve a string from the catalog using dot notation."""
|
||||
parts = key_path.split(".")
|
||||
current = self._catalog
|
||||
for part in parts:
|
||||
if isinstance(current, dict) and part in current:
|
||||
current = current[part]
|
||||
else:
|
||||
return default
|
||||
return str(current) if current is not None else default
|
||||
|
||||
def format(self, key_path: str, **kwargs: Any) -> str:
|
||||
"""Retrieve a template string and interpolate keyword arguments."""
|
||||
template = self.get(key_path, "")
|
||||
try:
|
||||
return template.format(**kwargs)
|
||||
except KeyError:
|
||||
return template
|
||||
|
||||
|
||||
catalog = StringCatalog()
|
||||
@@ -0,0 +1,86 @@
|
||||
import argparse
|
||||
import sys
|
||||
from typing import List, Optional
|
||||
|
||||
try:
|
||||
from lex.src.catalog import catalog
|
||||
from lex.src.db import DatabaseManager
|
||||
from lex.src.fuzzy import SearchEngine
|
||||
from lex.src.manifest import load_manifest
|
||||
from lex.src.renderer import QuickRenderer
|
||||
except ImportError:
|
||||
from src.catalog import catalog
|
||||
from src.db import DatabaseManager
|
||||
from src.fuzzy import SearchEngine
|
||||
from src.manifest import load_manifest
|
||||
from src.renderer import QuickRenderer
|
||||
|
||||
|
||||
def parse_args(args: Optional[List[str]] = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="lex",
|
||||
description=catalog.get("app.description", "Offline English Dictionary & Context Assistant"),
|
||||
)
|
||||
parser.add_argument(
|
||||
"-V", "-v", "--version",
|
||||
action="store_true",
|
||||
help="Show application version and stage information.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"word",
|
||||
nargs="*",
|
||||
help="The word or phrase to look up.",
|
||||
)
|
||||
return parser.parse_args(args)
|
||||
|
||||
|
||||
def run_cli(args: Optional[List[str]] = None) -> int:
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
parsed = parse_args(args)
|
||||
|
||||
|
||||
if parsed.version:
|
||||
manifest = load_manifest()
|
||||
version_text = catalog.format(
|
||||
"app.version_output",
|
||||
name=manifest.get("name", "LEX"),
|
||||
version=manifest.get("version", "1.0.0"),
|
||||
stage=manifest.get("stage", "Beta"),
|
||||
description=manifest.get("description", ""),
|
||||
)
|
||||
print(version_text)
|
||||
return 0
|
||||
|
||||
if not parsed.word:
|
||||
manifest = load_manifest()
|
||||
print(f"{manifest.get('name', 'LEX')} v{manifest.get('version', '1.0.0')} [{manifest.get('stage', 'Beta')}] - {manifest.get('description', '')}")
|
||||
print("Usage: lex <word> or lex --version")
|
||||
return 0
|
||||
|
||||
|
||||
query = " ".join(parsed.word).strip()
|
||||
|
||||
|
||||
db_manager = DatabaseManager()
|
||||
renderer = QuickRenderer()
|
||||
|
||||
if not db_manager.exists():
|
||||
renderer.render_db_missing(db_manager.db_path)
|
||||
return 1
|
||||
|
||||
engine = SearchEngine(db_manager)
|
||||
result = engine.lookup(query)
|
||||
|
||||
if not result or not result.entries:
|
||||
renderer.render_not_found(query)
|
||||
return 0
|
||||
|
||||
renderer.render_result(result)
|
||||
return 0
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class WordEntry:
|
||||
word: str
|
||||
pos: str
|
||||
definition: str
|
||||
examples: List[str]
|
||||
synonyms: List[str]
|
||||
synset_id: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrWordEntry:
|
||||
word: str
|
||||
pos: str
|
||||
glosses: List[str]
|
||||
examples: List[str]
|
||||
synonyms: List[str]
|
||||
|
||||
|
||||
TR_CHAR_VARIANTS = {
|
||||
"c": ["c", "ç"],
|
||||
"ç": ["c", "ç"],
|
||||
"g": ["g", "ğ"],
|
||||
"ğ": ["g", "ğ"],
|
||||
"i": ["i", "ı"],
|
||||
"ı": ["i", "ı"],
|
||||
"o": ["o", "ö"],
|
||||
"ö": ["o", "ö"],
|
||||
"s": ["s", "ş"],
|
||||
"ş": ["s", "ş"],
|
||||
"u": ["u", "ü"],
|
||||
"ü": ["u", "ü"],
|
||||
}
|
||||
|
||||
|
||||
class DatabaseManager:
|
||||
"""Handles SQLite connection and dictionary queries."""
|
||||
|
||||
def __init__(self, db_path: Optional[str] = None):
|
||||
if db_path is None:
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
db_path = os.path.join(base_dir, "data", "lex.db")
|
||||
self.db_path = db_path
|
||||
|
||||
def exists(self) -> bool:
|
||||
return os.path.exists(self.db_path)
|
||||
|
||||
def _get_connection(self) -> sqlite3.Connection:
|
||||
return sqlite3.connect(self.db_path)
|
||||
|
||||
def find_exact(self, word: str) -> List[WordEntry]:
|
||||
"""Fetch all definition entries for an exact English word match."""
|
||||
if not self.exists():
|
||||
return []
|
||||
|
||||
conn = self._get_connection()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT word, pos, definition, examples, synonyms, synset_id
|
||||
FROM entries
|
||||
WHERE word = ?
|
||||
""",
|
||||
(word.strip().lower(),),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
|
||||
results = []
|
||||
for r in rows:
|
||||
examples = json.loads(r[3]) if r[3] else []
|
||||
synonyms = json.loads(r[4]) if r[4] else []
|
||||
results.append(
|
||||
WordEntry(
|
||||
word=r[0],
|
||||
pos=r[1],
|
||||
definition=r[2],
|
||||
examples=examples,
|
||||
synonyms=synonyms,
|
||||
synset_id=r[5],
|
||||
)
|
||||
)
|
||||
return results
|
||||
|
||||
def find_tr_exact(self, word: str) -> List[TrWordEntry]:
|
||||
"""Fetch all definition entries for an exact Turkish word match."""
|
||||
if not self.exists():
|
||||
return []
|
||||
|
||||
conn = self._get_connection()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT word, pos, glosses, examples, synonyms
|
||||
FROM tr_entries
|
||||
WHERE word = ?
|
||||
""",
|
||||
(word.strip().lower(),),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
|
||||
results = []
|
||||
for r in rows:
|
||||
glosses = json.loads(r[2]) if r[2] else []
|
||||
examples = json.loads(r[3]) if r[3] else []
|
||||
synonyms = json.loads(r[4]) if r[4] else []
|
||||
results.append(
|
||||
TrWordEntry(
|
||||
word=r[0],
|
||||
pos=r[1],
|
||||
glosses=glosses,
|
||||
examples=examples,
|
||||
synonyms=synonyms,
|
||||
)
|
||||
)
|
||||
return results
|
||||
|
||||
def get_fuzzy_candidates(self, query: str) -> List[str]:
|
||||
"""Fetch distinct candidate words from English dictionary."""
|
||||
if not self.exists() or not query:
|
||||
return []
|
||||
|
||||
conn = self._get_connection()
|
||||
cur = conn.cursor()
|
||||
q = query.strip().lower()
|
||||
min_len = max(1, len(q) - 3)
|
||||
max_len = len(q) + 3
|
||||
|
||||
candidates = []
|
||||
if len(q) >= 4:
|
||||
pattern = f"{q[:2]}%"
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT DISTINCT word
|
||||
FROM entries
|
||||
WHERE word LIKE ?
|
||||
AND length(word) BETWEEN ? AND ?
|
||||
""",
|
||||
(pattern, min_len, max_len),
|
||||
)
|
||||
candidates = [r[0] for r in cur.fetchall()]
|
||||
|
||||
if len(candidates) < 50:
|
||||
pattern = f"{q[0]}%"
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT DISTINCT word
|
||||
FROM entries
|
||||
WHERE word LIKE ?
|
||||
AND length(word) BETWEEN ? AND ?
|
||||
""",
|
||||
(pattern, min_len, max_len),
|
||||
)
|
||||
candidates = [r[0] for r in cur.fetchall()]
|
||||
|
||||
conn.close()
|
||||
return candidates
|
||||
|
||||
def get_tr_fuzzy_candidates(self, query: str) -> List[str]:
|
||||
"""Fetch distinct candidate words from Turkish dictionary with diacritic variants."""
|
||||
if not self.exists() or not query:
|
||||
return []
|
||||
|
||||
conn = self._get_connection()
|
||||
cur = conn.cursor()
|
||||
q = query.strip().lower()
|
||||
min_len = max(1, len(q) - 3)
|
||||
max_len = len(q) + 3
|
||||
|
||||
first_char = q[0]
|
||||
variants = TR_CHAR_VARIANTS.get(first_char, [first_char])
|
||||
|
||||
candidates = []
|
||||
for v in variants:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT DISTINCT word
|
||||
FROM tr_entries
|
||||
WHERE word LIKE ?
|
||||
AND length(word) BETWEEN ? AND ?
|
||||
""",
|
||||
(f"{v}%", min_len, max_len),
|
||||
)
|
||||
for r in cur.fetchall():
|
||||
if r[0] not in candidates:
|
||||
candidates.append(r[0])
|
||||
|
||||
conn.close()
|
||||
return candidates
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import difflib
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, List, Optional, Union
|
||||
|
||||
try:
|
||||
from lex.src.db import DatabaseManager, TrWordEntry, WordEntry
|
||||
except ImportError:
|
||||
from src.db import DatabaseManager, TrWordEntry, WordEntry
|
||||
|
||||
TURKISH_CHARS = set("çğıöşüÇĞİÖŞÜ")
|
||||
|
||||
|
||||
@dataclass
|
||||
class SearchResult:
|
||||
query: str
|
||||
matched_word: str
|
||||
is_fuzzy: bool
|
||||
similarity_pct: int
|
||||
language: str # "en" or "tr"
|
||||
entries: List[Union[WordEntry, TrWordEntry]]
|
||||
|
||||
|
||||
TR_NORM_MAP = str.maketrans("çğıöşüÇĞİÖŞÜ", "cgiosuCGIOSU")
|
||||
|
||||
|
||||
def normalize_tr(s: str) -> str:
|
||||
return s.translate(TR_NORM_MAP).lower()
|
||||
|
||||
|
||||
class SearchEngine:
|
||||
"""Orchestrates multi-lingual exact and fuzzy word lookup."""
|
||||
|
||||
def __init__(self, db_manager: DatabaseManager, threshold: float = 0.75):
|
||||
self.db = db_manager
|
||||
self.threshold = threshold
|
||||
|
||||
def _has_turkish_chars(self, text: str) -> bool:
|
||||
return any(c in TURKISH_CHARS for c in text)
|
||||
|
||||
def lookup(self, raw_query: str) -> Optional[SearchResult]:
|
||||
query = raw_query.strip().lower()
|
||||
if not query:
|
||||
return None
|
||||
|
||||
has_tr_chars = self._has_turkish_chars(raw_query)
|
||||
|
||||
# 1. Turkish-first path if explicit Turkish characters exist
|
||||
if has_tr_chars:
|
||||
tr_exact = self.db.find_tr_exact(query)
|
||||
if tr_exact:
|
||||
return SearchResult(
|
||||
query=query,
|
||||
matched_word=query,
|
||||
is_fuzzy=False,
|
||||
similarity_pct=100,
|
||||
language="tr",
|
||||
entries=tr_exact,
|
||||
)
|
||||
tr_fuzzy = self._lookup_tr_fuzzy(query)
|
||||
if tr_fuzzy:
|
||||
return tr_fuzzy
|
||||
|
||||
# 2. English exact match lookup
|
||||
en_exact = self.db.find_exact(query)
|
||||
if en_exact:
|
||||
return SearchResult(
|
||||
query=query,
|
||||
matched_word=query,
|
||||
is_fuzzy=False,
|
||||
similarity_pct=100,
|
||||
language="en",
|
||||
entries=en_exact,
|
||||
)
|
||||
|
||||
# 3. Turkish exact match lookup (e.g., "araba", "yemek")
|
||||
tr_exact = self.db.find_tr_exact(query)
|
||||
if tr_exact:
|
||||
return SearchResult(
|
||||
query=query,
|
||||
matched_word=query,
|
||||
is_fuzzy=False,
|
||||
similarity_pct=100,
|
||||
language="tr",
|
||||
entries=tr_exact,
|
||||
)
|
||||
|
||||
# 4. Normalized Turkish match (e.g. typing "celiski" for "çelişki", "gecici" for "geçici")
|
||||
tr_norm_match = self._lookup_tr_normalized(query)
|
||||
if tr_norm_match:
|
||||
return tr_norm_match
|
||||
|
||||
# 5. Fuzzy Matching across both dictionaries
|
||||
en_fuzzy = self._lookup_en_fuzzy(query)
|
||||
tr_fuzzy = self._lookup_tr_fuzzy(query)
|
||||
|
||||
if en_fuzzy and tr_fuzzy:
|
||||
return en_fuzzy if en_fuzzy.similarity_pct >= tr_fuzzy.similarity_pct else tr_fuzzy
|
||||
return en_fuzzy or tr_fuzzy
|
||||
|
||||
def _lookup_tr_normalized(self, query: str) -> Optional[SearchResult]:
|
||||
norm_q = normalize_tr(query)
|
||||
candidates = self.db.get_tr_fuzzy_candidates(query)
|
||||
for cand in candidates:
|
||||
if normalize_tr(cand) == norm_q:
|
||||
entries = self.db.find_tr_exact(cand)
|
||||
if entries:
|
||||
return SearchResult(
|
||||
query=query,
|
||||
matched_word=cand,
|
||||
is_fuzzy=True,
|
||||
similarity_pct=100,
|
||||
language="tr",
|
||||
entries=entries,
|
||||
)
|
||||
return None
|
||||
|
||||
def _lookup_en_fuzzy(self, query: str) -> Optional[SearchResult]:
|
||||
candidates = self.db.get_fuzzy_candidates(query)
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
best_candidate = None
|
||||
best_score = 0.0
|
||||
|
||||
for candidate in candidates:
|
||||
score = difflib.SequenceMatcher(None, query, candidate).ratio()
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_candidate = candidate
|
||||
|
||||
if best_candidate and best_score >= self.threshold:
|
||||
fuzzy_entries = self.db.find_exact(best_candidate)
|
||||
if fuzzy_entries:
|
||||
return SearchResult(
|
||||
query=query,
|
||||
matched_word=best_candidate,
|
||||
is_fuzzy=True,
|
||||
similarity_pct=int(round(best_score * 100)),
|
||||
language="en",
|
||||
entries=fuzzy_entries,
|
||||
)
|
||||
return None
|
||||
|
||||
def _lookup_tr_fuzzy(self, query: str) -> Optional[SearchResult]:
|
||||
candidates = self.db.get_tr_fuzzy_candidates(query)
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
best_candidate = None
|
||||
best_score = 0.0
|
||||
|
||||
norm_q = normalize_tr(query)
|
||||
|
||||
for candidate in candidates:
|
||||
# Score against normalized candidate as well
|
||||
s1 = difflib.SequenceMatcher(None, query, candidate).ratio()
|
||||
s2 = difflib.SequenceMatcher(None, norm_q, normalize_tr(candidate)).ratio()
|
||||
score = max(s1, s2)
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_candidate = candidate
|
||||
|
||||
if best_candidate and best_score >= self.threshold:
|
||||
fuzzy_entries = self.db.find_tr_exact(best_candidate)
|
||||
if fuzzy_entries:
|
||||
return SearchResult(
|
||||
query=query,
|
||||
matched_word=best_candidate,
|
||||
is_fuzzy=True,
|
||||
similarity_pct=int(round(best_score * 100)),
|
||||
language="tr",
|
||||
entries=fuzzy_entries,
|
||||
)
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
import ctypes
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import tkinter as tk
|
||||
from pathlib import Path
|
||||
from tkinter import messagebox, ttk
|
||||
|
||||
IS_WINDOWS = platform.system() == "Windows"
|
||||
if IS_WINDOWS:
|
||||
import winreg
|
||||
|
||||
|
||||
def get_bundle_dir() -> Path:
|
||||
"""Get the source directory whether running raw or inside PyInstaller bundle."""
|
||||
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
||||
return Path(sys._MEIPASS)
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
BUNDLE_DIR = get_bundle_dir()
|
||||
if str(BUNDLE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(BUNDLE_DIR))
|
||||
|
||||
try:
|
||||
from lex.src.catalog import catalog
|
||||
except ImportError:
|
||||
from src.catalog import catalog
|
||||
|
||||
|
||||
def get_default_install_dir() -> Path:
|
||||
if IS_WINDOWS:
|
||||
local_app_data = os.environ.get("LOCALAPPDATA")
|
||||
if local_app_data:
|
||||
return Path(local_app_data) / "Lex"
|
||||
return Path.home() / "AppData" / "Local" / "Lex"
|
||||
return Path.home() / ".lex"
|
||||
|
||||
|
||||
def add_to_windows_path(target_dir: str) -> bool:
|
||||
target_clean = os.path.normpath(target_dir)
|
||||
try:
|
||||
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Environment", 0, winreg.KEY_READ | winreg.KEY_WRITE) as key:
|
||||
try:
|
||||
current_path, _ = winreg.QueryValueEx(key, "Path")
|
||||
except FileNotFoundError:
|
||||
current_path = ""
|
||||
|
||||
path_elements = [p.strip() for p in current_path.split(";") if p.strip()]
|
||||
normalized = [os.path.normpath(p) for p in path_elements]
|
||||
|
||||
if target_clean in normalized:
|
||||
return False
|
||||
|
||||
path_elements.append(target_clean)
|
||||
new_path = ";".join(path_elements)
|
||||
winreg.SetValueEx(key, "Path", 0, winreg.REG_EXPAND_SZ, new_path)
|
||||
|
||||
HWND_BROADCAST = 0xFFFF
|
||||
WM_SETTINGCHANGE = 0x001A
|
||||
SMTO_ABORTIFHUNG = 0x0002
|
||||
result = ctypes.c_long()
|
||||
ctypes.windll.user32.SendMessageTimeoutW(
|
||||
HWND_BROADCAST,
|
||||
WM_SETTINGCHANGE,
|
||||
0,
|
||||
"Environment",
|
||||
SMTO_ABORTIFHUNG,
|
||||
1000,
|
||||
ctypes.byref(result),
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def register_windows_uninstaller(install_dir: Path) -> None:
|
||||
uninstall_key_path = r"Software\Microsoft\Windows\CurrentVersion\Uninstall\Lex"
|
||||
try:
|
||||
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, uninstall_key_path) as key:
|
||||
python_exe = shutil.which("pythonw") or shutil.which("python") or "python"
|
||||
uninstaller_script = install_dir / "src" / "gui_uninstaller.py"
|
||||
uninstall_cmd = f'"{python_exe}" "{uninstaller_script}"'
|
||||
|
||||
winreg.SetValueEx(key, "DisplayName", 0, winreg.REG_SZ, "LEX - Offline CLI Dictionary")
|
||||
winreg.SetValueEx(key, "DisplayVersion", 0, winreg.REG_SZ, catalog.get("app.version", "1.0.0"))
|
||||
winreg.SetValueEx(key, "Publisher", 0, winreg.REG_SZ, catalog.get("app.publisher", "Gravitiny"))
|
||||
winreg.SetValueEx(key, "InstallLocation", 0, winreg.REG_SZ, str(install_dir))
|
||||
winreg.SetValueEx(key, "UninstallString", 0, winreg.REG_SZ, uninstall_cmd)
|
||||
icon_file = install_dir / "assets" / "lex_icon.ico"
|
||||
if icon_file.exists():
|
||||
winreg.SetValueEx(key, "DisplayIcon", 0, winreg.REG_SZ, str(icon_file))
|
||||
winreg.SetValueEx(key, "NoModify", 0, winreg.REG_DWORD, 1)
|
||||
winreg.SetValueEx(key, "NoRepair", 0, winreg.REG_DWORD, 1)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
|
||||
class InstallerApp:
|
||||
def __init__(self, root: tk.Tk):
|
||||
self.root = root
|
||||
self.root.title(catalog.get("gui_installer.window_title", "LEX Setup Wizard"))
|
||||
self.root.geometry("520x360")
|
||||
self.root.resizable(False, False)
|
||||
|
||||
# Center window
|
||||
self.root.update_idletasks()
|
||||
w = self.root.winfo_width()
|
||||
h = self.root.winfo_height()
|
||||
x = (self.root.winfo_screenwidth() // 2) - (w // 2)
|
||||
y = (self.root.winfo_screenheight() // 2) - (h // 2)
|
||||
self.root.geometry(f"{w}x{h}+{x}+{y}")
|
||||
|
||||
self.install_dir = get_default_install_dir()
|
||||
self.var_path = tk.BooleanVar(value=True)
|
||||
|
||||
icon_path = BUNDLE_DIR / "assets" / "lex_icon.ico"
|
||||
if not icon_path.exists():
|
||||
icon_path = BUNDLE_DIR / "lex" / "assets" / "lex_icon.ico"
|
||||
if icon_path.exists():
|
||||
try:
|
||||
self.root.iconbitmap(str(icon_path))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self._create_widgets()
|
||||
|
||||
def _create_widgets(self):
|
||||
self.main_frame = ttk.Frame(self.root, padding="25 20 25 15")
|
||||
self.main_frame.pack(fill=tk.BOTH, expand=True)
|
||||
|
||||
# Header Title
|
||||
self.title_label = ttk.Label(
|
||||
self.main_frame,
|
||||
text=catalog.get("gui_installer.welcome_title"),
|
||||
font=("Segoe UI", 15, "bold"),
|
||||
)
|
||||
self.title_label.pack(anchor="w", pady=(0, 6))
|
||||
|
||||
# Subtitle
|
||||
self.subtitle_label = ttk.Label(
|
||||
self.main_frame,
|
||||
text=catalog.get("gui_installer.welcome_subtitle"),
|
||||
font=("Segoe UI", 9),
|
||||
wraplength=470,
|
||||
)
|
||||
self.subtitle_label.pack(anchor="w", pady=(0, 15))
|
||||
|
||||
# Destination frame
|
||||
self.dest_frame = ttk.LabelFrame(
|
||||
self.main_frame,
|
||||
text=catalog.get("gui_installer.destination_label"),
|
||||
padding="10 10",
|
||||
)
|
||||
self.dest_frame.pack(fill=tk.X, pady=(0, 15))
|
||||
|
||||
self.lbl_path = ttk.Label(
|
||||
self.dest_frame,
|
||||
text=str(self.install_dir),
|
||||
font=("Consolas", 8),
|
||||
foreground="#333333",
|
||||
)
|
||||
self.lbl_path.pack(anchor="w")
|
||||
|
||||
# Checkbox frame
|
||||
self.chk_path = ttk.Checkbutton(
|
||||
self.main_frame,
|
||||
text=catalog.get("gui_installer.chk_path"),
|
||||
variable=self.var_path,
|
||||
)
|
||||
self.chk_path.pack(anchor="w", pady=(0, 15))
|
||||
|
||||
# Progress bar (hidden initially)
|
||||
self.progress_bar = ttk.Progressbar(self.main_frame, mode="indeterminate", length=470)
|
||||
|
||||
# Status text
|
||||
self.status_label = ttk.Label(
|
||||
self.main_frame,
|
||||
text="",
|
||||
font=("Segoe UI", 8),
|
||||
foreground="#555555",
|
||||
)
|
||||
self.status_label.pack(anchor="w", pady=(0, 10))
|
||||
|
||||
# Buttons frame
|
||||
self.button_frame = ttk.Frame(self.main_frame)
|
||||
self.button_frame.pack(side=tk.BOTTOM, fill=tk.X)
|
||||
|
||||
self.btn_cancel = ttk.Button(
|
||||
self.button_frame,
|
||||
text=catalog.get("gui_installer.btn_cancel", "Cancel"),
|
||||
command=self.root.destroy,
|
||||
)
|
||||
self.btn_cancel.pack(side=tk.RIGHT, padx=(10, 0))
|
||||
|
||||
self.btn_install = ttk.Button(
|
||||
self.button_frame,
|
||||
text=catalog.get("gui_installer.btn_install", "Install Now"),
|
||||
command=self._start_install,
|
||||
)
|
||||
self.btn_install.pack(side=tk.RIGHT)
|
||||
|
||||
def _start_install(self):
|
||||
self.dest_frame.pack_forget()
|
||||
self.chk_path.pack_forget()
|
||||
self.btn_install.config(state=tk.DISABLED)
|
||||
self.btn_cancel.config(state=tk.DISABLED)
|
||||
|
||||
self.progress_bar.pack(before=self.status_label, fill=tk.X, pady=(10, 10))
|
||||
self.progress_bar.start(12)
|
||||
|
||||
thread = threading.Thread(target=self._install_worker, daemon=True)
|
||||
thread.start()
|
||||
|
||||
def _install_worker(self):
|
||||
python_exe = sys.executable
|
||||
# If running from a bundled installer, find actual system python
|
||||
if getattr(sys, "frozen", False):
|
||||
# Find python on system PATH or standard locations
|
||||
python_exe = shutil.which("python") or shutil.which("python3") or "python"
|
||||
|
||||
self._update_status(catalog.get("gui_installer.status_copying"))
|
||||
time.sleep(0.2)
|
||||
|
||||
self.install_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
source_root = BUNDLE_DIR
|
||||
if (BUNDLE_DIR / "lex").exists():
|
||||
source_root = BUNDLE_DIR / "lex"
|
||||
|
||||
# Copy source modules, catalog, data, assets, and manifest
|
||||
items = ["src", "catalog", "data", "assets", "manifest.json", "main.py", "__main__.py"]
|
||||
for item in items:
|
||||
src = source_root / item
|
||||
dst = self.install_dir / item
|
||||
if src.is_dir():
|
||||
if dst.exists():
|
||||
shutil.rmtree(dst)
|
||||
shutil.copytree(src, dst)
|
||||
elif src.is_file():
|
||||
shutil.copy2(src, dst)
|
||||
|
||||
|
||||
# Create instant lightweight lex.cmd launcher
|
||||
cmd_path = self.install_dir / "lex.cmd"
|
||||
with open(cmd_path, "w", encoding="utf-8") as f:
|
||||
f.write(f'@echo off\n"{python_exe}" "%~dp0main.py" %*\n')
|
||||
|
||||
time.sleep(0.2)
|
||||
|
||||
# Configure PATH
|
||||
if self.var_path.get() and IS_WINDOWS:
|
||||
self._update_status(catalog.get("gui_installer.status_path"))
|
||||
add_to_windows_path(str(self.install_dir))
|
||||
time.sleep(0.2)
|
||||
|
||||
# Register Registry Uninstaller
|
||||
if IS_WINDOWS:
|
||||
self._update_status(catalog.get("gui_installer.status_registry"))
|
||||
register_windows_uninstaller(self.install_dir)
|
||||
time.sleep(0.2)
|
||||
|
||||
self.root.after(0, self._on_finish)
|
||||
|
||||
|
||||
|
||||
def _update_status(self, text: str):
|
||||
self.root.after(0, lambda: self.status_label.config(text=text))
|
||||
|
||||
def _on_finish(self):
|
||||
self.progress_bar.stop()
|
||||
self.progress_bar.config(mode="determinate", value=100)
|
||||
|
||||
self.title_label.config(text=catalog.get("gui_installer.congrats_title"))
|
||||
self.subtitle_label.config(text=catalog.get("gui_installer.congrats_message"))
|
||||
self.status_label.config(text=catalog.get("gui_installer.status_complete"))
|
||||
|
||||
self.btn_install.pack_forget()
|
||||
self.btn_cancel.config(
|
||||
text=catalog.get("gui_installer.btn_finish", "Finish"),
|
||||
state=tk.NORMAL,
|
||||
command=self.root.destroy,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
root = tk.Tk()
|
||||
app = InstallerApp(root)
|
||||
root.mainloop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,205 @@
|
||||
import ctypes
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import tkinter as tk
|
||||
from pathlib import Path
|
||||
from tkinter import messagebox, ttk
|
||||
|
||||
IS_WINDOWS = platform.system() == "Windows"
|
||||
if IS_WINDOWS:
|
||||
import winreg
|
||||
|
||||
INSTALL_DIR = Path(__file__).resolve().parent.parent
|
||||
if str(INSTALL_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(INSTALL_DIR))
|
||||
|
||||
try:
|
||||
from lex.src.catalog import catalog
|
||||
except ImportError:
|
||||
from src.catalog import catalog
|
||||
|
||||
|
||||
def remove_from_windows_path(target_dir: str) -> bool:
|
||||
target_clean = os.path.normpath(target_dir)
|
||||
try:
|
||||
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Environment", 0, winreg.KEY_READ | winreg.KEY_WRITE) as key:
|
||||
try:
|
||||
current_path, _ = winreg.QueryValueEx(key, "Path")
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
|
||||
path_elements = [p.strip() for p in current_path.split(";") if p.strip()]
|
||||
new_elements = [p for p in path_elements if os.path.normpath(p) != target_clean]
|
||||
|
||||
if len(new_elements) == len(path_elements):
|
||||
return False
|
||||
|
||||
new_path = ";".join(new_elements)
|
||||
winreg.SetValueEx(key, "Path", 0, winreg.REG_EXPAND_SZ, new_path)
|
||||
|
||||
HWND_BROADCAST = 0xFFFF
|
||||
WM_SETTINGCHANGE = 0x001A
|
||||
SMTO_ABORTIFHUNG = 0x0002
|
||||
result = ctypes.c_long()
|
||||
ctypes.windll.user32.SendMessageTimeoutW(
|
||||
HWND_BROADCAST,
|
||||
WM_SETTINGCHANGE,
|
||||
0,
|
||||
"Environment",
|
||||
SMTO_ABORTIFHUNG,
|
||||
1000,
|
||||
ctypes.byref(result),
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def remove_windows_registry_entry() -> None:
|
||||
uninstall_key_path = r"Software\Microsoft\Windows\CurrentVersion\Uninstall"
|
||||
try:
|
||||
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, uninstall_key_path, 0, winreg.KEY_WRITE) as parent_key:
|
||||
winreg.DeleteKey(parent_key, "Lex")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class UninstallerApp:
|
||||
def __init__(self, root: tk.Tk):
|
||||
self.root = root
|
||||
self.root.title(catalog.get("gui_uninstaller.window_title", "LEX Uninstaller"))
|
||||
self.root.geometry("480x280")
|
||||
self.root.resizable(False, False)
|
||||
|
||||
# Center window
|
||||
self.root.update_idletasks()
|
||||
w = self.root.winfo_width()
|
||||
h = self.root.winfo_height()
|
||||
x = (self.root.winfo_screenwidth() // 2) - (w // 2)
|
||||
y = (self.root.winfo_screenheight() // 2) - (h // 2)
|
||||
self.root.geometry(f"{w}x{h}+{x}+{y}")
|
||||
|
||||
# Try set icon
|
||||
icon_path = INSTALL_DIR / "assets" / "lex_icon.ico"
|
||||
if icon_path.exists():
|
||||
try:
|
||||
self.root.iconbitmap(str(icon_path))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self._create_widgets()
|
||||
|
||||
def _create_widgets(self):
|
||||
main_frame = ttk.Frame(self.root, padding="20 20 20 15")
|
||||
main_frame.pack(fill=tk.BOTH, expand=True)
|
||||
|
||||
self.title_label = ttk.Label(
|
||||
main_frame,
|
||||
text=catalog.get("gui_uninstaller.confirm_title", "Uninstall LEX"),
|
||||
font=("Segoe UI", 14, "bold"),
|
||||
)
|
||||
self.title_label.pack(anchor="w", pady=(0, 5))
|
||||
|
||||
self.subtitle_label = ttk.Label(
|
||||
main_frame,
|
||||
text=catalog.get("gui_uninstaller.confirm_subtitle"),
|
||||
font=("Segoe UI", 9),
|
||||
wraplength=440,
|
||||
)
|
||||
self.subtitle_label.pack(anchor="w", pady=(0, 20))
|
||||
|
||||
self.progress_bar = ttk.Progressbar(main_frame, mode="determinate", length=440)
|
||||
self.progress_bar.pack(pady=(0, 10))
|
||||
|
||||
self.status_label = ttk.Label(
|
||||
main_frame,
|
||||
text="",
|
||||
font=("Segoe UI", 8),
|
||||
foreground="#555555",
|
||||
)
|
||||
self.status_label.pack(anchor="w", pady=(0, 15))
|
||||
|
||||
self.button_frame = ttk.Frame(main_frame)
|
||||
self.button_frame.pack(side=tk.BOTTOM, fill=tk.X)
|
||||
|
||||
self.btn_cancel = ttk.Button(
|
||||
self.button_frame,
|
||||
text=catalog.get("gui_uninstaller.btn_cancel", "Cancel"),
|
||||
command=self.root.destroy,
|
||||
)
|
||||
self.btn_cancel.pack(side=tk.RIGHT, padx=(10, 0))
|
||||
|
||||
self.btn_uninstall = ttk.Button(
|
||||
self.button_frame,
|
||||
text=catalog.get("gui_uninstaller.btn_uninstall", "Uninstall"),
|
||||
command=self._start_uninstall,
|
||||
)
|
||||
self.btn_uninstall.pack(side=tk.RIGHT)
|
||||
|
||||
def _start_uninstall(self):
|
||||
self.btn_uninstall.config(state=tk.DISABLED)
|
||||
self.btn_cancel.config(state=tk.DISABLED)
|
||||
self.progress_bar.config(mode="indeterminate")
|
||||
self.progress_bar.start(15)
|
||||
|
||||
thread = threading.Thread(target=self._uninstall_worker, daemon=True)
|
||||
thread.start()
|
||||
|
||||
def _uninstall_worker(self):
|
||||
self._update_status(catalog.get("gui_uninstaller.status_removing_path"))
|
||||
time.sleep(0.4)
|
||||
if IS_WINDOWS:
|
||||
remove_from_windows_path(str(INSTALL_DIR))
|
||||
|
||||
self._update_status(catalog.get("gui_uninstaller.status_removing_registry"))
|
||||
time.sleep(0.4)
|
||||
if IS_WINDOWS:
|
||||
remove_windows_registry_entry()
|
||||
|
||||
self._update_status(catalog.get("gui_uninstaller.status_removing_files"))
|
||||
time.sleep(0.5)
|
||||
|
||||
# Self-destruct batch script
|
||||
if IS_WINDOWS:
|
||||
cleanup_bat = INSTALL_DIR.parent / "lex_cleanup.bat"
|
||||
with open(cleanup_bat, "w", encoding="utf-8") as f:
|
||||
f.write(
|
||||
f'@echo off\n'
|
||||
f'timeout /t 2 /nobreak >nul\n'
|
||||
f'rmdir /s /q "{INSTALL_DIR}" >nul 2>&1\n'
|
||||
f'del "%~f0" >nul 2>&1\n'
|
||||
)
|
||||
os.spawnl(os.P_NOWAIT, os.environ.get("COMSPEC", "cmd.exe"), "cmd.exe", "/c", str(cleanup_bat))
|
||||
|
||||
self.root.after(0, self._on_finish)
|
||||
|
||||
def _update_status(self, text: str):
|
||||
self.root.after(0, lambda: self.status_label.config(text=text))
|
||||
|
||||
def _on_finish(self):
|
||||
self.progress_bar.stop()
|
||||
self.progress_bar.config(mode="determinate", value=100)
|
||||
self.title_label.config(text=catalog.get("gui_uninstaller.success_title"))
|
||||
self.subtitle_label.config(text=catalog.get("gui_uninstaller.success_message"))
|
||||
self.status_label.config(text=catalog.get("gui_uninstaller.status_complete"))
|
||||
|
||||
self.btn_uninstall.pack_forget()
|
||||
self.btn_cancel.config(
|
||||
text=catalog.get("gui_uninstaller.btn_close", "Close"),
|
||||
state=tk.NORMAL,
|
||||
command=self.root.destroy,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
root = tk.Tk()
|
||||
app = UninstallerApp(root)
|
||||
root.mainloop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,23 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
def load_manifest() -> Dict[str, Any]:
|
||||
"""Load metadata from manifest.json located at package root."""
|
||||
base_dir = Path(__file__).resolve().parent.parent
|
||||
manifest_path = base_dir / "manifest.json"
|
||||
if manifest_path.exists():
|
||||
try:
|
||||
with open(manifest_path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
"name": "Lex",
|
||||
"version": "1.0.0",
|
||||
"stage": "Beta",
|
||||
"description": "Offline English Dictionary & Context Assistant",
|
||||
"dependencies": ["rich>=13.0.0"],
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
from rich.console import Console
|
||||
from rich.panel import Panel
|
||||
|
||||
try:
|
||||
from lex.src.catalog import catalog
|
||||
from lex.src.fuzzy import SearchResult
|
||||
except ImportError:
|
||||
from src.catalog import catalog
|
||||
from src.fuzzy import SearchResult
|
||||
|
||||
|
||||
class QuickRenderer:
|
||||
"""Renders dictionary search results in the clean terminal card format."""
|
||||
|
||||
def __init__(self, console: Console = None):
|
||||
self.console = console or Console()
|
||||
|
||||
def render_not_found(self, query: str) -> None:
|
||||
msg = catalog.format("status.nothing_found", query=query)
|
||||
self.console.print(f"[dim]{msg}[/dim]")
|
||||
|
||||
def render_db_missing(self, path: str) -> None:
|
||||
msg = catalog.format("status.db_missing", path=path)
|
||||
self.console.print(f"[red]{msg}[/red]")
|
||||
|
||||
def render_result(self, result: SearchResult) -> None:
|
||||
if result.is_fuzzy:
|
||||
notice = catalog.format(
|
||||
"status.fuzzy_notice",
|
||||
matched_word=result.matched_word,
|
||||
similarity=result.similarity_pct,
|
||||
)
|
||||
self.console.print(f"[yellow]{notice}[/yellow]\n")
|
||||
|
||||
if result.language == "tr":
|
||||
self._render_turkish_result(result)
|
||||
else:
|
||||
self._render_english_result(result)
|
||||
|
||||
def _render_english_result(self, result: SearchResult) -> None:
|
||||
primary_entry = result.entries[0]
|
||||
word_header = f"[bold cyan]{primary_entry.word.upper()}[/bold cyan] [dim magenta]({primary_entry.pos})[/dim magenta]"
|
||||
|
||||
body_lines = []
|
||||
|
||||
# Definition
|
||||
def_label = catalog.get("labels.definition")
|
||||
body_lines.append(f"[bold]{def_label}:[/bold] {primary_entry.definition}")
|
||||
|
||||
# Usage Examples (up to 3 for quick mode)
|
||||
all_examples = []
|
||||
for entry in result.entries:
|
||||
for ex in getattr(entry, "examples", []):
|
||||
if ex not in all_examples:
|
||||
all_examples.append(ex)
|
||||
|
||||
if all_examples:
|
||||
body_lines.append("")
|
||||
ex_label = catalog.get("labels.examples")
|
||||
body_lines.append(f"[bold]{ex_label}:[/bold]")
|
||||
for ex in all_examples[:3]:
|
||||
formatted_ex = catalog.format("formatting.bullet_point", example=ex)
|
||||
body_lines.append(f"[green]{formatted_ex}[/green]")
|
||||
|
||||
# Synonyms
|
||||
all_synonyms = []
|
||||
for entry in result.entries:
|
||||
for syn in getattr(entry, "synonyms", []):
|
||||
if syn not in all_synonyms:
|
||||
all_synonyms.append(syn)
|
||||
|
||||
if all_synonyms:
|
||||
body_lines.append("")
|
||||
syn_label = catalog.get("labels.synonyms")
|
||||
sep = catalog.get("formatting.synonym_separator", ", ")
|
||||
syn_str = sep.join(all_synonyms[:6])
|
||||
body_lines.append(f"[bold]{syn_label}:[/bold] [yellow]{syn_str}[/yellow]")
|
||||
|
||||
card_content = "\n".join(body_lines)
|
||||
panel = Panel(
|
||||
card_content,
|
||||
title=word_header,
|
||||
title_align="left",
|
||||
border_style="bright_blue",
|
||||
padding=(1, 2),
|
||||
)
|
||||
self.console.print(panel)
|
||||
|
||||
def _render_turkish_result(self, result: SearchResult) -> None:
|
||||
primary_entry = result.entries[0]
|
||||
word_header = f"[bold cyan]{primary_entry.word.upper()}[/bold cyan] [dim magenta](Turkish {primary_entry.pos})[/dim magenta]"
|
||||
|
||||
body_lines = []
|
||||
|
||||
# English Glosses / Meanings
|
||||
gloss_label = catalog.get("labels.tr_english_meanings", "English Meanings")
|
||||
body_lines.append(f"[bold]{gloss_label}:[/bold]")
|
||||
|
||||
all_glosses = []
|
||||
for entry in result.entries:
|
||||
for g in getattr(entry, "glosses", []):
|
||||
if g not in all_glosses:
|
||||
all_glosses.append(g)
|
||||
|
||||
for idx, gloss in enumerate(all_glosses[:4], 1):
|
||||
body_lines.append(f" {idx}. [bold green]{gloss}[/bold green]")
|
||||
|
||||
# Examples
|
||||
all_examples = []
|
||||
for entry in result.entries:
|
||||
for ex in getattr(entry, "examples", []):
|
||||
if ex not in all_examples:
|
||||
all_examples.append(ex)
|
||||
|
||||
if all_examples:
|
||||
body_lines.append("")
|
||||
ex_label = catalog.get("labels.examples")
|
||||
body_lines.append(f"[bold]{ex_label}:[/bold]")
|
||||
for ex in all_examples[:3]:
|
||||
formatted_ex = catalog.format("formatting.bullet_point", example=ex)
|
||||
body_lines.append(f"[green]{formatted_ex}[/green]")
|
||||
|
||||
# Synonyms / Related
|
||||
all_synonyms = []
|
||||
for entry in result.entries:
|
||||
for syn in getattr(entry, "synonyms", []):
|
||||
if syn not in all_synonyms:
|
||||
all_synonyms.append(syn)
|
||||
|
||||
if all_synonyms:
|
||||
body_lines.append("")
|
||||
syn_label = catalog.get("labels.tr_synonyms", "Related Words")
|
||||
sep = catalog.get("formatting.synonym_separator", ", ")
|
||||
syn_str = sep.join(all_synonyms[:6])
|
||||
body_lines.append(f"[bold]{syn_label}:[/bold] [yellow]{syn_str}[/yellow]")
|
||||
|
||||
card_content = "\n".join(body_lines)
|
||||
panel = Panel(
|
||||
card_content,
|
||||
title=word_header,
|
||||
title_align="left",
|
||||
border_style="bright_cyan",
|
||||
padding=(1, 2),
|
||||
)
|
||||
self.console.print(panel)
|
||||
@@ -0,0 +1,28 @@
|
||||
# SEC - Quick CLI Cheat Sheet & Code Snippet Assistant
|
||||
|
||||
## Project Purpose
|
||||
A lightweight, lightning-fast CLI cheat sheet and code snippet assistant powered by the `cheat.sh` engine, ergonomic sol-el keyboard layout, smart query routing, and optional clipboard integration.
|
||||
|
||||
---
|
||||
|
||||
## Architectural Decisions
|
||||
1. **Name & Ergonomics:** `sec` (optimized for left-hand QWERTY reachability in dropdown/Quake terminals).
|
||||
2. **Backend & Engine:** Direct live queries to the `cheat.sh` API with smart multi-token routing.
|
||||
3. **Smart Query Router:**
|
||||
- Strategy 1: Targeted language/tool lookup (`cht.sh/<target>/<query>`).
|
||||
- Strategy 2: Global semantic fallback search (`cht.sh/~<query>`).
|
||||
4. **Offline Exact-Query Cache:** Lightweight SQLite or file-based cache for previously fetched queries so repeated lookups work offline.
|
||||
5. **Clipboard Integration:** Optional `-c` / `--copy` flag to automatically extract and copy executable code blocks to the clipboard.
|
||||
6. **Centralized UI/String Catalog:** Centralized JSON string catalog (`catalog/strings.json`). No hardcoded UI strings in code.
|
||||
7. **Code Standards:** Professional English in all code, comments, catalogs, and documentation. No emojis in terminal UI or codebase.
|
||||
8. **Manifest & Versioning:** `manifest.json` tracking semver, dependencies, and changelog, wired to `-V` / `--version`.
|
||||
|
||||
---
|
||||
|
||||
## Pending Topics & Decisions
|
||||
- [x] **1. Live API Client & Multi-token Routing:** Tilde-based search, candidates fallback chain, error/index suppression.
|
||||
- [x] **2. Clipboard Dual Mode:** `-c` for executable code only, `-c a` for full response.
|
||||
- [x] **3. Offline SQLite Cache:** Automatic caching of valid queries in `data/cache.db`.
|
||||
- [ ] **4. Deterministic Non-AI Keyword & Intent Engine:** Build a purely offline, algorithmic keyword classifier (trie/inverted-index/alias table) that parses freeform user prompts into exact `cheat.sh` canonical topics and flags without external AI APIs.
|
||||
- [ ] **5. ANSI Rendering & Paging:** Optional terminal paging for multi-page cheat sheets.
|
||||
- [ ] **6. Cache Expiration & Invalidation:** TTL or explicit cache refresh flags (`--refresh`).
|
||||
@@ -0,0 +1,16 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
if str(BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(BASE_DIR))
|
||||
if str(BASE_DIR.parent) not in sys.path:
|
||||
sys.path.insert(0, str(BASE_DIR.parent))
|
||||
|
||||
try:
|
||||
from sec.src.cli import run_cli
|
||||
except ImportError:
|
||||
from src.cli import run_cli
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(run_cli(sys.argv[1:]))
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"app": {
|
||||
"name": "SEC",
|
||||
"description": "CLI Cheat Sheet & Code Snippet Assistant",
|
||||
"version": "1.0.0",
|
||||
"version_output": "{name} v{version} [{stage}] - {description}"
|
||||
},
|
||||
"status": {
|
||||
"fetching": "Querying cheat sheet for: \"{query}\"...",
|
||||
"not_found": "No cheat sheet found for: \"{query}\".",
|
||||
"offline_cached": "[Cached Result - Offline Mode]",
|
||||
"copied_code": "Copied executable code to clipboard.",
|
||||
"copied_all": "Copied full response to clipboard.",
|
||||
"clipboard_error": "Unable to copy to clipboard.",
|
||||
"network_error": "Unable to connect to cheat.sh. Please check your internet connection."
|
||||
},
|
||||
"labels": {
|
||||
"usage_title": "Usage:",
|
||||
"examples_title": "Examples:",
|
||||
"query_header": "CHEAT SHEET: {title}",
|
||||
"source_badge": "cheat.sh"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
if str(BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(BASE_DIR))
|
||||
if str(BASE_DIR.parent) not in sys.path:
|
||||
sys.path.insert(0, str(BASE_DIR.parent))
|
||||
|
||||
try:
|
||||
from sec.src.cli import run_cli
|
||||
except ImportError:
|
||||
from src.cli import run_cli
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(run_cli(sys.argv[1:]))
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "Sec",
|
||||
"display_name": "SEC - CLI Cheat Sheet & Code Snippet Assistant",
|
||||
"description": "Lightning-fast CLI cheat sheet and code snippet assistant powered by cheat.sh with smart routing and clipboard copy.",
|
||||
"version": "1.0.0",
|
||||
"stage": "Alpha",
|
||||
"release_type": "Initial",
|
||||
"created_at": "2026-10-02",
|
||||
"updated_at": "2026-10-02",
|
||||
"license": "MIT",
|
||||
"author": "Gravitiny Team",
|
||||
"dependencies": [
|
||||
"requests>=2.28.0",
|
||||
"rich>=13.0.0"
|
||||
],
|
||||
"features": [
|
||||
"Smart Multi-Token cheat.sh Query Router",
|
||||
"Left-Hand Optimized QWERTY Command Name (sec)",
|
||||
"Clipboard Code Extraction (--copy / -c)",
|
||||
"Offline Query Cache",
|
||||
"Centralized JSON Message and UI Catalog"
|
||||
],
|
||||
"changelog": [
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"date": "2026-10-02",
|
||||
"stage": "Alpha",
|
||||
"type": "Initial Scaffold",
|
||||
"changes": [
|
||||
"Initial project scaffold and architecture definition for SEC."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
class Student(object):
|
||||
name = ""
|
||||
age = 0
|
||||
major = ""
|
||||
|
||||
# The class "constructor" - It's actually an initializer
|
||||
def __init__(self, name, age, major):
|
||||
self.name = name
|
||||
self.age = age
|
||||
self.major = major
|
||||
|
||||
def make_student(name, age, major):
|
||||
student = Student(name, age, major)
|
||||
return student
|
||||
|
||||
# Note that even though one of the principles in Python's philosophy is
|
||||
# *"there should be one—and preferably only one—obvious way to do it"*,
|
||||
# there are still multiple ways to do this. You can also use the two
|
||||
# following snippets of code to take advantage of Python's dynamic
|
||||
# capabilities:
|
||||
|
||||
class Student(object):
|
||||
name = ""
|
||||
age = 0
|
||||
major = ""
|
||||
|
||||
def make_student(name, age, major):
|
||||
student = Student()
|
||||
student.name = name
|
||||
student.age = age
|
||||
student.major = major
|
||||
# Note: I didn't need to create a variable in the class definition before doing
|
||||
this.
|
||||
student.gpa = float(4.0)
|
||||
return student
|
||||
|
||||
# I prefer the former, but there are instances where the latter can be
|
||||
# useful – one being when working with document databases like MongoDB.
|
||||
#
|
||||
# [Wulfram] [so/q/15081542] [cc by-sa 3.0]
|
||||
@@ -0,0 +1 @@
|
||||
"""SEC - Quick CLI Cheat Sheet & Code Snippet Assistant."""
|
||||
@@ -0,0 +1,47 @@
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
class StringCatalog:
|
||||
"""Centralized catalog for user-facing strings and message templates."""
|
||||
|
||||
_instance = None
|
||||
_catalog: Dict[str, Any] = {}
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super(StringCatalog, cls).__new__(cls)
|
||||
cls._instance._load_catalog()
|
||||
return cls._instance
|
||||
|
||||
def _load_catalog(self) -> None:
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
catalog_path = os.path.join(base_dir, "catalog", "strings.json")
|
||||
if os.path.exists(catalog_path):
|
||||
with open(catalog_path, "r", encoding="utf-8") as f:
|
||||
self._catalog = json.load(f)
|
||||
else:
|
||||
self._catalog = {}
|
||||
|
||||
def get(self, key_path: str, default: str = "") -> str:
|
||||
"""Retrieve a string from the catalog using dot notation."""
|
||||
parts = key_path.split(".")
|
||||
current = self._catalog
|
||||
for part in parts:
|
||||
if isinstance(current, dict) and part in current:
|
||||
current = current[part]
|
||||
else:
|
||||
return default
|
||||
return str(current) if current is not None else default
|
||||
|
||||
def format(self, key_path: str, **kwargs: Any) -> str:
|
||||
"""Retrieve a template string and interpolate keyword arguments."""
|
||||
template = self.get(key_path, "")
|
||||
try:
|
||||
return template.format(**kwargs)
|
||||
except KeyError:
|
||||
return template
|
||||
|
||||
|
||||
catalog = StringCatalog()
|
||||
@@ -0,0 +1,118 @@
|
||||
import sys
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
try:
|
||||
from sec.src.catalog import catalog
|
||||
from sec.src.client import CheatClient
|
||||
from sec.src.clipboard import copy_to_clipboard, extract_code_only, strip_ansi
|
||||
from sec.src.manifest import load_manifest
|
||||
from sec.src.renderer import SnippetRenderer
|
||||
from sec.src.router import QueryRouter
|
||||
except ImportError:
|
||||
from src.catalog import catalog
|
||||
from src.client import CheatClient
|
||||
from src.clipboard import copy_to_clipboard, extract_code_only, strip_ansi
|
||||
from src.manifest import load_manifest
|
||||
from src.renderer import SnippetRenderer
|
||||
from src.router import QueryRouter
|
||||
|
||||
|
||||
def parse_arguments(raw_args: List[str]) -> Tuple[List[str], Optional[str], bool]:
|
||||
"""Parse raw arguments into (query_tokens, copy_mode, is_version_flag)."""
|
||||
copy_mode = None
|
||||
is_version = False
|
||||
query_tokens: List[str] = []
|
||||
|
||||
i = 0
|
||||
while i < len(raw_args):
|
||||
arg = raw_args[i]
|
||||
|
||||
if arg in ["-V", "-v", "--version"]:
|
||||
is_version = True
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if arg in ["-c", "--copy"]:
|
||||
# Check if next token is 'a' or 'all'
|
||||
if i + 1 < len(raw_args) and raw_args[i + 1].lower() in ["a", "all"]:
|
||||
copy_mode = "all"
|
||||
i += 2
|
||||
continue
|
||||
else:
|
||||
copy_mode = "code"
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if arg in ["--copy-all", "-ca"]:
|
||||
copy_mode = "all"
|
||||
i += 1
|
||||
continue
|
||||
|
||||
query_tokens.append(arg)
|
||||
i += 1
|
||||
|
||||
return query_tokens, copy_mode, is_version
|
||||
|
||||
|
||||
def run_cli(args: Optional[List[str]] = None) -> int:
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
raw_args = args if args is not None else sys.argv[1:]
|
||||
query_tokens, copy_mode, is_version = parse_arguments(raw_args)
|
||||
|
||||
if is_version:
|
||||
manifest = load_manifest()
|
||||
version_text = catalog.format(
|
||||
"app.version_output",
|
||||
name=manifest.get("name", "SEC"),
|
||||
version=manifest.get("version", "1.0.0"),
|
||||
stage=manifest.get("stage", "Alpha"),
|
||||
description=manifest.get("description", ""),
|
||||
)
|
||||
print(version_text)
|
||||
return 0
|
||||
|
||||
if not query_tokens:
|
||||
manifest = load_manifest()
|
||||
print(f"{manifest.get('name', 'SEC')} v{manifest.get('version', '1.0.0')} [{manifest.get('stage', 'Alpha')}] - {manifest.get('description', '')}")
|
||||
print("Usage: sec <query...> [-c] [-c a]")
|
||||
print("Examples:")
|
||||
print(" sec python read json")
|
||||
print(" sec tar extract")
|
||||
print(" sec linux memory usage")
|
||||
print(" sec git undo commit -c # Copy code only to clipboard")
|
||||
print(" sec docker build -c a # Copy full response to clipboard")
|
||||
return 0
|
||||
|
||||
raw_query = " ".join(query_tokens)
|
||||
router = QueryRouter()
|
||||
routed = router.route(query_tokens)
|
||||
|
||||
client = CheatClient()
|
||||
renderer = SnippetRenderer()
|
||||
|
||||
result = client.fetch(routed)
|
||||
if not result:
|
||||
renderer.render_not_found(raw_query)
|
||||
return 0
|
||||
|
||||
copied = False
|
||||
is_all_copy = False
|
||||
if copy_mode:
|
||||
if copy_mode == "all":
|
||||
text_to_copy = strip_ansi(result.content)
|
||||
is_all_copy = True
|
||||
else:
|
||||
text_to_copy = extract_code_only(result.content)
|
||||
is_all_copy = False
|
||||
|
||||
if text_to_copy:
|
||||
copied = copy_to_clipboard(text_to_copy)
|
||||
|
||||
renderer.render_result(result, copied=copied, is_all_copy=is_all_copy)
|
||||
return 0
|
||||
@@ -0,0 +1,131 @@
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
import requests
|
||||
|
||||
from sec.src.router import RoutedQuery
|
||||
|
||||
|
||||
@dataclass
|
||||
class FetchResult:
|
||||
query: str
|
||||
url: str
|
||||
content: str
|
||||
is_cached: bool
|
||||
is_fallback: bool
|
||||
|
||||
|
||||
class CheatClient:
|
||||
"""Handles HTTP requests to cheat.sh and manages the local query cache."""
|
||||
|
||||
def __init__(self, cache_db_path: Optional[str] = None, timeout: int = 6):
|
||||
if cache_db_path is None:
|
||||
base_dir = Path(__file__).resolve().parent.parent
|
||||
data_dir = base_dir / "data"
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
cache_db_path = str(data_dir / "cache.db")
|
||||
self.cache_db_path = cache_db_path
|
||||
self.timeout = timeout
|
||||
self._init_cache()
|
||||
|
||||
def _init_cache(self) -> None:
|
||||
conn = sqlite3.connect(self.cache_db_path)
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
CREATE TABLE IF NOT EXISTS query_cache (
|
||||
query_key TEXT PRIMARY KEY,
|
||||
url TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
timestamp REAL NOT NULL
|
||||
);
|
||||
""")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def _get_from_cache(self, query_key: str) -> Optional[str]:
|
||||
try:
|
||||
conn = sqlite3.connect(self.cache_db_path)
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT content FROM query_cache WHERE query_key = ?", (query_key,))
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
return row[0] if row else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def _save_to_cache(self, query_key: str, url: str, content: str) -> None:
|
||||
try:
|
||||
conn = sqlite3.connect(self.cache_db_path)
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
INSERT OR REPLACE INTO query_cache (query_key, url, content, timestamp)
|
||||
VALUES (?, ?, ?, ?);
|
||||
""", (query_key, url, content, time.time()))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _is_error_response(self, text: str) -> bool:
|
||||
if not text or not text.strip():
|
||||
return True
|
||||
lower = text.lower()
|
||||
if (
|
||||
"unknown cheat sheet" in lower
|
||||
or "404 not found" in lower
|
||||
or "page not found" in lower
|
||||
or "internal::list" in lower
|
||||
or text.startswith("#[internal::list]")
|
||||
or text.startswith("internal::list")
|
||||
):
|
||||
return True
|
||||
if len(text.strip()) < 5:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _http_get(self, url: str) -> Optional[str]:
|
||||
headers = {
|
||||
"User-Agent": "curl/7.88.1",
|
||||
"Accept": "*/*",
|
||||
}
|
||||
# ?T ensures plain text without html wrapping
|
||||
fetch_url = url if "?" in url else f"{url}?T"
|
||||
try:
|
||||
resp = requests.get(fetch_url, headers=headers, timeout=self.timeout)
|
||||
if resp.status_code == 200 and not self._is_error_response(resp.text):
|
||||
return resp.text.strip()
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
def fetch(self, routed: RoutedQuery) -> Optional[FetchResult]:
|
||||
query_key = routed.raw_query
|
||||
|
||||
# 1. Attempt candidate URLs in priority order
|
||||
for idx, url in enumerate(routed.candidate_urls):
|
||||
content = self._http_get(url)
|
||||
if content:
|
||||
self._save_to_cache(query_key, url, content)
|
||||
return FetchResult(
|
||||
query=routed.raw_query,
|
||||
url=url,
|
||||
content=content,
|
||||
is_cached=False,
|
||||
is_fallback=(idx > 0),
|
||||
)
|
||||
|
||||
# 2. Fallback to local cache if offline or network error
|
||||
cached_content = self._get_from_cache(query_key)
|
||||
if cached_content and not self._is_error_response(cached_content):
|
||||
return FetchResult(
|
||||
query=routed.raw_query,
|
||||
url=routed.primary_url,
|
||||
content=cached_content,
|
||||
is_cached=True,
|
||||
is_fallback=False,
|
||||
)
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,118 @@
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import subprocess
|
||||
from typing import List
|
||||
|
||||
ANSI_ESCAPE_RE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
|
||||
|
||||
|
||||
def strip_ansi(text: str) -> str:
|
||||
"""Remove ANSI escape sequences from text."""
|
||||
return ANSI_ESCAPE_RE.sub("", text)
|
||||
|
||||
|
||||
def extract_code_only(text: str) -> str:
|
||||
"""Extract only executable code lines, removing comments, blank lines, and headers."""
|
||||
clean_text = strip_ansi(text)
|
||||
lines = clean_text.splitlines()
|
||||
|
||||
code_lines: List[str] = []
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
if not stripped:
|
||||
continue
|
||||
|
||||
# Skip comment lines
|
||||
if (
|
||||
stripped.startswith("#")
|
||||
or stripped.startswith("//")
|
||||
or stripped.startswith("/*")
|
||||
or stripped.startswith("*")
|
||||
or stripped.startswith("*/")
|
||||
or stripped.startswith("rem ")
|
||||
or stripped.startswith("--")
|
||||
or stripped.startswith('"""')
|
||||
or stripped.startswith("'''")
|
||||
):
|
||||
continue
|
||||
|
||||
# Skip cheat.sh page header artifacts
|
||||
if stripped.startswith("cheat:") or stripped.startswith("tags:") or stripped == "---":
|
||||
continue
|
||||
|
||||
code_lines.append(line)
|
||||
|
||||
return "\n".join(code_lines).strip()
|
||||
|
||||
|
||||
def copy_to_clipboard(text: str) -> bool:
|
||||
"""Copy text to system clipboard across Windows, macOS, and Linux."""
|
||||
if not text:
|
||||
return False
|
||||
|
||||
system = platform.system()
|
||||
|
||||
if system == "Windows":
|
||||
try:
|
||||
GMEM_MOVEABLE = 0x0002
|
||||
CF_UNICODETEXT = 13
|
||||
|
||||
user32 = ctypes.windll.user32
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
|
||||
kernel32.GlobalAlloc.restype = wintypes.HGLOBAL
|
||||
kernel32.GlobalAlloc.argtypes = [wintypes.UINT, ctypes.c_size_t]
|
||||
|
||||
kernel32.GlobalLock.restype = wintypes.LPVOID
|
||||
kernel32.GlobalLock.argtypes = [wintypes.HGLOBAL]
|
||||
|
||||
kernel32.GlobalUnlock.argtypes = [wintypes.HGLOBAL]
|
||||
user32.SetClipboardData.argtypes = [wintypes.UINT, wintypes.HANDLE]
|
||||
|
||||
encoded = text.encode("utf-16le") + b"\x00\x00"
|
||||
|
||||
if not user32.OpenClipboard(None):
|
||||
return False
|
||||
|
||||
user32.EmptyClipboard()
|
||||
h_mem = kernel32.GlobalAlloc(GMEM_MOVEABLE, len(encoded))
|
||||
if not h_mem:
|
||||
user32.CloseClipboard()
|
||||
return False
|
||||
|
||||
p_mem = kernel32.GlobalLock(h_mem)
|
||||
if not p_mem:
|
||||
user32.CloseClipboard()
|
||||
return False
|
||||
|
||||
ctypes.memmove(p_mem, encoded, len(encoded))
|
||||
kernel32.GlobalUnlock(h_mem)
|
||||
|
||||
user32.SetClipboardData(CF_UNICODETEXT, h_mem)
|
||||
user32.CloseClipboard()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
elif system == "Darwin":
|
||||
try:
|
||||
p = subprocess.Popen(["pbcopy"], stdin=subprocess.PIPE)
|
||||
p.communicate(text.encode("utf-8"))
|
||||
return p.returncode == 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
else:
|
||||
# Linux (xclip / wl-copy / xsel)
|
||||
for cmd in [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"]]:
|
||||
try:
|
||||
p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
|
||||
p.communicate(text.encode("utf-8"))
|
||||
if p.returncode == 0:
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
return False
|
||||
@@ -0,0 +1,22 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
def load_manifest() -> Dict[str, Any]:
|
||||
"""Load metadata from manifest.json located at package root."""
|
||||
base_dir = Path(__file__).resolve().parent.parent
|
||||
manifest_path = base_dir / "manifest.json"
|
||||
if manifest_path.exists():
|
||||
try:
|
||||
with open(manifest_path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
"name": "Sec",
|
||||
"version": "1.0.0",
|
||||
"stage": "Alpha",
|
||||
"description": "CLI Cheat Sheet & Code Snippet Assistant",
|
||||
"dependencies": ["requests>=2.28.0", "rich>=13.0.0"],
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
from rich.console import Console
|
||||
from rich.panel import Panel
|
||||
from rich.text import Text
|
||||
|
||||
try:
|
||||
from sec.src.catalog import catalog
|
||||
from sec.src.client import FetchResult
|
||||
except ImportError:
|
||||
from src.catalog import catalog
|
||||
from src.client import FetchResult
|
||||
|
||||
|
||||
class SnippetRenderer:
|
||||
"""Renders cheat.sh responses in styled terminal format."""
|
||||
|
||||
def __init__(self, console: Console = None):
|
||||
self.console = console or Console()
|
||||
|
||||
def render_not_found(self, query: str) -> None:
|
||||
msg = catalog.format("status.not_found", query=query)
|
||||
self.console.print(f"[dim]{msg}[/dim]")
|
||||
|
||||
def render_network_error(self) -> None:
|
||||
msg = catalog.get("status.network_error")
|
||||
self.console.print(f"[red]{msg}[/red]")
|
||||
|
||||
def render_clipboard_notice(self, is_all: bool) -> None:
|
||||
key = "status.copied_all" if is_all else "status.copied_code"
|
||||
msg = catalog.get(key)
|
||||
self.console.print(f"[bold cyan]>> {msg}[/bold cyan]")
|
||||
|
||||
def render_result(self, result: FetchResult, copied: bool = False, is_all_copy: bool = False) -> None:
|
||||
if result.is_cached:
|
||||
cached_notice = catalog.get("status.offline_cached")
|
||||
self.console.print(f"[yellow]{cached_notice}[/yellow]")
|
||||
|
||||
# Print content with native ANSI formatting
|
||||
parsed_text = Text.from_ansi(result.content)
|
||||
self.console.print(parsed_text)
|
||||
|
||||
if copied:
|
||||
self.console.print("")
|
||||
self.render_clipboard_notice(is_all_copy)
|
||||
@@ -0,0 +1,209 @@
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
PROGRAMMING_LANGS = {
|
||||
"python", "py", "go", "golang", "rust", "rs", "javascript", "js",
|
||||
"typescript", "ts", "c", "cpp", "c++", "csharp", "cs", "java", "kotlin",
|
||||
"kt", "swift", "php", "ruby", "rb", "perl", "lua", "r", "scala", "dart",
|
||||
"elixir", "clojure", "haskell", "hs", "erlang", "zig", "nim", "bash", "sh",
|
||||
"zsh", "fish", "powershell", "ps1", "sql", "mysql", "postgres", "sqlite",
|
||||
}
|
||||
|
||||
CLI_TOOLS = {
|
||||
"tar", "grep", "find", "sed", "awk", "ssh", "scp", "rsync", "curl", "wget",
|
||||
"chmod", "chown", "ps", "top", "htop", "kill", "lsof", "netstat", "ip",
|
||||
"tmux", "screen", "vim", "nvim", "nano", "ffmpeg", "jq", "openssl",
|
||||
"docker", "dockerfile", "compose", "docker-compose", "git", "kubectl", "k8s",
|
||||
"terraform", "ansible", "nginx", "apache", "systemd", "iptables", "ufw",
|
||||
"free", "df", "du", "vmstat", "iostat", "sar", "strace", "nc", "nmap",
|
||||
}
|
||||
|
||||
PLATFORM_STOPWORDS = {
|
||||
"linux", "ubuntu", "debian", "arch", "centos", "alpine", "unix",
|
||||
"windows", "macos", "shell", "command", "how", "to", "cli", "example",
|
||||
}
|
||||
|
||||
COMMON_SYNONYMS = {
|
||||
"serialize": ["dump", "dumps", "write", "stringify", "encode", "save"],
|
||||
"serialization": ["dump", "dumps", "write", "stringify", "encode", "save"],
|
||||
"deserialize": ["load", "loads", "read", "parse", "decode"],
|
||||
"deserialization": ["load", "loads", "read", "parse", "decode"],
|
||||
"parse": ["load", "loads", "read", "decode"],
|
||||
"read": ["load", "open", "parse", "get"],
|
||||
"write": ["dump", "save", "export", "create"],
|
||||
"save": ["write", "dump", "export"],
|
||||
"delete": ["remove", "del", "drop", "pop", "clear"],
|
||||
"remove": ["delete", "del", "drop", "pop", "clear"],
|
||||
"sort": ["sorted", "order", "reverse", "orderby"],
|
||||
"order": ["sort", "sorted", "reverse"],
|
||||
"find": ["search", "lookup", "match", "filter", "get"],
|
||||
"search": ["find", "lookup", "match", "grep", "filter"],
|
||||
"iterate": ["loop", "for", "traverse", "each"],
|
||||
"loop": ["iterate", "for", "traverse", "while"],
|
||||
"filter": ["find", "match", "where", "select"],
|
||||
"reverse": ["reversed", "invert"],
|
||||
"reversed": ["reverse", "invert"],
|
||||
"length": ["size", "count", "len"],
|
||||
"size": ["length", "count", "len"],
|
||||
"count": ["size", "length", "len"],
|
||||
"convert": ["cast", "parse", "to", "transform"],
|
||||
"extract": ["unpack", "unzip", "untar", "decompress"],
|
||||
"compress": ["archive", "pack", "zip", "tar"],
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class RoutedQuery:
|
||||
raw_query: str
|
||||
target: str
|
||||
subquery: str
|
||||
candidate_urls: List[str] = field(default_factory=list)
|
||||
is_targeted: bool = False
|
||||
|
||||
@property
|
||||
def primary_url(self) -> str:
|
||||
return self.candidate_urls[0] if self.candidate_urls else "https://cht.sh"
|
||||
|
||||
@property
|
||||
def fallback_url(self) -> str:
|
||||
return self.candidate_urls[1] if len(self.candidate_urls) > 1 else self.primary_url
|
||||
|
||||
|
||||
class QueryRouter:
|
||||
"""Parses arbitrary CLI tokens into prioritized cheat.sh candidate URLs."""
|
||||
|
||||
@staticmethod
|
||||
def _generate_query_variants(tokens: List[str]) -> List[str]:
|
||||
"""Generates orderings and synonym variants for query subterms."""
|
||||
variants: List[List[str]] = [list(tokens)]
|
||||
|
||||
# Permutation with reversed terms for two-token subqueries
|
||||
if len(tokens) == 2:
|
||||
variants.append([tokens[1], tokens[0]])
|
||||
|
||||
# Generate synonym replacements
|
||||
for i, token in enumerate(tokens):
|
||||
if token in COMMON_SYNONYMS:
|
||||
for syn in COMMON_SYNONYMS[token]:
|
||||
new_variant = list(tokens)
|
||||
new_variant[i] = syn
|
||||
variants.append(new_variant)
|
||||
if len(new_variant) == 2:
|
||||
variants.append([new_variant[1], new_variant[0]])
|
||||
|
||||
seen = set()
|
||||
unique_variants: List[str] = []
|
||||
for v in variants:
|
||||
joined = "+".join(quote_plus(t) for t in v)
|
||||
if joined not in seen:
|
||||
seen.add(joined)
|
||||
unique_variants.append(joined)
|
||||
|
||||
return unique_variants
|
||||
|
||||
@classmethod
|
||||
def route(cls, tokens: List[str]) -> RoutedQuery:
|
||||
cleaned_tokens = [t.strip().lower() for t in tokens if t.strip()]
|
||||
if not cleaned_tokens:
|
||||
return RoutedQuery(
|
||||
raw_query="",
|
||||
target="",
|
||||
subquery="",
|
||||
candidate_urls=["https://cht.sh"],
|
||||
is_targeted=False,
|
||||
)
|
||||
|
||||
raw_query = " ".join(cleaned_tokens)
|
||||
first_token = cleaned_tokens[0]
|
||||
remaining = cleaned_tokens[1:]
|
||||
|
||||
# 1. Programming Languages (cht.sh/python/json+dumps, cht.sh/python/write+json)
|
||||
if first_token in PROGRAMMING_LANGS:
|
||||
if remaining:
|
||||
candidates = []
|
||||
variants = cls._generate_query_variants(remaining)
|
||||
for var in variants:
|
||||
candidates.append(f"https://cht.sh/{first_token}/{var}")
|
||||
|
||||
# Individual keyword lookups in language scope
|
||||
for token in remaining:
|
||||
candidates.append(f"https://cht.sh/{first_token}/{quote_plus(token)}")
|
||||
|
||||
# Search within language
|
||||
tilde_sub = "~".join(quote_plus(t) for t in remaining)
|
||||
candidates.append(f"https://cht.sh/{first_token}/~{tilde_sub}")
|
||||
|
||||
# Global fallback with tilde
|
||||
candidates.append(f"https://cht.sh/~{first_token}~{tilde_sub}")
|
||||
else:
|
||||
candidates = [f"https://cht.sh/{first_token}"]
|
||||
|
||||
return RoutedQuery(
|
||||
raw_query=raw_query,
|
||||
target=first_token,
|
||||
subquery=" ".join(remaining),
|
||||
candidate_urls=candidates,
|
||||
is_targeted=True,
|
||||
)
|
||||
|
||||
# 2. Recognized CLI Tools (cht.sh/tar~extract or cht.sh/tar)
|
||||
if first_token in CLI_TOOLS:
|
||||
if remaining:
|
||||
candidates = []
|
||||
tilde_sub = "~".join(quote_plus(t) for t in remaining)
|
||||
candidates.append(f"https://cht.sh/{first_token}~{tilde_sub}")
|
||||
|
||||
# Synonym variants for CLI tool subqueries
|
||||
variants = cls._generate_query_variants(remaining)
|
||||
for var in variants:
|
||||
candidates.append(f"https://cht.sh/{first_token}/{var}")
|
||||
|
||||
candidates.append(f"https://cht.sh/~{first_token}~{tilde_sub}")
|
||||
else:
|
||||
candidates = [
|
||||
f"https://cht.sh/{first_token}",
|
||||
f"https://cht.sh/~{first_token}",
|
||||
]
|
||||
|
||||
return RoutedQuery(
|
||||
raw_query=raw_query,
|
||||
target=first_token,
|
||||
subquery=" ".join(remaining),
|
||||
candidate_urls=candidates,
|
||||
is_targeted=True,
|
||||
)
|
||||
|
||||
# 3. Single word query (cht.sh/command or cht.sh/~word)
|
||||
if len(cleaned_tokens) == 1:
|
||||
word = cleaned_tokens[0]
|
||||
candidates = [
|
||||
f"https://cht.sh/{word}",
|
||||
f"https://cht.sh/~{word}",
|
||||
]
|
||||
return RoutedQuery(
|
||||
raw_query=raw_query,
|
||||
target=word,
|
||||
subquery="",
|
||||
candidate_urls=candidates,
|
||||
is_targeted=True,
|
||||
)
|
||||
|
||||
# 4. Multi-token general search (e.g., 'linux memory usage' -> '~linux~memory~usage', '~memory~usage', '~memory')
|
||||
candidates = []
|
||||
candidates.append(f"https://cht.sh/~{'~'.join(quote_plus(t) for t in cleaned_tokens)}")
|
||||
|
||||
meaningful_tokens = [t for t in cleaned_tokens if t not in PLATFORM_STOPWORDS]
|
||||
if meaningful_tokens and meaningful_tokens != cleaned_tokens:
|
||||
candidates.append(f"https://cht.sh/~{'~'.join(quote_plus(t) for t in meaningful_tokens)}")
|
||||
if len(meaningful_tokens) > 1:
|
||||
for token in meaningful_tokens:
|
||||
candidates.append(f"https://cht.sh/~{quote_plus(token)}")
|
||||
|
||||
return RoutedQuery(
|
||||
raw_query=raw_query,
|
||||
target="",
|
||||
subquery=raw_query,
|
||||
candidate_urls=candidates,
|
||||
is_targeted=False,
|
||||
)
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"app": {
|
||||
"name": "Gravitiny",
|
||||
"tagline": "Micro-Productivity Applet Ecosystem & Runtime Orchestrator",
|
||||
"version_output": "{name} v{version} [{stage}] - {description}",
|
||||
"usage_header": "Usage: gravitiny <command> [arguments]",
|
||||
"available_commands_title": "Available Commands:"
|
||||
},
|
||||
"commands": {
|
||||
"list": {
|
||||
"description": "List all installed and discovered micro-applets",
|
||||
"no_applets_found": "No installed applets found in the applet directory.",
|
||||
"installed_header": "Installed Applets ({count}):",
|
||||
"table_col_id": "ID",
|
||||
"table_col_name": "Name",
|
||||
"table_col_version": "Version",
|
||||
"table_col_runtime": "Runtime",
|
||||
"table_col_shims": "Shims",
|
||||
"table_col_description": "Description"
|
||||
},
|
||||
"run": {
|
||||
"description": "Execute an installed applet with forwarded arguments",
|
||||
"usage": "Usage: gravitiny run <applet_id> [args...]",
|
||||
"missing_applet": "Error: Applet ID is required for 'run' command.",
|
||||
"applet_not_found": "Error: Applet '{applet_id}' is not installed or could not be found.",
|
||||
"exec_failed": "Error: Failed to execute applet '{applet_id}': {error}"
|
||||
},
|
||||
"info": {
|
||||
"description": "Display detailed metadata for an installed applet",
|
||||
"usage": "Usage: gravitiny info <applet_id>",
|
||||
"missing_applet": "Error: Applet ID is required for 'info' command.",
|
||||
"applet_not_found": "Error: Applet '{applet_id}' is not found.",
|
||||
"title": "Applet Metadata: {name}",
|
||||
"field_id": "ID",
|
||||
"field_version": "Version",
|
||||
"field_author": "Author",
|
||||
"field_license": "License",
|
||||
"field_runtime": "Runtime",
|
||||
"field_entrypoint": "Entrypoint",
|
||||
"field_shims": "Shims",
|
||||
"field_dependencies": "Dependencies",
|
||||
"field_description": "Description",
|
||||
"field_path": "Path"
|
||||
},
|
||||
"alias": {
|
||||
"description": "Configure or regenerate custom command shims for an applet",
|
||||
"usage": "Usage: gravitiny alias <applet_id> <new_alias>",
|
||||
"missing_args": "Error: Applet ID and new alias name are required.",
|
||||
"applet_not_found": "Error: Applet '{applet_id}' is not found.",
|
||||
"success": "Generated shim '{alias}' for applet '{applet_id}' in {bin_dir}."
|
||||
},
|
||||
"setup": {
|
||||
"description": "Initialize Gravitiny home directory, venv, and bin PATH configuration",
|
||||
"status_title": "Gravitiny Environment Status:",
|
||||
"home_path": "Home Directory: {path}",
|
||||
"bin_path": "Bin Directory: {path}",
|
||||
"applets_path": "Applets Directory: {path}",
|
||||
"path_configured": "Bin directory is in system PATH.",
|
||||
"path_missing": "Bin directory is NOT in system PATH.",
|
||||
"path_instruction_windows": "To add to PATH, run in PowerShell: [Environment]::SetEnvironmentVariable('Path', $env:Path + ';{path}', 'User')",
|
||||
"path_instruction_posix": "To add to PATH, add this line to your shell profile (~/.bashrc or ~/.zshrc):\nexport PATH=\"{path}:$PATH\"",
|
||||
"regenerated_shims": "Regenerated all command shims in {path}."
|
||||
},
|
||||
"search": {
|
||||
"description": "Search remote registry for available applets",
|
||||
"usage": "Usage: gravitiny search <query>",
|
||||
"missing_query": "Error: Search query is required.",
|
||||
"searching": "Searching registry for '{query}'...",
|
||||
"no_results": "No applets matching '{query}' found in remote registry."
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
"unknown_command": "Error: Unknown command '{command}'. Run 'gravitiny --help' for usage.",
|
||||
"general_error": "Error: {error}"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Ensure package root is in sys.path
|
||||
package_root = Path(__file__).resolve().parent.parent
|
||||
if str(package_root) not in sys.path:
|
||||
sys.path.insert(0, str(package_root))
|
||||
|
||||
from gravitiny.src.cli import run_cli
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(run_cli())
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "Gravitiny",
|
||||
"id": "gravitiny",
|
||||
"version": "0.1.0",
|
||||
"stage": "Alpha",
|
||||
"description": "Micro-Productivity Applet Ecosystem & Runtime Orchestrator",
|
||||
"author": "Gravitiny Team",
|
||||
"license": "MIT",
|
||||
"dependencies": [
|
||||
"rich"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
# Gravitiny Core Package
|
||||
@@ -0,0 +1,47 @@
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
class StringCatalog:
|
||||
"""Centralized catalog for Gravitiny manager strings and interaction messages."""
|
||||
|
||||
_instance = None
|
||||
_catalog: Dict[str, Any] = {}
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super(StringCatalog, cls).__new__(cls)
|
||||
cls._instance._load_catalog()
|
||||
return cls._instance
|
||||
|
||||
def _load_catalog(self) -> None:
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
catalog_path = os.path.join(base_dir, "catalog", "strings.json")
|
||||
if os.path.exists(catalog_path):
|
||||
with open(catalog_path, "r", encoding="utf-8") as f:
|
||||
self._catalog = json.load(f)
|
||||
else:
|
||||
self._catalog = {}
|
||||
|
||||
def get(self, key_path: str, default: str = "") -> str:
|
||||
"""Retrieve a string from the catalog using dot notation."""
|
||||
parts = key_path.split(".")
|
||||
current = self._catalog
|
||||
for part in parts:
|
||||
if isinstance(current, dict) and part in current:
|
||||
current = current[part]
|
||||
else:
|
||||
return default
|
||||
return str(current) if current is not None else default
|
||||
|
||||
def format(self, key_path: str, **kwargs: Any) -> str:
|
||||
"""Retrieve a template string and interpolate keyword arguments."""
|
||||
template = self.get(key_path, "")
|
||||
try:
|
||||
return template.format(**kwargs)
|
||||
except KeyError:
|
||||
return template
|
||||
|
||||
|
||||
catalog = StringCatalog()
|
||||
@@ -0,0 +1,261 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
try:
|
||||
from gravitiny.src.catalog import catalog
|
||||
from gravitiny.src.discovery import AppletDiscovery
|
||||
from gravitiny.src.launcher import AppletLauncher
|
||||
from gravitiny.src.manifest import load_manager_manifest
|
||||
from gravitiny.src.shims import ShimGenerator
|
||||
except ImportError:
|
||||
from src.catalog import catalog
|
||||
from src.discovery import AppletDiscovery
|
||||
from src.launcher import AppletLauncher
|
||||
from src.manifest import load_manager_manifest
|
||||
from src.shims import ShimGenerator
|
||||
|
||||
|
||||
def print_help() -> None:
|
||||
manifest = load_manager_manifest()
|
||||
print(f"{manifest.get('name', 'Gravitiny')} v{manifest.get('version', '0.1.0')} [{manifest.get('stage', 'Alpha')}] - {catalog.get('app.tagline')}")
|
||||
print()
|
||||
print(catalog.get("app.usage_header"))
|
||||
print(" gravitiny list " + catalog.get("commands.list.description"))
|
||||
print(" gravitiny run <applet_id> [args...] " + catalog.get("commands.run.description"))
|
||||
print(" gravitiny info <applet_id> " + catalog.get("commands.info.description"))
|
||||
print(" gravitiny alias <applet> <alias> " + catalog.get("commands.alias.description"))
|
||||
print(" gravitiny setup " + catalog.get("commands.setup.description"))
|
||||
print()
|
||||
print("Shorthand execution:")
|
||||
print(" gravitiny <applet_id> [args...]")
|
||||
print()
|
||||
print("Examples:")
|
||||
print(" gravitiny list")
|
||||
print(" gravitiny run lex algorithm")
|
||||
print(" gravitiny sec python json serialize -c")
|
||||
print(" gravitiny setup")
|
||||
|
||||
|
||||
def cmd_list() -> int:
|
||||
discovery = AppletDiscovery()
|
||||
applets = discovery.discover_all()
|
||||
|
||||
if not applets:
|
||||
print(catalog.get("commands.list.no_applets_found"))
|
||||
return 0
|
||||
|
||||
print(catalog.format("commands.list.installed_header", count=len(applets)))
|
||||
print()
|
||||
|
||||
# Calculate column widths
|
||||
id_w = max(len(catalog.get("commands.list.table_col_id")), max(len(a.id) for a in applets.values())) + 2
|
||||
name_w = max(len(catalog.get("commands.list.table_col_name")), max(len(a.name) for a in applets.values())) + 2
|
||||
ver_w = max(len(catalog.get("commands.list.table_col_version")), max(len(a.version) for a in applets.values())) + 2
|
||||
shims_w = max(len(catalog.get("commands.list.table_col_shims")), max(len(", ".join(a.shims)) for a in applets.values())) + 2
|
||||
|
||||
header = (
|
||||
f"{catalog.get('commands.list.table_col_id'):<{id_w}} "
|
||||
f"{catalog.get('commands.list.table_col_name'):<{name_w}} "
|
||||
f"{catalog.get('commands.list.table_col_version'):<{ver_w}} "
|
||||
f"{catalog.get('commands.list.table_col_shims'):<{shims_w}} "
|
||||
f"{catalog.get('commands.list.table_col_description')}"
|
||||
)
|
||||
separator = "-" * max(len(header), 70)
|
||||
|
||||
print(header)
|
||||
print(separator)
|
||||
|
||||
for applet in sorted(applets.values(), key=lambda x: x.id):
|
||||
shims_str = ", ".join(applet.shims) if applet.shims else applet.id
|
||||
print(
|
||||
f"{applet.id:<{id_w}} "
|
||||
f"{applet.name:<{name_w}} "
|
||||
f"{applet.version:<{ver_w}} "
|
||||
f"{shims_str:<{shims_w}} "
|
||||
f"{applet.description}"
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_run(args: List[str]) -> int:
|
||||
if not args:
|
||||
print(catalog.get("commands.run.missing_applet"))
|
||||
print(catalog.get("commands.run.usage"))
|
||||
return 1
|
||||
|
||||
applet_id = args[0]
|
||||
applet_args = args[1:]
|
||||
|
||||
discovery = AppletDiscovery()
|
||||
applet = discovery.get_applet(applet_id)
|
||||
|
||||
if not applet:
|
||||
print(catalog.format("commands.run.applet_not_found", applet_id=applet_id))
|
||||
return 1
|
||||
|
||||
return AppletLauncher.execute(applet, applet_args)
|
||||
|
||||
|
||||
def cmd_info(args: List[str]) -> int:
|
||||
if not args:
|
||||
print(catalog.get("commands.info.missing_applet"))
|
||||
print(catalog.get("commands.info.usage"))
|
||||
return 1
|
||||
|
||||
applet_id = args[0]
|
||||
discovery = AppletDiscovery()
|
||||
applet = discovery.get_applet(applet_id)
|
||||
|
||||
if not applet:
|
||||
print(catalog.format("commands.info.applet_not_found", applet_id=applet_id))
|
||||
return 1
|
||||
|
||||
print(catalog.format("commands.info.title", name=applet.name))
|
||||
print("-" * 50)
|
||||
print(f" {catalog.get('commands.info.field_id'):<15}: {applet.id}")
|
||||
print(f" {catalog.get('commands.info.field_version'):<15}: {applet.version}")
|
||||
print(f" {catalog.get('commands.info.field_author'):<15}: {applet.author}")
|
||||
print(f" {catalog.get('commands.info.field_license'):<15}: {applet.license}")
|
||||
print(f" {catalog.get('commands.info.field_runtime'):<15}: {applet.runtime}")
|
||||
print(f" {catalog.get('commands.info.field_entrypoint'):<15}: {applet.entrypoint}")
|
||||
print(f" {catalog.get('commands.info.field_shims'):<15}: {', '.join(applet.shims)}")
|
||||
print(f" {catalog.get('commands.info.field_dependencies'):<15}: {', '.join(applet.dependencies) if applet.dependencies else 'None'}")
|
||||
print(f" {catalog.get('commands.info.field_description'):<15}: {applet.description}")
|
||||
if applet.path:
|
||||
print(f" {catalog.get('commands.info.field_path'):<15}: {applet.path}")
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_alias(args: List[str]) -> int:
|
||||
if len(args) < 2:
|
||||
print(catalog.get("commands.alias.missing_args"))
|
||||
print(catalog.get("commands.alias.usage"))
|
||||
return 1
|
||||
|
||||
applet_id, alias_name = args[0], args[1]
|
||||
discovery = AppletDiscovery()
|
||||
applet = discovery.get_applet(applet_id)
|
||||
|
||||
if not applet:
|
||||
print(catalog.format("commands.alias.applet_not_found", applet_id=applet_id))
|
||||
return 1
|
||||
|
||||
shim_gen = ShimGenerator()
|
||||
created = shim_gen.generate_shim(applet, alias=alias_name)
|
||||
|
||||
if created:
|
||||
print(catalog.format("commands.alias.success", alias=alias_name, applet_id=applet.id, bin_dir=shim_gen.bin_dir))
|
||||
return 0
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_setup() -> int:
|
||||
user_home = Path.home()
|
||||
gravitiny_home = user_home / ".gravitiny"
|
||||
bin_dir = gravitiny_home / "bin"
|
||||
applets_dir = gravitiny_home / "applets"
|
||||
|
||||
bin_dir.mkdir(parents=True, exist_ok=True)
|
||||
applets_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
print(catalog.get("commands.setup.status_title"))
|
||||
print(catalog.format("commands.setup.home_path", path=gravitiny_home))
|
||||
print(catalog.format("commands.setup.bin_path", path=bin_dir))
|
||||
print(catalog.format("commands.setup.applets_path", path=applets_dir))
|
||||
print()
|
||||
|
||||
# Regenerate shims for all discovered applets
|
||||
discovery = AppletDiscovery()
|
||||
applets = discovery.discover_all()
|
||||
shim_gen = ShimGenerator(bin_dir=bin_dir)
|
||||
|
||||
for applet in applets.values():
|
||||
shim_gen.generate_shim(applet)
|
||||
|
||||
# Also generate gravitiny master CLI shim
|
||||
is_windows = os.name == "nt"
|
||||
python_exe = sys.executable
|
||||
gravitiny_main = Path(__file__).resolve().parent.parent / "main.py"
|
||||
if is_windows:
|
||||
master_shim = bin_dir / "gravitiny.cmd"
|
||||
with open(master_shim, "w", encoding="utf-8") as f:
|
||||
f.write(f"@echo off\nsetlocal\n\"{python_exe}\" \"{gravitiny_main}\" %*\n")
|
||||
else:
|
||||
master_shim = bin_dir / "gravitiny"
|
||||
with open(master_shim, "w", encoding="utf-8") as f:
|
||||
f.write(f"#!/usr/bin/env sh\nexec \"{python_exe}\" \"{gravitiny_main}\" \"$@\"\n")
|
||||
try:
|
||||
os.chmod(master_shim, 0o755)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print(catalog.format("commands.setup.regenerated_shims", path=bin_dir))
|
||||
print()
|
||||
|
||||
# Check PATH status
|
||||
current_path = os.environ.get("PATH", "")
|
||||
is_in_path = str(bin_dir).lower() in current_path.lower()
|
||||
|
||||
if is_in_path:
|
||||
print(catalog.get("commands.setup.path_configured"))
|
||||
else:
|
||||
print(catalog.get("commands.setup.path_missing"))
|
||||
if os.name == "nt":
|
||||
print(catalog.format("commands.setup.path_instruction_windows", path=bin_dir))
|
||||
else:
|
||||
print(catalog.format("commands.setup.path_instruction_posix", path=bin_dir))
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
def run_cli(args: Optional[List[str]] = None) -> int:
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
raw_args = args if args is not None else sys.argv[1:]
|
||||
|
||||
if not raw_args or raw_args[0] in ["-h", "--help", "help"]:
|
||||
print_help()
|
||||
return 0
|
||||
|
||||
if raw_args[0] in ["-V", "-v", "--version"]:
|
||||
manifest = load_manager_manifest()
|
||||
print(catalog.format(
|
||||
"app.version_output",
|
||||
name=manifest.get("name", "Gravitiny"),
|
||||
version=manifest.get("version", "0.1.0"),
|
||||
stage=manifest.get("stage", "Alpha"),
|
||||
description=catalog.get("app.tagline"),
|
||||
))
|
||||
return 0
|
||||
|
||||
command = raw_args[0].lower()
|
||||
sub_args = raw_args[1:]
|
||||
|
||||
if command == "list":
|
||||
return cmd_list()
|
||||
elif command == "run":
|
||||
return cmd_run(sub_args)
|
||||
elif command == "info":
|
||||
return cmd_info(sub_args)
|
||||
elif command == "alias":
|
||||
return cmd_alias(sub_args)
|
||||
elif command == "setup":
|
||||
return cmd_setup()
|
||||
|
||||
# Shorthand: check if command matches an installed applet directly
|
||||
discovery = AppletDiscovery()
|
||||
matched_applet = discovery.get_applet(command)
|
||||
if matched_applet:
|
||||
return AppletLauncher.execute(matched_applet, sub_args)
|
||||
|
||||
print(catalog.format("errors.unknown_command", command=command))
|
||||
return 1
|
||||
@@ -0,0 +1,58 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from gravitiny.src.manifest import AppletManifest, parse_applet_manifest
|
||||
|
||||
|
||||
class AppletDiscovery:
|
||||
"""Discovers installed micro-applets across local workspace and user profile directories."""
|
||||
|
||||
def __init__(self, custom_applets_dir: Optional[Path] = None):
|
||||
self.search_dirs: List[Path] = []
|
||||
|
||||
if custom_applets_dir:
|
||||
self.search_dirs.append(Path(custom_applets_dir))
|
||||
|
||||
# 1. Local workspace applets directory
|
||||
base_dir = Path(__file__).resolve().parent.parent
|
||||
workspace_applets = base_dir / "applets"
|
||||
if workspace_applets.exists():
|
||||
self.search_dirs.append(workspace_applets)
|
||||
|
||||
# 2. User home applets directory (~/.gravitiny/applets)
|
||||
user_applets = Path.home() / ".gravitiny" / "applets"
|
||||
if user_applets.exists() and user_applets not in self.search_dirs:
|
||||
self.search_dirs.append(user_applets)
|
||||
|
||||
def discover_all(self) -> Dict[str, AppletManifest]:
|
||||
"""Scans all search directories and returns a dictionary of applet_id -> AppletManifest."""
|
||||
applets: Dict[str, AppletManifest] = {}
|
||||
|
||||
for search_dir in self.search_dirs:
|
||||
if not search_dir.exists() or not search_dir.is_dir():
|
||||
continue
|
||||
|
||||
for child in search_dir.iterdir():
|
||||
if child.is_dir() and not child.name.startswith((".", "_")):
|
||||
manifest = parse_applet_manifest(child)
|
||||
if manifest and manifest.id not in applets:
|
||||
applets[manifest.id] = manifest
|
||||
|
||||
return applets
|
||||
|
||||
def get_applet(self, applet_id: str) -> Optional[AppletManifest]:
|
||||
"""Looks up a specific applet by its ID or shim alias."""
|
||||
clean_id = applet_id.strip().lower()
|
||||
all_applets = self.discover_all()
|
||||
|
||||
# Exact ID match
|
||||
if clean_id in all_applets:
|
||||
return all_applets[clean_id]
|
||||
|
||||
# Alias / Shim match
|
||||
for applet in all_applets.values():
|
||||
if clean_id in [s.lower() for s in applet.shims]:
|
||||
return applet
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,51 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import List
|
||||
|
||||
from gravitiny.src.manifest import AppletManifest
|
||||
|
||||
|
||||
class AppletLauncher:
|
||||
"""Executes applets with full stream forwarding, correct working directories, and exit codes."""
|
||||
|
||||
@staticmethod
|
||||
def _get_python_interpreter() -> str:
|
||||
venv_python_win = Path_home = sys.executable
|
||||
user_home = sys.path[0]
|
||||
# Check standard sys.executable
|
||||
return sys.executable
|
||||
|
||||
@classmethod
|
||||
def execute(cls, manifest: AppletManifest, args: List[str]) -> int:
|
||||
if not manifest.path:
|
||||
return 1
|
||||
|
||||
entrypoint = manifest.path / manifest.entrypoint
|
||||
if not entrypoint.exists():
|
||||
return 1
|
||||
|
||||
cwd = str(manifest.path)
|
||||
cmd: List[str] = []
|
||||
|
||||
if manifest.runtime == "python":
|
||||
cmd = [sys.executable, str(entrypoint)] + args
|
||||
elif manifest.runtime == "binary":
|
||||
cmd = [str(entrypoint)] + args
|
||||
elif manifest.runtime == "node":
|
||||
cmd = ["node", str(entrypoint)] + args
|
||||
elif manifest.runtime == "shell":
|
||||
if os.name == "nt":
|
||||
cmd = ["powershell", "-ExecutionPolicy", "Bypass", "-File", str(entrypoint)] + args
|
||||
else:
|
||||
cmd = ["sh", str(entrypoint)] + args
|
||||
else:
|
||||
cmd = [str(entrypoint)] + args
|
||||
|
||||
try:
|
||||
res = subprocess.run(cmd, cwd=cwd)
|
||||
return res.returncode
|
||||
except KeyboardInterrupt:
|
||||
return 130
|
||||
except Exception:
|
||||
return 1
|
||||
@@ -0,0 +1,83 @@
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppletManifest:
|
||||
id: str
|
||||
name: str
|
||||
version: str
|
||||
description: str = ""
|
||||
author: str = "Unknown"
|
||||
license: str = "MIT"
|
||||
runtime: str = "python"
|
||||
entrypoint: str = "main.py"
|
||||
shims: List[str] = field(default_factory=list)
|
||||
dependencies: List[str] = field(default_factory=list)
|
||||
tags: List[str] = field(default_factory=list)
|
||||
network: str = "offline"
|
||||
path: Optional[Path] = None
|
||||
raw: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
def load_manager_manifest() -> Dict[str, Any]:
|
||||
"""Loads Gravitiny Manager system manifest."""
|
||||
base_dir = Path(__file__).resolve().parent.parent
|
||||
manifest_path = base_dir / "manifest.json"
|
||||
if manifest_path.exists():
|
||||
try:
|
||||
with open(manifest_path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
pass
|
||||
return {"name": "Gravitiny", "version": "0.1.0", "stage": "Alpha", "description": ""}
|
||||
|
||||
|
||||
def parse_applet_manifest(applet_dir: Path) -> Optional[AppletManifest]:
|
||||
"""Parses an applet's manifest.json or constructs defaults from folder info."""
|
||||
manifest_path = applet_dir / "manifest.json"
|
||||
data: Dict[str, Any] = {}
|
||||
if manifest_path.exists():
|
||||
try:
|
||||
with open(manifest_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
applet_id = data.get("id") or applet_dir.name.lower()
|
||||
name = data.get("name") or applet_dir.name.capitalize()
|
||||
version = data.get("version") or "1.0.0"
|
||||
description = data.get("description") or ""
|
||||
author = data.get("author") or "Unknown"
|
||||
license_name = data.get("license") or "MIT"
|
||||
runtime = data.get("runtime") or "python"
|
||||
entrypoint = data.get("entrypoint") or "main.py"
|
||||
|
||||
shims = data.get("shims")
|
||||
if not shims:
|
||||
# Default shim is the applet id
|
||||
shims = [applet_id]
|
||||
|
||||
dependencies = data.get("dependencies") or []
|
||||
tags = data.get("tags") or []
|
||||
network = data.get("network") or "offline"
|
||||
|
||||
return AppletManifest(
|
||||
id=applet_id,
|
||||
name=name,
|
||||
version=version,
|
||||
description=description,
|
||||
author=author,
|
||||
license=license_name,
|
||||
runtime=runtime,
|
||||
entrypoint=entrypoint,
|
||||
shims=shims,
|
||||
dependencies=dependencies,
|
||||
tags=tags,
|
||||
network=network,
|
||||
path=applet_dir,
|
||||
raw=data,
|
||||
)
|
||||
@@ -0,0 +1,85 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
from gravitiny.src.manifest import AppletManifest
|
||||
|
||||
|
||||
class ShimGenerator:
|
||||
"""Generates and manages cross-platform command shims in the Gravitiny bin directory."""
|
||||
|
||||
def __init__(self, bin_dir: Optional[Path] = None):
|
||||
if bin_dir is None:
|
||||
# Default to ~/.gravitiny/bin or local gravitiny/bin
|
||||
user_home = Path.home()
|
||||
bin_dir = user_home / ".gravitiny" / "bin"
|
||||
self.bin_dir = Path(bin_dir)
|
||||
self.bin_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def _get_python_interpreter(self) -> str:
|
||||
"""Returns the Python interpreter path (virtualenv or current)."""
|
||||
user_home = Path.home()
|
||||
venv_python_win = user_home / ".gravitiny" / "venv" / "Scripts" / "python.exe"
|
||||
venv_python_posix = user_home / ".gravitiny" / "venv" / "bin" / "python"
|
||||
|
||||
if os.name == "nt" and venv_python_win.exists():
|
||||
return str(venv_python_win)
|
||||
elif os.name != "nt" and venv_python_posix.exists():
|
||||
return str(venv_python_posix)
|
||||
return sys.executable
|
||||
|
||||
def generate_shim(self, manifest: AppletManifest, alias: Optional[str] = None) -> List[Path]:
|
||||
"""Generates shims for an applet based on its manifest and optional custom alias."""
|
||||
if not manifest.path:
|
||||
return []
|
||||
|
||||
entrypoint_path = manifest.path / manifest.entrypoint
|
||||
shim_names = [alias] if alias else manifest.shims
|
||||
created_paths: List[Path] = []
|
||||
is_windows = os.name == "nt"
|
||||
python_exe = self._get_python_interpreter()
|
||||
|
||||
for name in shim_names:
|
||||
clean_name = name.strip().lower()
|
||||
if not clean_name:
|
||||
continue
|
||||
|
||||
if is_windows:
|
||||
shim_file = self.bin_dir / f"{clean_name}.cmd"
|
||||
content = (
|
||||
"@echo off\n"
|
||||
"setlocal\n"
|
||||
f'"{python_exe}" "{entrypoint_path}" %*\n'
|
||||
)
|
||||
with open(shim_file, "w", encoding="utf-8") as f:
|
||||
f.write(content)
|
||||
created_paths.append(shim_file)
|
||||
else:
|
||||
shim_file = self.bin_dir / clean_name
|
||||
content = (
|
||||
"#!/usr/bin/env sh\n"
|
||||
f'exec "{python_exe}" "{entrypoint_path}" "$@"\n'
|
||||
)
|
||||
with open(shim_file, "w", encoding="utf-8") as f:
|
||||
f.write(content)
|
||||
try:
|
||||
os.chmod(shim_file, 0o755)
|
||||
except Exception:
|
||||
pass
|
||||
created_paths.append(shim_file)
|
||||
|
||||
return created_paths
|
||||
|
||||
def remove_shim(self, shim_name: str) -> bool:
|
||||
"""Removes a shim by name."""
|
||||
is_windows = os.name == "nt"
|
||||
target_name = f"{shim_name.strip().lower()}.cmd" if is_windows else shim_name.strip().lower()
|
||||
shim_file = self.bin_dir / target_name
|
||||
if shim_file.exists():
|
||||
try:
|
||||
shim_file.unlink()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
return False
|
||||
Reference in New Issue
Block a user