cxc 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
chat.py ADDED
@@ -0,0 +1,204 @@
1
+ import os, requests, shlex
2
+ from textual.app import App, ComposeResult
3
+ from textual.containers import Horizontal, Vertical, ScrollableContainer, Center
4
+ from textual.widgets import Header, Footer, Input, Static, Markdown
5
+ from textual.binding import Binding
6
+ from textual.screen import ModalScreen
7
+
8
+ from config_loader import load_config
9
+
10
+ CVT = load_config()
11
+
12
+
13
+ API_KEY = f"{CVT.API}"
14
+ MODEL_AI = f"{CVT.MODEL}"
15
+ URL = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL_AI}:generateContent?key={API_KEY}"
16
+
17
+ history = []
18
+
19
+ class HelpScreen(ModalScreen):
20
+ BINDINGS = [
21
+ ("escape", "dismiss", "Close"),
22
+ ]
23
+
24
+ def compose(self):
25
+ yield Static(
26
+ """[ HELP ]
27
+
28
+ quit : Go out
29
+
30
+ Press ESC to close
31
+ """,
32
+ id="help",
33
+ )
34
+
35
+ def action_dismiss(self):
36
+ self.dismiss()
37
+
38
+
39
+ class ChatBubble(Markdown):
40
+ pass
41
+
42
+ class CodeX(App):
43
+ CSS = """
44
+ Screen {
45
+ background: #1a1a1a;
46
+ }
47
+ Header {
48
+ background: #333333;
49
+ color: #cccccc;
50
+ }
51
+ Footer {
52
+ background: #333333;
53
+ color: #999999;
54
+ }
55
+ #chat-area {
56
+ background: #1a1a1a;
57
+ padding: 1;
58
+ }
59
+ Input {
60
+ background: #2a2a2a;
61
+ color: #cccccc;
62
+ border: none;
63
+ dock: bottom;
64
+ margin: 0 1 1 1;
65
+ }
66
+ Input:focus {
67
+ border: none;
68
+ }
69
+ .user-row {
70
+ width: 100%;
71
+ height: auto;
72
+ margin-bottom: 1;
73
+ }
74
+ .ai-row {
75
+ width: 100%;
76
+ height: auto;
77
+ margin-bottom: 1;
78
+ }
79
+ .user-bubble {
80
+ background: #3a3a3a;
81
+ color: #cccccc;
82
+ padding: 1 2;
83
+ max-width: 70%;
84
+ width: auto;
85
+ }
86
+ .ai-bubble {
87
+ background: #2e2e2e;
88
+ color: #dddddd;
89
+ padding: 1 2;
90
+ max-width: 70%;
91
+ width: auto;
92
+ }
93
+
94
+ HelpScreen {
95
+ align: center middle;
96
+ }
97
+
98
+ #help {
99
+ width: 60;
100
+ border: round green;
101
+ padding: 1 2;
102
+ background: $surface;
103
+ }
104
+
105
+
106
+ #esc {
107
+ width: 100%;
108
+ text-align: center;
109
+ }
110
+
111
+ """
112
+
113
+ BINDINGS = [
114
+ Binding("ctrl+q", "quit", "Quit", priority=True),
115
+ Binding("ctrl+H", "help", "Help", priority=True),
116
+ ]
117
+
118
+
119
+ def compose(self):
120
+ yield Header(name="CodeX Core", classes="header")
121
+ with ScrollableContainer(id="chat-area"):
122
+ pass
123
+ yield Input(placeholder="Type a message ...", id="input-box")
124
+ yield Footer()
125
+
126
+ def on_mount(self):
127
+ self.query_one("#input-box", Input).focus()
128
+
129
+ def on_input_submitted(self, event: Input.Submitted):
130
+ msg = event.value.strip()
131
+ if not msg:
132
+ return
133
+ if msg.lower() == "quit":
134
+ self.exit()
135
+ return
136
+
137
+
138
+ elif msg.lower() == "help":
139
+ self.push_screen(HelpScreen())
140
+ event.input.value = ""
141
+ event.input.focus()
142
+ return
143
+
144
+
145
+ self.add_user_msg(msg)
146
+ self.query_one("#input-box", Input).value = ""
147
+ self.run_worker(lambda: self.get_ai_response(msg), name="ai_request", thread=True)
148
+
149
+ def add_user_msg(self, text):
150
+ chat = self.query_one("#chat-area", ScrollableContainer)
151
+ row = Horizontal(classes="user-row")
152
+ row.styles.width = "100%"
153
+ row.styles.height = "auto"
154
+ row.styles.align_horizontal = "right"
155
+ chat.mount(row)
156
+ bubble = ChatBubble(text, classes="user-bubble")
157
+ bubble.styles.margin = (0, 0, 0, 1)
158
+ row.mount(bubble)
159
+ chat.scroll_end()
160
+
161
+ def add_ai_msg(self, text):
162
+ chat = self.query_one("#chat-area", ScrollableContainer)
163
+ col = Vertical(classes="ai-row")
164
+ col.styles.width = "100%"
165
+ col.styles.height = "auto"
166
+ chat.mount(col)
167
+ name_label = Static(CVT.AI_NAME)
168
+ name_label.styles.margin = (0, 0, 0, 0)
169
+ name_label.styles.color = "#777777"
170
+ col.mount(name_label)
171
+ bubble = ChatBubble(text, classes="ai-bubble")
172
+ bubble.styles.margin = (0, 1, 0, 0)
173
+ col.mount(bubble)
174
+ chat.scroll_end()
175
+
176
+ def get_ai_response(self, msg):
177
+ history.append({
178
+ "role": "user",
179
+ "parts": [{"text": msg}]
180
+ })
181
+ SYS_PROMPT = f"{CVT.AI_PROMPT}"
182
+ payload = {
183
+ "system_instruction": {
184
+ "parts": [{"text": SYS_PROMPT}]
185
+ },
186
+ "contents": history
187
+ }
188
+ headers = {"Content-Type": "application/json"}
189
+ try:
190
+ response = requests.post(URL, json=payload, headers=headers)
191
+ response.raise_for_status()
192
+ data = response.json()
193
+ ai_response = data['candidates'][0]['content']['parts'][0]['text']
194
+ self.call_from_thread(self.add_ai_msg, ai_response)
195
+ history.append({
196
+ "role": "model",
197
+ "parts": [{"text": ai_response}]
198
+ })
199
+ except requests.exceptions.RequestException as e:
200
+ self.call_from_thread(self.add_ai_msg, f"Connection Error: {e}")
201
+
202
+ def askAI():
203
+ app = CodeX()
204
+ app.run()
colors.py ADDED
@@ -0,0 +1,10 @@
1
+ class C:
2
+ RESET = "\033[0m"
3
+ BLACK = "\033[30m"
4
+ RED = "\033[31m"
5
+ GREEN = "\033[32m"
6
+ YELLOW = "\033[33m"
7
+ BLUE = "\033[34m"
8
+ MAGENTA= "\033[35m"
9
+ CYAN = "\033[36m"
10
+ WHITE = "\033[37m"
config_loader.py ADDED
@@ -0,0 +1,125 @@
1
+ """Shared configuration loader for CodeX Core (cxc).
2
+
3
+ Configuration lives in ``~/.config/cxc/config.toml``. When upgrading from an
4
+ older release that used ``~/.config/cxc/config.py``, the old file is read once
5
+ and automatically migrated to TOML (a ``config.py.bak`` backup is kept).
6
+ """
7
+
8
+ try:
9
+ import tomllib
10
+ except ModuleNotFoundError: # Python < 3.11
11
+ raise SystemExit(
12
+ "[!] CodeX Core needs Python 3.11+ (tomllib). Please upgrade Python."
13
+ )
14
+
15
+ from pathlib import Path
16
+ from types import SimpleNamespace
17
+
18
+ CONFIG_DIR = Path.home() / ".config" / "cxc"
19
+ CONFIG_FILE = CONFIG_DIR / "config.toml"
20
+ LEGACY_FILE = CONFIG_DIR / "config.py"
21
+ LEGACY_LOCK = CONFIG_DIR / ".lock"
22
+
23
+ REQUIRED_KEYS = {
24
+ "API": "PASTE_YOUR_API_KEY",
25
+ "MODEL": "gemini-2.5-flash",
26
+ "AI_NAME": "Your_Ai_Name",
27
+ "AI_PROMPT": "You Are {AI_NAME}",
28
+ "MUSIC_DIR": "Music",
29
+ "VIDEO_DIR": "Videos",
30
+ }
31
+
32
+
33
+ def _escape(value):
34
+ return str(value).replace("\\", "\\\\").replace('"', '\\"')
35
+
36
+
37
+ def _render_toml(data):
38
+ def line(key):
39
+ return f'{key} = "{_escape(data.get(key, REQUIRED_KEYS[key]))}"'
40
+
41
+ return "\n".join([
42
+ "# CodeX Core (cxc) configuration",
43
+ "# Edit this file then restart cxc.",
44
+ "",
45
+ "# --- AI credentials ---",
46
+ line("API"),
47
+ line("MODEL"),
48
+ line("AI_NAME"),
49
+ "# AI_PROMPT may reference other keys, e.g. {AI_NAME}",
50
+ line("AI_PROMPT"),
51
+ "",
52
+ "# --- Folders (relative to your home directory) ---",
53
+ line("MUSIC_DIR"),
54
+ line("VIDEO_DIR"),
55
+ "",
56
+ ])
57
+
58
+
59
+ def _write_config(data):
60
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
61
+ CONFIG_FILE.write_text(_render_toml(data), encoding="utf-8")
62
+ try:
63
+ CONFIG_FILE.chmod(0o600)
64
+ except OSError:
65
+ pass
66
+
67
+
68
+ def _migrate_legacy():
69
+ import importlib.util
70
+
71
+ spec = importlib.util.spec_from_file_location("cxc_legacy_config", LEGACY_FILE)
72
+ module = importlib.util.module_from_spec(spec)
73
+ spec.loader.exec_module(module)
74
+ legacy = module.Config
75
+
76
+ data = {key: str(getattr(legacy, key, default))
77
+ for key, default in REQUIRED_KEYS.items()}
78
+
79
+ # Turn the resolved prompt back into a template so it keeps following AI_NAME.
80
+ ai_name = data["AI_NAME"]
81
+ if ai_name and ai_name in data["AI_PROMPT"]:
82
+ data["AI_PROMPT"] = data["AI_PROMPT"].replace(ai_name, "{AI_NAME}")
83
+
84
+ _write_config(data)
85
+
86
+ try:
87
+ LEGACY_FILE.rename(LEGACY_FILE.with_name("config.py.bak"))
88
+ except OSError:
89
+ pass
90
+ try:
91
+ LEGACY_LOCK.unlink()
92
+ except OSError:
93
+ pass
94
+
95
+ print(f"[+] Migrated legacy config -> {CONFIG_FILE}")
96
+
97
+
98
+ def load_config():
99
+ """Return the config as a simple object with attribute access."""
100
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
101
+
102
+ if not CONFIG_FILE.exists():
103
+ if LEGACY_FILE.exists():
104
+ _migrate_legacy()
105
+ else:
106
+ _write_config(dict(REQUIRED_KEYS))
107
+ print(f"[+] Created config at {CONFIG_FILE}")
108
+
109
+ try:
110
+ with CONFIG_FILE.open("rb") as handle:
111
+ data = tomllib.load(handle)
112
+ except tomllib.TOMLDecodeError as exc:
113
+ raise SystemExit(f"[!] Invalid config: {CONFIG_FILE}\n {exc}")
114
+
115
+ for key, default in REQUIRED_KEYS.items():
116
+ data.setdefault(key, default)
117
+
118
+ # Resolve simple placeholders (e.g. "{AI_NAME}") inside AI_PROMPT.
119
+ if isinstance(data.get("AI_PROMPT"), str):
120
+ try:
121
+ data["AI_PROMPT"] = data["AI_PROMPT"].format(**data)
122
+ except (KeyError, IndexError, ValueError):
123
+ pass
124
+
125
+ return SimpleNamespace(**data)
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: cxc
3
+ Version: 1.0.0
4
+ Summary: CodeX Core, Ai Tools For Terminal.
5
+ Home-page: https://github.com/XyrionMD/Cxc
6
+ Author: Xyrion
7
+ License: MIT
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Operating System :: OS Independent
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: requests
13
+ Requires-Dist: textual
14
+ Requires-Dist: yt-dlp
15
+ Requires-Dist: rapidfuzz
16
+ Dynamic: author
17
+ Dynamic: classifier
18
+ Dynamic: description
19
+ Dynamic: description-content-type
20
+ Dynamic: home-page
21
+ Dynamic: license
22
+ Dynamic: license-file
23
+ Dynamic: requires-dist
24
+ Dynamic: summary
25
+
26
+ **CodeX Core CXC**
27
+
28
+ Hello everyone, my name is Rion. This is my boredom project, which might be useful for you. This tool has several features such as:
29
+
30
+ **Features**
31
+
32
+ - Download Music with yt-dlp
33
+ - Search Music with yt-dlp
34
+ - Video Downloader (DV)
35
+ - Local Search
36
+ - mpx Music Player X
37
+ - AI Chat
38
+ - Self Update via pipx
39
+
40
+ **How to use**
41
+
42
+ ```
43
+ cxc help
44
+ ```
45
+
46
+ **Commands**
47
+
48
+ | Command | Alias | Description |
49
+ | ------------------------------ | ----- | ------------------------------------ |
50
+ | `cxc search "<title>"` | `-S` | Search music information |
51
+ | `cxc search --local "<title>"` | | Search your downloaded files locally |
52
+ | `cxc download "<title>"` | `-D` | Search and download music to MP3 |
53
+ | `cxc DV -r "<res>" "<URL>"` | | Download a video at a chosen quality |
54
+ | `cxc mpx` | | Open Music Player X |
55
+ | `cxc chat` | | Open the AI chat menu |
56
+ | `cxc time` | `-t` | Show time, day, month, and year |
57
+ | `cxc update` | `-U` | Self update via `pipx upgrade cxc` |
58
+ | `cxc version` | `-v` | Show the current version |
59
+ | `cxc help` | `h` | Display the help menu |
60
+
61
+ **Configuration**
62
+
63
+ cxc stores its settings in `~/.config/cxc/config.toml` (TOML format). The file is created automatically on first run — just edit it and restart cxc.
64
+
65
+ ```toml
66
+ # CodeX Core (cxc) configuration
67
+
68
+ # --- AI credentials ---
69
+ API = "PASTE_YOUR_API_KEY"
70
+ MODEL = "gemini-2.5-flash"
71
+ AI_NAME = "Your_Ai_Name"
72
+ # AI_PROMPT may reference other keys, e.g. {AI_NAME}
73
+ AI_PROMPT = "You Are {AI_NAME}"
74
+
75
+ # --- Folders (relative to your home directory) ---
76
+ MUSIC_DIR = "Music"
77
+ VIDEO_DIR = "Videos"
78
+ ```
79
+
80
+ | Key | Description |
81
+ | ----------- | ----------------------------------------------------------------- |
82
+ | `API` | Your Gemini API key (required for `cxc chat`). |
83
+ | `MODEL` | The AI model to use, e.g. `gemini-2.5-flash`. |
84
+ | `AI_NAME` | The name shown for the AI in chat. |
85
+ | `AI_PROMPT` | The system prompt. May reference other keys, e.g. `{AI_NAME}`. |
86
+ | `MUSIC_DIR` | Folder for downloaded music, relative to your home directory. |
87
+ | `VIDEO_DIR` | Folder for downloaded videos, relative to your home directory. |
88
+
89
+ **Config format & migration**
90
+
91
+ The configuration format changed from a Python file (`config.py`) to **TOML** (`config.toml`). You don't need to do anything manually:
92
+
93
+ - If you upgrade from an old version, cxc migrates automatically the first time you run it:
94
+ 1. reads your old `config.py`,
95
+ 2. writes the new `config.toml`,
96
+ 3. keeps a backup of the old file as `config.py.bak`,
97
+ 4. removes the old `.lock` file.
98
+ - Your API key and all other settings are preserved.
99
+ - If you have no old config, a fresh `config.toml` is created for you.
100
+ - The file is stored with owner-only permissions (`600`) because it holds your API key.
101
+ - cxc now requires **Python 3.11+** (for the built-in `tomllib`).
102
+
103
+ **Update**
104
+
105
+ ## What's New in v1.0.0 (First Stable Release)
106
+
107
+ - **Video Downloader (DV)** — download videos with yt-dlp and pick the resolution, e.g. `cxc DV -r "360" "<URL>"`.
108
+ - **Self Update** — update cxc straight from the terminal using `pipx upgrade`, e.g. `cxc update`.
109
+ - **Local Search** — find your downloaded music/videos on your device with partial-title and typo-tolerant matching, e.g. `cxc search --local "<music title>"`.
110
+ - **New config format** — configuration moved from `config.py` to `config.toml`, with automatic migration from the old file. See the [Configuration](#configuration) section.
111
+
112
+ **Notes**
113
+
114
+ - Before using the chat feature, please set your configuration first in `~/.config/cxc/config.toml` (see [Configuration](#configuration)).
115
+ - The `1.26.x` versions were the **nightly** channel. **v1.0.0 is the first stable release** of CXC, so the versioning restarts from here.
116
+
117
+ I will update regularly but I can't guarantee it, so see you in the next update.
@@ -0,0 +1,12 @@
1
+ chat.py,sha256=Z0w03cJaGUSdtb2fb3tuSDtl64Rvt0Bhb_pJtBaFWv0,5105
2
+ colors.py,sha256=2mzqnOURqcTJiEg3lqxPHJ4rPtNjd0zTYuYOm_cW9BA,224
3
+ config_loader.py,sha256=nUrlpU-1TL8pq6IznRHw_glRsN4Q7VyFXnp1Zr539RY,3604
4
+ cxc.py,sha256=6aaIINfYV-HON3jra-U7VUTSpLhznZ0Iq6J-ga7jd7E,3898
5
+ downloader.py,sha256=EQmOIQcMoYEF25c61HtdgIP93qkpfu00h6Vnwh4moDE,5423
6
+ mpx.py,sha256=Rb0b2S5wkvLDq-NLpvO1EnQ-S8rYBh3ouuLyxM296Ow,2618
7
+ cxc-1.0.0.dist-info/licenses/LICENSE,sha256=NFoAUNfVAojlHcEXGviGvd0K4tp8b2hRlq0CJG0O-yg,1068
8
+ cxc-1.0.0.dist-info/METADATA,sha256=FWJNg2CjZRK1xzrKHzhhVcEbsPuR7DMPqcxvf1aQjqI,4812
9
+ cxc-1.0.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
10
+ cxc-1.0.0.dist-info/entry_points.txt,sha256=SrlIgaFsceXO1bKhfzuanikxqr9KPngEBGtEp7htf_o,33
11
+ cxc-1.0.0.dist-info/top_level.txt,sha256=wX_FvyB0XjYYOySTfbA7q7Gle9suM4c8CkSbFVA7U_E,45
12
+ cxc-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ cxc = cxc:main
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) [2026] [Xyrion]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
@@ -0,0 +1,6 @@
1
+ chat
2
+ colors
3
+ config_loader
4
+ cxc
5
+ downloader
6
+ mpx
cxc.py ADDED
@@ -0,0 +1,171 @@
1
+ #!/bin/python3
2
+
3
+ import sys, datetime, shutil, subprocess
4
+
5
+ from pathlib import Path
6
+
7
+ from colors import C
8
+ from config_loader import load_config
9
+ from chat import askAI
10
+ from downloader import search, download, video_dowloader, update_OTA, local_search
11
+ from mpx import mpx
12
+
13
+ CVT = load_config()
14
+
15
+ arg = sys.argv[1:]
16
+
17
+ mpv_process = None
18
+
19
+ MUSIC_DIR = Path.home() / CVT.MUSIC_DIR
20
+ MUSIC_DIR.mkdir(parents=True, exist_ok=True)
21
+
22
+ VIDEO_DIR = Path.home() / CVT.VIDEO_DIR
23
+ VIDEO_DIR.mkdir(parents=True, exist_ok=True)
24
+
25
+ Version = "1.0.0 Stable"
26
+
27
+
28
+ def show_help():
29
+ print(f"""
30
+ =================================================
31
+ CodeX Core <==> cxc
32
+ =================================================
33
+
34
+ Version: {Version}
35
+
36
+ Usage: cxc <commands> [options]
37
+
38
+ Available commands :
39
+ - search <title> / -S <title> : Search Music Information
40
+ - search --local <title> : Search your downloaded files locally
41
+ - download <title> / -D <title> : Search and download music to MP3
42
+ - time : Displays time, day, month, year
43
+ - chat : Open the chat menu with AI
44
+ - mpx : Music Player X
45
+ - DV : Video Downloader
46
+ - update : Self Update
47
+ - version / -v : Show Version
48
+ - help / h : Display this help menu
49
+ """)
50
+
51
+ def show_help_download():
52
+ print("""
53
+ =======================================
54
+ Download Help
55
+ =======================================
56
+ - cxc download "<Music Title>"
57
+
58
+ [cxc download --help / -h]
59
+ """)
60
+
61
+ def show_help_DV():
62
+ print("""
63
+ =======================================
64
+ DV Help
65
+ =======================================
66
+ - cxc DV -r "reso" "<URL Video>"
67
+
68
+
69
+ # Example
70
+ - cxc DV -r "360" "https://youtube.com/xXxxX"
71
+
72
+
73
+ [cxc DV --help / -h]
74
+ """)
75
+
76
+ def show_help_play():
77
+ print("""
78
+ =======================================
79
+ mpx Help
80
+ =======================================
81
+ cxc mpx
82
+
83
+ [cxc mpx --help / -h]
84
+ """)
85
+
86
+ def show_help_chat():
87
+ print("""
88
+ =======================================
89
+ How To Use cxc chat?
90
+ =======================================
91
+ step 1
92
+ settings up your config
93
+ - nano ~/.config/cxc/config.toml
94
+
95
+ last step
96
+ open cxc chat
97
+ - cxc chat
98
+
99
+ [cxc chat --help / -h]
100
+ """)
101
+
102
+ def show_help_search():
103
+ print('cxc search "<Music title>"')
104
+ print('cxc search --local "<Music title>"')
105
+ print("\n [cxc search --help / -h]")
106
+
107
+ cvt = datetime.datetime.now()
108
+
109
+ def show_time():
110
+ print("Day:", cvt.strftime("%A"))
111
+ print("Hours:", cvt.strftime("%H:%M:%S"))
112
+ print("Month:", cvt.strftime("%B %Y"))
113
+
114
+
115
+ def main():
116
+ global mpv_process
117
+ match arg:
118
+ case ["download"] | ["-D"] | ["download", "--help"] | ["download", "-h"]:
119
+ show_help_download()
120
+
121
+ case ["download", query] | ["-D", query]:
122
+ download(query)
123
+
124
+ case ["DV"] | ["DV", "--help"] | ["DV", "-h"]:
125
+ show_help_DV()
126
+
127
+ case ["DV", "-r", quality, query]:
128
+ video_dowloader(query, quality)
129
+
130
+ case ["update"] | ["-U"]:
131
+ update_OTA()
132
+
133
+ case ["mpx", "--help"] | ["mpx", "-h"]:
134
+ show_help_play()
135
+
136
+
137
+ case ["mpx"]:
138
+ mpx()
139
+
140
+ case ["help"] | ["--help"] | ["h"] | ["-h"]:
141
+ show_help()
142
+
143
+ case ["time"] | ["-t"]:
144
+ show_time()
145
+
146
+ case ["search"] | ["-S"] | ["search", "--help"] | ["search", "-h"]:
147
+ show_help_search()
148
+
149
+ case ["search", "--local", query]:
150
+ local_search(query)
151
+
152
+ case ["search",query] | ["-S", query]:
153
+ search(query)
154
+
155
+ case ["chat", "--help"] | ["chat", "-h"]:
156
+ show_help_chat()
157
+
158
+ case ["chat"]:
159
+ askAI()
160
+
161
+ case ["version"] | ["-v"]:
162
+ print(Version)
163
+
164
+ case []:
165
+ show_help()
166
+
167
+ case _:
168
+ print("Command Not Found")
169
+ show_help()
170
+
171
+
downloader.py ADDED
@@ -0,0 +1,192 @@
1
+ import yt_dlp, io, contextlib, time, shutil, os, subprocess
2
+ from colors import C
3
+ from pathlib import Path
4
+
5
+ from config_loader import load_config
6
+
7
+ CVT = load_config()
8
+
9
+ MUSIC_DIR = Path.home() / CVT.MUSIC_DIR
10
+ VIDEO_DIR = Path.home() / CVT.VIDEO_DIR
11
+
12
+ def SilentLogger():
13
+ def debug(self, msg):
14
+ pass
15
+ def warning(self, msg):
16
+ pass
17
+ def error(self, msg):
18
+ pass
19
+
20
+ class QuietYDL(yt_dlp.YoutubeDL):
21
+ def to_screen(self, *args, **kwargs):
22
+ pass
23
+
24
+ def report_warning(self, *args, **kwargs):
25
+ pass
26
+
27
+ def report_error(self, message, *args, **kwargs):
28
+ raise yt_dlp.utils.DownloadError(message)
29
+
30
+ ydl_opts = {
31
+ 'format': 'bestaudio/best',
32
+ 'quiet': True,
33
+ 'no_warnings': True,
34
+ 'logger': SilentLogger(),
35
+ 'postprocessors': [{
36
+ 'key': 'FFmpegExtractAudio',
37
+ 'preferredcodec': 'mp3',
38
+ 'preferredquality': '192',
39
+ }],
40
+ 'outtmpl': str(MUSIC_DIR / '%(title)s.%(ext)s'),
41
+ }
42
+
43
+ def search(query):
44
+ try:
45
+ with QuietYDL(ydl_opts) as ydl:
46
+ with contextlib.redirect_stderr(io.StringIO()):
47
+ info = ydl.extract_info(f"ytsearch1:{query}", download=False)
48
+
49
+ entries = info.get("entries") or []
50
+
51
+ if not entries:
52
+ print("No results found")
53
+ return
54
+ else:
55
+ print("Target Found\n")
56
+
57
+ video = info['entries'][0]
58
+ nameC = video.get('uploader')
59
+ duration = video.get('duration')
60
+ description = video.get('description')[:50]
61
+ xcv = info['entries'][0]['title']
62
+ minute, second = divmod(duration, 60)
63
+ print(f"{C.BLUE}Title: {xcv}{C.RESET}")
64
+ print(f"{C.BLUE}Channel: {nameC}{C.RESET}")
65
+ print(f"{C.GREEN}Video Duration: {minute}:{second}{C.RESET}")
66
+ print(f"{C.GREEN}Short description: {description}{C.RESET}")
67
+ except yt_dlp.utils.DownloadError:
68
+ print("Connection Timeout")
69
+
70
+
71
+ def local_search(query):
72
+ try:
73
+ from rapidfuzz import fuzz
74
+ except ImportError:
75
+ fuzz = None
76
+
77
+ query = query.strip().lower()
78
+
79
+ if not query:
80
+ print("Please provide a keyword to search")
81
+ return
82
+
83
+ tokens = query.split()
84
+ folders = [MUSIC_DIR, VIDEO_DIR]
85
+ matches = []
86
+
87
+ for folder in folders:
88
+ if not folder.exists():
89
+ continue
90
+
91
+ for file in folder.rglob("*"):
92
+ if not file.is_file():
93
+ continue
94
+
95
+ name = file.stem.lower()
96
+ score = 0
97
+
98
+ for tok in tokens:
99
+ if len(tok) < 3 or fuzz is None:
100
+ if tok not in name:
101
+ score = 0
102
+ break
103
+ score = max(score, 100)
104
+ else:
105
+ ratio = fuzz.partial_ratio(tok, name)
106
+ if ratio < 70:
107
+ score = 0
108
+ break
109
+ score = max(score, ratio)
110
+
111
+ if score:
112
+ matches.append((score, file))
113
+
114
+ if not matches:
115
+ print(f'No local file matching "{query}"')
116
+ return
117
+
118
+ matches.sort(key=lambda item: item[0], reverse=True)
119
+
120
+ print(f"Found {len(matches)} local file(s):\n")
121
+ for score, file in matches:
122
+ print(f" {C.GREEN}{file.name}{C.RESET} {C.BLUE}[{score:.0f}%]{C.RESET}")
123
+ print(f" {C.CYAN}{file}{C.RESET}")
124
+
125
+
126
+ def download(query):
127
+ print("Please Wait...")
128
+
129
+ time.sleep(1)
130
+ try:
131
+ with QuietYDL(ydl_opts) as ydl:
132
+ with contextlib.redirect_stderr(io.StringIO()):
133
+ info = ydl.extract_info(f"ytsearch1:{query}", download=False)
134
+
135
+ entries = info.get("entries") or []
136
+
137
+ if not entries:
138
+ print("No results found")
139
+ return
140
+ else:
141
+ print("Target Found, Starting Download")
142
+
143
+ Xid = info['entries'][0]['id']
144
+ url = f"https://youtu.be/{Xid}"
145
+ xcv = info['entries'][0]['title']
146
+
147
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
148
+ ydl.download([url])
149
+ cmd = input("Do You Play It? [y/n] ").lower()
150
+
151
+ if cmd == "y":
152
+ cmd_args = ["mpv", "--no-video", MUSIC_DIR / xcv] + [".mp3"]
153
+ final_args = cmd_args[:2] + [str(cmd_args[2]) + cmd_args[3]]
154
+ subprocess.Popen(final_args)
155
+
156
+ except yt_dlp.utils.DownloadError:
157
+ print("Connection Timeout")
158
+ return
159
+
160
+ def video_dowloader(query, quality):
161
+ options = f"bestvideo[height<={quality}]+bestaudio/best[height<={quality}]"
162
+
163
+ opts = {
164
+ 'format': options,
165
+ 'quiet': True,
166
+ 'no_warnings': True,
167
+ 'logger': SilentLogger(),
168
+ 'merge_output_format': 'mp4',
169
+ 'outtmpl': str(VIDEO_DIR / '%(title)s.%(ext)s'),
170
+ }
171
+
172
+ try:
173
+ with yt_dlp.YoutubeDL(opts) as ydl:
174
+ ydl.download([query])
175
+
176
+ except yt_dlp.utils.DownloadError:
177
+ print("Connection Timeout")
178
+ return
179
+
180
+ def update_OTA():
181
+ ota = os.system("pipx upgrade cxc")
182
+
183
+ if ota != 0:
184
+ os.system("clear")
185
+ print("[Error] Failed to upgrade cxc")
186
+ answer = input("Try again now? [y/n]: ")
187
+
188
+ if answer == "y":
189
+ print("accepted...")
190
+ os.system("pipx upgrade cxc")
191
+ else:
192
+ return
mpx.py ADDED
@@ -0,0 +1,93 @@
1
+ import os, time, subprocess
2
+ from pathlib import Path
3
+
4
+ from config_loader import load_config
5
+
6
+ CVT = load_config()
7
+
8
+ MUSIC_DIR = Path.home() / CVT.MUSIC_DIR
9
+
10
+ mpv_state = None
11
+
12
+ def mpx():
13
+ global mpv_state
14
+
15
+
16
+ while True:
17
+ try:
18
+ os.system("clear")
19
+ print("Welcome To Music Player X")
20
+ cmd = input("MPX >>> ").lower().strip()
21
+
22
+ if cmd == "quit":
23
+ return
24
+
25
+ elif cmd.startswith("play "):
26
+ args = cmd.split(" ", 1)[1]
27
+ songs = sorted(MUSIC_DIR.glob("*.mp3")) + sorted(MUSIC_DIR.glob("*.flac")) + sorted(MUSIC_DIR.glob("*.wav"))
28
+
29
+ if args == "all":
30
+ if mpv_state:
31
+ mpv_state.terminate()
32
+ print("[+] Playing All Songs")
33
+
34
+ cmd_args = ["mpv", "--no-video"] + [str(s) for s in songs]
35
+ mpv_state = subprocess.Popen(cmd_args)
36
+
37
+ if not songs:
38
+ print("[-] Empty Music Folder ")
39
+ elif args.isdigit():
40
+ idx = int(args) - 1
41
+ if 0 <= idx < len(songs):
42
+ song = songs[idx]
43
+ if mpv_state:
44
+ mpv_state.terminate()
45
+
46
+ print(f"[+] Playing: {song.name}")
47
+ mpv_state = subprocess.Popen(["mpv", "--no-video", str(song)])
48
+ else:
49
+ print(f"[-] Number {args} not found. Max: {len(songs)}")
50
+ else:
51
+ song = MUSIC_DIR / args
52
+ if song.exists():
53
+ if mpv_state:
54
+ mpv_state.terminate()
55
+ print(f"[+] Playing: {song.name}")
56
+ mpv_state = subprocess.Popen(["mpv", "--no-video", str(song)])
57
+ else:
58
+ print(f"[-] File {args} not found ")
59
+ input()
60
+ elif cmd == "list":
61
+ songs = sorted(MUSIC_DIR.glob("*.mp3")) + sorted(MUSIC_DIR.glob("*.flac")) + sorted(MUSIC_DIR.glob("*.wav"))
62
+ if not songs:
63
+ print("[-]Empty Music Folder ")
64
+ else:
65
+ print("=" * 56)
66
+ for i, song in enumerate(songs, 1):
67
+ print(f"{i}. {song.name}")
68
+ print("play all, for play all music in folder")
69
+ print("=" * 56)
70
+ print("Enter To Exit")
71
+ input()
72
+ elif cmd == "help":
73
+ print("""
74
+ ======================
75
+ Avaible Command:
76
+ ======================
77
+ - play <args>
78
+ - list
79
+ - help
80
+
81
+
82
+
83
+ [NOTES]
84
+ When running inside this interactive shell,
85
+ mpv controls may experience input buffering delay.
86
+ If shortcuts like Space (Pause) or q (Stop) feel unresponsive,
87
+ please press the key 2-3 times consecutively to trigger it.
88
+ Enter To Exit
89
+ """)
90
+ input()
91
+
92
+ except Exception as e:
93
+ printf("Error: {e}")