asciify-term 0.3.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.
- ascii_art/__init__.py +2 -0
- ascii_art/__main__.py +5 -0
- ascii_art/__version__.py +1 -0
- ascii_art/charset.py +69 -0
- ascii_art/cli.py +166 -0
- ascii_art/converter.py +62 -0
- ascii_art/image_loader.py +123 -0
- ascii_art/image_resize.py +132 -0
- ascii_art/server.py +95 -0
- ascii_art/terminal.py +144 -0
- ascii_art/ui.py +43 -0
- ascii_art/url_image_loader.py +117 -0
- ascii_art/writer.py +116 -0
- asciify_term-0.3.0.dist-info/METADATA +156 -0
- asciify_term-0.3.0.dist-info/RECORD +19 -0
- asciify_term-0.3.0.dist-info/WHEEL +5 -0
- asciify_term-0.3.0.dist-info/entry_points.txt +2 -0
- asciify_term-0.3.0.dist-info/licenses/LICENSE +21 -0
- asciify_term-0.3.0.dist-info/top_level.txt +1 -0
ascii_art/__init__.py
ADDED
ascii_art/__main__.py
ADDED
ascii_art/__version__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.3.0"
|
ascii_art/charset.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# src/ascii_art/charset.py
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
# Define available charsets in a dictionary for easy lookup
|
|
6
|
+
CHARSETS = {
|
|
7
|
+
"default": " .:;!|)]>#$@%",
|
|
8
|
+
"simple": " .:-=+*#%@",
|
|
9
|
+
"blocks": " ░▒▓█",
|
|
10
|
+
"blocks_extended": " ░░▒▒▓▓██",
|
|
11
|
+
"binary": "10",
|
|
12
|
+
"cyberpunk": " .:?08NM",
|
|
13
|
+
"braille": " ⠐⠠⢀⠂⠔⢄⠒⠤⢆⠖⠦⢖⠶⠷⡷⠿⣟⣯⣷⣾⣿",
|
|
14
|
+
"braille_small": "⠀⠁⠃⠇⠏⠟⠿⡿⣿",
|
|
15
|
+
"tech": " ⠂⠔⠦⠶⠷▏░⠿▎▍▒▓▌▟▋▊▉█",
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
CONFIG_FILE = Path.home() / ".asciify_config.json"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_charset(custom_charset=None):
|
|
22
|
+
"""
|
|
23
|
+
Returns the charset to use.
|
|
24
|
+
Priority:
|
|
25
|
+
1. Custom string passed via CLI flag (-c)
|
|
26
|
+
2. Persisted user preference (set via --set-charset)
|
|
27
|
+
3. Default charset
|
|
28
|
+
"""
|
|
29
|
+
# 1. Custom CLI Override
|
|
30
|
+
if custom_charset:
|
|
31
|
+
if isinstance(custom_charset, str) and len(custom_charset) > 0:
|
|
32
|
+
return custom_charset
|
|
33
|
+
else:
|
|
34
|
+
raise ValueError("Custom charset must be a non-empty string.")
|
|
35
|
+
|
|
36
|
+
# 2. Check Persistent Config
|
|
37
|
+
saved_charset_name = load_persistent_charset_name()
|
|
38
|
+
if saved_charset_name and saved_charset_name in CHARSETS:
|
|
39
|
+
return CHARSETS[saved_charset_name]
|
|
40
|
+
|
|
41
|
+
# 3. Default
|
|
42
|
+
return CHARSETS["default"]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def set_persistent_charset(charset_name):
|
|
46
|
+
"""Saves the user's preferred charset name to a local config file."""
|
|
47
|
+
if charset_name not in CHARSETS:
|
|
48
|
+
available = ", ".join(CHARSETS.keys())
|
|
49
|
+
raise ValueError(f"Invalid charset '{charset_name}'. Available: {available}")
|
|
50
|
+
|
|
51
|
+
try:
|
|
52
|
+
data = {"charset": charset_name}
|
|
53
|
+
with open(CONFIG_FILE, "w") as f:
|
|
54
|
+
json.dump(data, f)
|
|
55
|
+
print(f"✅ Default charset set to: {charset_name}")
|
|
56
|
+
except Exception as e:
|
|
57
|
+
print(f"❌ Failed to save config: {e}")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def load_persistent_charset_name():
|
|
61
|
+
"""Loads the preferred charset name if it exists."""
|
|
62
|
+
if not CONFIG_FILE.exists():
|
|
63
|
+
return None
|
|
64
|
+
try:
|
|
65
|
+
with open(CONFIG_FILE, "r") as f:
|
|
66
|
+
data = json.load(f)
|
|
67
|
+
return data.get("charset")
|
|
68
|
+
except Exception:
|
|
69
|
+
return None
|
ascii_art/cli.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
# src/ascii_art/cli.py
|
|
2
|
+
import argparse
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from . import charset as charset_mod
|
|
8
|
+
from . import (converter, image_loader, image_resize, server, terminal, ui,
|
|
9
|
+
writer)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def parse_args():
|
|
13
|
+
parser = argparse.ArgumentParser(
|
|
14
|
+
description="Asciify: Terminal-first ASCII Art Generator", add_help=True
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
# --- INPUT ---
|
|
18
|
+
parser.add_argument("-i", "--input-file", help="Path to input image file")
|
|
19
|
+
|
|
20
|
+
# --- MODE SWITCH ---
|
|
21
|
+
parser.add_argument(
|
|
22
|
+
"--full", action="store_true", help="Launch the legacy interactive mode"
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
# --- OUTPUT FLAGS ---
|
|
26
|
+
parser.add_argument(
|
|
27
|
+
"-s", "--save", action="store_true", help="Save output to current directory"
|
|
28
|
+
)
|
|
29
|
+
parser.add_argument("--output-folder", help="Specify directory for saved output")
|
|
30
|
+
parser.add_argument(
|
|
31
|
+
"--output-file-name", help="Specify filename (WITHOUT extension)"
|
|
32
|
+
)
|
|
33
|
+
parser.add_argument(
|
|
34
|
+
"--html", action="store_true", help="Save as HTML file (preserves color)"
|
|
35
|
+
)
|
|
36
|
+
parser.add_argument("--color", action="store_true", help="Enable colorized output")
|
|
37
|
+
|
|
38
|
+
# --- DIMENSION FLAGS ---
|
|
39
|
+
parser.add_argument("--width", type=int, help="Target width")
|
|
40
|
+
parser.add_argument("--height", type=int, help="Target height")
|
|
41
|
+
parser.add_argument("--aspect-ratio", type=float, help="Target aspect ratio")
|
|
42
|
+
parser.add_argument("--downsize", type=float, help="Downsize factor (n)")
|
|
43
|
+
|
|
44
|
+
# --- CHARSET FLAGS ---
|
|
45
|
+
parser.add_argument(
|
|
46
|
+
"--show-charsets", action="store_true", help="List available charsets"
|
|
47
|
+
)
|
|
48
|
+
parser.add_argument("--set-charset", help="Set the default charset for future runs")
|
|
49
|
+
parser.add_argument(
|
|
50
|
+
"-c", "--charset", help="Use a specific charset string for this run"
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
# --- LEGACY/FULL MODE ONLY ---
|
|
54
|
+
parser.add_argument(
|
|
55
|
+
"--no-preview", action="store_true", help="Skip preview (Full mode only)"
|
|
56
|
+
)
|
|
57
|
+
parser.add_argument(
|
|
58
|
+
"--no-animate", action="store_true", help="Disable animation (Full mode only)"
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
# Parse
|
|
62
|
+
args = parser.parse_args()
|
|
63
|
+
return args
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def run_legacy_interactive_mode(args):
|
|
67
|
+
"""
|
|
68
|
+
The old interactive workflow for --full flag
|
|
69
|
+
"""
|
|
70
|
+
if args.no_animate:
|
|
71
|
+
ui.CONFIG["animate"] = False
|
|
72
|
+
|
|
73
|
+
ui.print_header()
|
|
74
|
+
|
|
75
|
+
# Image Selection
|
|
76
|
+
img_path = None
|
|
77
|
+
if args.input_file:
|
|
78
|
+
p = Path(args.input_file)
|
|
79
|
+
if not p.exists():
|
|
80
|
+
ui.cool_print(f"Error: Input path '{args.input_file}' does not exist.\n")
|
|
81
|
+
sys.exit(1)
|
|
82
|
+
img_path = p
|
|
83
|
+
else:
|
|
84
|
+
img_path = image_loader.list_and_select_image()
|
|
85
|
+
if not img_path:
|
|
86
|
+
return
|
|
87
|
+
|
|
88
|
+
# Load Image
|
|
89
|
+
do_preview = not args.no_preview
|
|
90
|
+
img = image_loader.load_image(img_path, preview=do_preview)
|
|
91
|
+
if not img:
|
|
92
|
+
return
|
|
93
|
+
|
|
94
|
+
# Dimensions
|
|
95
|
+
target_w, target_h = None, None
|
|
96
|
+
|
|
97
|
+
# Check flags first, else interactive
|
|
98
|
+
if args.width or args.height:
|
|
99
|
+
try:
|
|
100
|
+
target_w, target_h = image_resize.calculate_dimensions(
|
|
101
|
+
img, args.width, args.height, args.aspect_ratio
|
|
102
|
+
)
|
|
103
|
+
except ValueError as e:
|
|
104
|
+
ui.cool_print(f"Error: {e}\n")
|
|
105
|
+
sys.exit(1)
|
|
106
|
+
|
|
107
|
+
if target_w is None or target_h is None:
|
|
108
|
+
target_w, target_h = image_resize.interactive_downsize_factor(img)
|
|
109
|
+
|
|
110
|
+
# Resize
|
|
111
|
+
img_resized = image_resize.resize_image(img, target_w, target_h)
|
|
112
|
+
|
|
113
|
+
# Charset
|
|
114
|
+
try:
|
|
115
|
+
chars = charset_mod.get_charset(args.charset)
|
|
116
|
+
except ValueError as e:
|
|
117
|
+
ui.cool_print(f"Error: {e}\n")
|
|
118
|
+
sys.exit(1)
|
|
119
|
+
|
|
120
|
+
# Convert
|
|
121
|
+
ui.cool_print(f"Converting to {target_w}x{target_h}...\n")
|
|
122
|
+
ascii_grid = converter.image_to_ascii(img_resized, chars)
|
|
123
|
+
|
|
124
|
+
# Save
|
|
125
|
+
output_path = writer.save_art(
|
|
126
|
+
ascii_grid, img_path, output_name=args.output_file_name
|
|
127
|
+
)
|
|
128
|
+
if not output_path:
|
|
129
|
+
return
|
|
130
|
+
|
|
131
|
+
# Server
|
|
132
|
+
ui.clear_terminal()
|
|
133
|
+
server.start_server_and_open_browser(output_path)
|
|
134
|
+
ui.cool_print("\nServer is running. Check your browser.\n")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def main():
|
|
138
|
+
args = parse_args()
|
|
139
|
+
|
|
140
|
+
# --- 1. CHECK FOR NO ARGS ---
|
|
141
|
+
if len(sys.argv) == 1:
|
|
142
|
+
# "python -m src.ascii_art -> this will DO NOTHING, AND JUST THROW AN ERROR"
|
|
143
|
+
print("Error: No arguments provided.")
|
|
144
|
+
print("Usage: asciify -i <input_file> [options]")
|
|
145
|
+
print("Try 'asciify --help' for details.")
|
|
146
|
+
sys.exit(1)
|
|
147
|
+
|
|
148
|
+
# --- 2. BRANCH: FULL INTERACTIVE MODE ---
|
|
149
|
+
if args.full:
|
|
150
|
+
while True:
|
|
151
|
+
run_legacy_interactive_mode(args)
|
|
152
|
+
# Legacy loop logic
|
|
153
|
+
ui.cool_print("Enter 1 to run again, or any other key to exit: ")
|
|
154
|
+
choice = input().strip()
|
|
155
|
+
if choice != "1":
|
|
156
|
+
ui.clear_terminal()
|
|
157
|
+
sys.exit()
|
|
158
|
+
ui.clear_terminal()
|
|
159
|
+
|
|
160
|
+
# --- 3. BRANCH: TERMINAL MODE (DEFAULT) ---
|
|
161
|
+
# This handles -i, configuration, printing, and saving
|
|
162
|
+
terminal.run_terminal_pipeline(args)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
if __name__ == "__main__":
|
|
166
|
+
main()
|
ascii_art/converter.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# src/ascii_art/converter.py
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def image_to_ascii(img, charset):
|
|
6
|
+
"""
|
|
7
|
+
Converts a PIL image to a 2D list of characters (Grayscale).
|
|
8
|
+
"""
|
|
9
|
+
arr = np.array(img)
|
|
10
|
+
|
|
11
|
+
# Handle dimensions (Height, Width)
|
|
12
|
+
# Convert to grayscale logic: max(R, G, B)
|
|
13
|
+
if len(arr.shape) == 3:
|
|
14
|
+
# Vectorized operation: max across channel axis (axis 2)
|
|
15
|
+
gray_arr = np.max(arr[:, :, :3], axis=2)
|
|
16
|
+
else:
|
|
17
|
+
gray_arr = arr
|
|
18
|
+
|
|
19
|
+
# Normalize to charset length
|
|
20
|
+
scale = (len(charset) - 1) / 255
|
|
21
|
+
indices = (gray_arr * scale).astype(int)
|
|
22
|
+
|
|
23
|
+
# Map indices to characters
|
|
24
|
+
ascii_grid = []
|
|
25
|
+
for row in indices:
|
|
26
|
+
ascii_row = [charset[i] for i in row]
|
|
27
|
+
ascii_grid.append(ascii_row)
|
|
28
|
+
|
|
29
|
+
return ascii_grid
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def image_to_ascii_with_color(img, charset):
|
|
33
|
+
"""
|
|
34
|
+
Converts a PIL image to a 2D list of tuples: (character, (r, g, b)).
|
|
35
|
+
"""
|
|
36
|
+
# Ensure image is RGB to guarantee 3 channels
|
|
37
|
+
img_rgb = img.convert("RGB")
|
|
38
|
+
arr = np.array(img_rgb)
|
|
39
|
+
|
|
40
|
+
# 1. Get Grayscale values for Char selection
|
|
41
|
+
gray_arr = np.max(arr, axis=2)
|
|
42
|
+
|
|
43
|
+
# 2. Normalize for charset index
|
|
44
|
+
scale = (len(charset) - 1) / 255
|
|
45
|
+
indices = (gray_arr * scale).astype(int)
|
|
46
|
+
|
|
47
|
+
# 3. Build the grid
|
|
48
|
+
# This results in a list of rows, where each item is (char, (r,g,b))
|
|
49
|
+
colored_grid = []
|
|
50
|
+
|
|
51
|
+
rows, cols, _ = arr.shape
|
|
52
|
+
|
|
53
|
+
for i in range(rows):
|
|
54
|
+
row_data = []
|
|
55
|
+
for j in range(cols):
|
|
56
|
+
char_idx = indices[i, j]
|
|
57
|
+
char = charset[char_idx]
|
|
58
|
+
rgb = tuple(arr[i, j]) # (R, G, B)
|
|
59
|
+
row_data.append((char, rgb))
|
|
60
|
+
colored_grid.append(row_data)
|
|
61
|
+
|
|
62
|
+
return colored_grid
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# src/ascii_art/image_loader.py
|
|
2
|
+
import os
|
|
3
|
+
import shutil
|
|
4
|
+
import subprocess
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from PIL import Image
|
|
8
|
+
|
|
9
|
+
from . import url_image_loader # Import new handler
|
|
10
|
+
from .ui import clear_terminal, cool_print
|
|
11
|
+
|
|
12
|
+
# --- SMART PATHING LOGIC ---
|
|
13
|
+
REPO_INPUT = Path("assets/input")
|
|
14
|
+
if REPO_INPUT.exists() and REPO_INPUT.is_dir():
|
|
15
|
+
INPUT_DIR = REPO_INPUT
|
|
16
|
+
MODE = "REPO"
|
|
17
|
+
else:
|
|
18
|
+
INPUT_DIR = Path(".")
|
|
19
|
+
MODE = "USER"
|
|
20
|
+
|
|
21
|
+
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tiff"}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def list_and_select_image():
|
|
25
|
+
files = []
|
|
26
|
+
for filepath in INPUT_DIR.iterdir():
|
|
27
|
+
if filepath.is_file():
|
|
28
|
+
if filepath.suffix.lower() in IMAGE_EXTENSIONS:
|
|
29
|
+
files.append(filepath)
|
|
30
|
+
|
|
31
|
+
if not files:
|
|
32
|
+
if MODE == "REPO":
|
|
33
|
+
cool_print(f"No files found in {INPUT_DIR}\n")
|
|
34
|
+
else:
|
|
35
|
+
cool_print("No image files found in the current directory.\n")
|
|
36
|
+
cool_print("Tip: Run this command inside a folder containing images.\n")
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
files.sort(key=lambda f: f.stat().st_mtime, reverse=True)
|
|
40
|
+
|
|
41
|
+
cool_print(f"Scanning: {INPUT_DIR.resolve()}\n")
|
|
42
|
+
cool_print("Available images (sorted by newest):\n")
|
|
43
|
+
|
|
44
|
+
max_show = 15
|
|
45
|
+
for idx, f in enumerate(files[:max_show]):
|
|
46
|
+
print(f"[{idx}] {f.name}")
|
|
47
|
+
|
|
48
|
+
if len(files) > max_show:
|
|
49
|
+
print(f"... and {len(files) - max_show} more.")
|
|
50
|
+
|
|
51
|
+
print()
|
|
52
|
+
|
|
53
|
+
while True:
|
|
54
|
+
cool_print("Enter the index of the image file: ")
|
|
55
|
+
try:
|
|
56
|
+
selection = input().strip()
|
|
57
|
+
idx = int(selection)
|
|
58
|
+
if 0 <= idx < len(files):
|
|
59
|
+
return files[idx]
|
|
60
|
+
else:
|
|
61
|
+
cool_print("Invalid index. Try again.\n")
|
|
62
|
+
except ValueError:
|
|
63
|
+
cool_print("Please enter a valid number.\n")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _smart_preview(path):
|
|
67
|
+
path_str = str(path)
|
|
68
|
+
if shutil.which("powershell.exe"):
|
|
69
|
+
try:
|
|
70
|
+
subprocess.run(
|
|
71
|
+
["powershell.exe", "-c", "start", f"'{path_str}'"],
|
|
72
|
+
stdout=subprocess.DEVNULL,
|
|
73
|
+
stderr=subprocess.DEVNULL,
|
|
74
|
+
)
|
|
75
|
+
return True
|
|
76
|
+
except Exception:
|
|
77
|
+
pass
|
|
78
|
+
|
|
79
|
+
has_display = os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")
|
|
80
|
+
if not has_display:
|
|
81
|
+
return False
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
img = Image.open(path)
|
|
85
|
+
img.show()
|
|
86
|
+
return True
|
|
87
|
+
except Exception:
|
|
88
|
+
return False
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def load_image(source, preview=True):
|
|
92
|
+
"""
|
|
93
|
+
Loads an image from a Path object OR a URL string.
|
|
94
|
+
"""
|
|
95
|
+
# 1. URL HANDLING
|
|
96
|
+
if isinstance(source, str) and source.startswith(("http://", "https://")):
|
|
97
|
+
# URLs are never previewed (we don't save to disk)
|
|
98
|
+
data, filename = url_image_loader.download_image(source)
|
|
99
|
+
if not data:
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
try:
|
|
103
|
+
img = Image.open(data)
|
|
104
|
+
# Attach the original filename to the object metadata
|
|
105
|
+
# This allows terminal.py to use it for saving without a real file path
|
|
106
|
+
img.info["custom_filename"] = filename
|
|
107
|
+
return img
|
|
108
|
+
except Exception as e:
|
|
109
|
+
cool_print(f"Error opening downloaded image data: {e}\n")
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
# 2. LOCAL FILE HANDLING
|
|
113
|
+
try:
|
|
114
|
+
img = Image.open(source)
|
|
115
|
+
if preview:
|
|
116
|
+
cool_print(f"Opening {source} for preview...\n")
|
|
117
|
+
success = _smart_preview(source)
|
|
118
|
+
if not success:
|
|
119
|
+
cool_print("Warning: No suitable display found. Skipping preview.\n")
|
|
120
|
+
return img
|
|
121
|
+
except Exception as e:
|
|
122
|
+
cool_print(f"Error loading image: {e}\n")
|
|
123
|
+
return None
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# src/ascii_art/image_resize.py
|
|
2
|
+
import shutil
|
|
3
|
+
|
|
4
|
+
from PIL import Image
|
|
5
|
+
|
|
6
|
+
from .ui import cool_print
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def calculate_dimensions(img, target_w=None, target_h=None, ratio=None):
|
|
10
|
+
orig_w, orig_h = img.size
|
|
11
|
+
orig_ratio = orig_w / orig_h
|
|
12
|
+
|
|
13
|
+
if target_w and target_h and ratio:
|
|
14
|
+
calc_ratio = target_w / target_h
|
|
15
|
+
if abs(calc_ratio - ratio) > 0.01:
|
|
16
|
+
raise ValueError(
|
|
17
|
+
f"Conflict: Width ({target_w}) and Height ({target_h}) imply ratio {calc_ratio:.2f}, but --ratio {ratio} was provided."
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
if target_w and target_h:
|
|
21
|
+
return target_w, target_h
|
|
22
|
+
|
|
23
|
+
if target_w:
|
|
24
|
+
r = ratio if ratio else orig_ratio
|
|
25
|
+
return target_w, int(target_w / r)
|
|
26
|
+
|
|
27
|
+
if target_h:
|
|
28
|
+
r = ratio if ratio else orig_ratio
|
|
29
|
+
return int(target_h * r), target_h
|
|
30
|
+
|
|
31
|
+
return None, None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def resize_image(img, width, height):
|
|
35
|
+
return img.resize((width, height), Image.Resampling.LANCZOS)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def interactive_downsize_factor(img, bypass_downsizing=False):
|
|
39
|
+
orig_w, orig_h = img.size
|
|
40
|
+
cool_print(f"\nOriginal dimensions: {orig_w}x{orig_h}\n")
|
|
41
|
+
|
|
42
|
+
while True:
|
|
43
|
+
cool_print("Enter downsize factor 'n' (New size = Original / n): ")
|
|
44
|
+
try:
|
|
45
|
+
val = input().strip()
|
|
46
|
+
n = float(val)
|
|
47
|
+
|
|
48
|
+
if bypass_downsizing:
|
|
49
|
+
if n <= 0:
|
|
50
|
+
cool_print("Factor 'n' must be > 0. Try again.\n")
|
|
51
|
+
continue
|
|
52
|
+
else:
|
|
53
|
+
if n < 1:
|
|
54
|
+
cool_print("Factor 'n' must be >= 1 (Downsizing only).\n")
|
|
55
|
+
cool_print("Use --bypass-downsizing flag to allow upscaling.\n")
|
|
56
|
+
continue
|
|
57
|
+
|
|
58
|
+
new_w = int(orig_w / n)
|
|
59
|
+
new_h = int(orig_h / n)
|
|
60
|
+
|
|
61
|
+
if new_w < 1 or new_h < 1:
|
|
62
|
+
cool_print(
|
|
63
|
+
f"Resulting image ({new_w}x{new_h}) is too small! Use a smaller 'n'.\n"
|
|
64
|
+
)
|
|
65
|
+
continue
|
|
66
|
+
|
|
67
|
+
cool_print(f"Calculated dimensions: {new_w}x{new_h}\n")
|
|
68
|
+
return new_w, new_h
|
|
69
|
+
|
|
70
|
+
except ValueError:
|
|
71
|
+
cool_print("Invalid number. Please enter a number (e.g. 2, 4, 10).\n")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# --- UPDATED TERMINAL FIT LOGIC ---
|
|
75
|
+
def get_auto_terminal_dimensions(img):
|
|
76
|
+
"""
|
|
77
|
+
Calculates the width/height to fit the image strictly within
|
|
78
|
+
the current terminal view using the 'Downsize Factor n' approach.
|
|
79
|
+
"""
|
|
80
|
+
# 1. Get Terminal Size
|
|
81
|
+
# Fallback to 80x24 if detection fails
|
|
82
|
+
# term_w, term_h = shutil.get_terminal_size((80, 24))
|
|
83
|
+
term_w, term_h = shutil.get_terminal_size()
|
|
84
|
+
|
|
85
|
+
# We remove 1 line from height to leave room for the cursor/prompt at the bottom
|
|
86
|
+
# We keep width as-is, or remove 1 if terminal auto-wraps aggressively
|
|
87
|
+
max_w = term_w
|
|
88
|
+
max_h = term_h - 1
|
|
89
|
+
|
|
90
|
+
iw, ih = img.size
|
|
91
|
+
|
|
92
|
+
# 2. Define Font Correction
|
|
93
|
+
# Terminal characters are tall (~2x height of width).
|
|
94
|
+
# To maintain visual aspect ratio, we must squash the height by ~0.5-0.8.
|
|
95
|
+
FONT_ASPECT_CORRECTION = 0.75
|
|
96
|
+
|
|
97
|
+
# 3. Calculate "n" needed to fit Width
|
|
98
|
+
# Formula: new_w = iw / n => n = iw / new_w
|
|
99
|
+
# We want new_w <= max_w, so:
|
|
100
|
+
n_width = iw / max_w
|
|
101
|
+
|
|
102
|
+
# 4. Calculate "n" needed to fit Height
|
|
103
|
+
# Formula: new_h = (ih / n) * 0.5 => n = (ih * 0.5) / new_h
|
|
104
|
+
# We want new_h <= max_h, so:
|
|
105
|
+
n_height = (ih * FONT_ASPECT_CORRECTION) / max_h
|
|
106
|
+
|
|
107
|
+
# 5. Determine Final 'n'
|
|
108
|
+
# To satisfy BOTH constraints (Width fit AND Height fit),
|
|
109
|
+
# we must use the LARGER 'n' (which produces the smaller image).
|
|
110
|
+
# This automatically handles the "Landscape vs Portrait" logic:
|
|
111
|
+
# - If Portrait, ih is big, so n_height will likely be bigger -> Fits to Height.
|
|
112
|
+
# - If Landscape, iw is big, so n_width will likely be bigger -> Fits to Width.
|
|
113
|
+
# - If Landscape but super tall result (the "catch"), n_height becomes bigger -> Fits to Height.
|
|
114
|
+
n = max(n_width, n_height)
|
|
115
|
+
|
|
116
|
+
# Sanity check: prevent upscaling (n < 1) unless you want tiny images to fill screen.
|
|
117
|
+
# For a viewer, usually we accept n < 1 (zoom in), but if you prefer strictly
|
|
118
|
+
# "Fit inside but don't upscale", uncomment the next line:
|
|
119
|
+
# n = max(n, 1.0)
|
|
120
|
+
|
|
121
|
+
if n == 0:
|
|
122
|
+
n = 1 # Prevent div by zero for weird edge cases
|
|
123
|
+
|
|
124
|
+
# 6. Calculate Final Dimensions
|
|
125
|
+
final_w = int(iw / n)
|
|
126
|
+
final_h = int((ih / n) * FONT_ASPECT_CORRECTION)
|
|
127
|
+
|
|
128
|
+
# Ensure at least 1x1
|
|
129
|
+
final_w = max(1, final_w)
|
|
130
|
+
final_h = max(1, final_h)
|
|
131
|
+
|
|
132
|
+
return final_w, final_h
|
ascii_art/server.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# src/ascii_art/server.py
|
|
2
|
+
import http.server
|
|
3
|
+
import shutil
|
|
4
|
+
import socketserver
|
|
5
|
+
import subprocess
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
import webbrowser
|
|
9
|
+
|
|
10
|
+
from .ui import cool_print
|
|
11
|
+
|
|
12
|
+
# --- GLOBAL STATE ---
|
|
13
|
+
SERVER_STATE = {"current_file": None, "is_running": False}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class DynamicFileHandler(http.server.SimpleHTTPRequestHandler):
|
|
17
|
+
def log_message(self, format, *args):
|
|
18
|
+
# Silence server logs
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
def do_GET(self):
|
|
22
|
+
if self.path == "/" or self.path == "/myfile":
|
|
23
|
+
filepath = SERVER_STATE["current_file"]
|
|
24
|
+
|
|
25
|
+
if not filepath:
|
|
26
|
+
self.send_error(404, "No file currently loaded.")
|
|
27
|
+
return
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
with open(filepath, "rb") as f:
|
|
31
|
+
content = f.read()
|
|
32
|
+
self.send_response(200)
|
|
33
|
+
self.send_header("Content-type", "text/plain; charset=utf-8")
|
|
34
|
+
self.end_headers()
|
|
35
|
+
self.wfile.write(content)
|
|
36
|
+
except Exception as e:
|
|
37
|
+
self.send_error(404, f"File not found: {e}")
|
|
38
|
+
else:
|
|
39
|
+
self.send_error(404, "Not Found")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def open_browser_silently(url):
|
|
43
|
+
"""
|
|
44
|
+
Opens the browser using PowerShell on WSL/Windows to avoid
|
|
45
|
+
'grep: WSLInterop' stderr noise from Python's webbrowser module.
|
|
46
|
+
"""
|
|
47
|
+
# 1. Try Windows/WSL native method (Silent)
|
|
48
|
+
if shutil.which("powershell.exe"):
|
|
49
|
+
try:
|
|
50
|
+
subprocess.run(
|
|
51
|
+
["powershell.exe", "-c", "start", f"'{url}'"],
|
|
52
|
+
stdout=subprocess.DEVNULL,
|
|
53
|
+
stderr=subprocess.DEVNULL,
|
|
54
|
+
)
|
|
55
|
+
return
|
|
56
|
+
except Exception:
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
# 2. Fallback to standard Python way (Linux/Mac)
|
|
60
|
+
try:
|
|
61
|
+
webbrowser.open(url)
|
|
62
|
+
except Exception:
|
|
63
|
+
pass
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def start_server_and_open_browser(filepath):
|
|
67
|
+
PORT = 8000
|
|
68
|
+
|
|
69
|
+
SERVER_STATE["current_file"] = filepath
|
|
70
|
+
url = f"http://localhost:{PORT}/myfile"
|
|
71
|
+
|
|
72
|
+
# If server is already running, just open browser
|
|
73
|
+
if SERVER_STATE["is_running"]:
|
|
74
|
+
cool_print(f"Server already running. Updating content...\n")
|
|
75
|
+
cool_print(f"Opening browser at: {url}\n")
|
|
76
|
+
open_browser_silently(url)
|
|
77
|
+
return
|
|
78
|
+
|
|
79
|
+
# Start new server
|
|
80
|
+
def run_server():
|
|
81
|
+
socketserver.TCPServer.allow_reuse_address = True
|
|
82
|
+
try:
|
|
83
|
+
with socketserver.TCPServer(("", PORT), DynamicFileHandler) as httpd:
|
|
84
|
+
SERVER_STATE["is_running"] = True
|
|
85
|
+
httpd.serve_forever()
|
|
86
|
+
except OSError as e:
|
|
87
|
+
print(f"Warning: Could not start server: {e}")
|
|
88
|
+
|
|
89
|
+
server_thread = threading.Thread(target=run_server, daemon=True)
|
|
90
|
+
server_thread.start()
|
|
91
|
+
|
|
92
|
+
time.sleep(1)
|
|
93
|
+
|
|
94
|
+
cool_print(f"Server started. Access your art at: {url}\n")
|
|
95
|
+
open_browser_silently(url)
|
ascii_art/terminal.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# src/ascii_art/terminal.py
|
|
2
|
+
import shutil
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from . import charset as charset_mod
|
|
7
|
+
from . import converter, image_loader, image_resize, ui, writer
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def run_terminal_pipeline(args):
|
|
11
|
+
"""
|
|
12
|
+
Main logic for the terminal-first workflow.
|
|
13
|
+
args: The Namespace object from argparse.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
# --- 1. CHARSET OPERATIONS ---
|
|
17
|
+
if hasattr(args, "show_charsets") and args.show_charsets:
|
|
18
|
+
print(f"\nAvailable Charsets:")
|
|
19
|
+
for name, chars in charset_mod.CHARSETS.items():
|
|
20
|
+
print(f" • {name:<15} : {chars}")
|
|
21
|
+
print()
|
|
22
|
+
if not args.input_file:
|
|
23
|
+
return
|
|
24
|
+
|
|
25
|
+
if hasattr(args, "set_charset") and args.set_charset:
|
|
26
|
+
try:
|
|
27
|
+
charset_mod.set_persistent_charset(args.set_charset)
|
|
28
|
+
except ValueError as e:
|
|
29
|
+
print(f"❌ Error: {e}")
|
|
30
|
+
sys.exit(1)
|
|
31
|
+
if not args.input_file:
|
|
32
|
+
return
|
|
33
|
+
|
|
34
|
+
# --- 2. INPUT VALIDATION & 3. LOAD IMAGE ---
|
|
35
|
+
if not args.input_file:
|
|
36
|
+
print("Error: Input file is required. Use -i/--input-file <path>")
|
|
37
|
+
sys.exit(1)
|
|
38
|
+
|
|
39
|
+
# Check if input is URL or Local File
|
|
40
|
+
is_url = args.input_file.startswith(("http://", "https://"))
|
|
41
|
+
|
|
42
|
+
img = None
|
|
43
|
+
original_path_obj = None
|
|
44
|
+
|
|
45
|
+
if is_url:
|
|
46
|
+
# Load directly (image_loader handles download)
|
|
47
|
+
img = image_loader.load_image(args.input_file, preview=False)
|
|
48
|
+
if not img:
|
|
49
|
+
sys.exit(1)
|
|
50
|
+
|
|
51
|
+
# Recover the filename we extracted during download
|
|
52
|
+
# Default to a safe fallback if missing
|
|
53
|
+
fname = img.info.get("custom_filename", "downloaded_image.jpg")
|
|
54
|
+
|
|
55
|
+
original_path_obj = Path(fname)
|
|
56
|
+
|
|
57
|
+
else:
|
|
58
|
+
# Standard Local File Check
|
|
59
|
+
p = Path(args.input_file)
|
|
60
|
+
if not p.exists():
|
|
61
|
+
print(f"Error: Input file '{args.input_file}' not found.")
|
|
62
|
+
sys.exit(1)
|
|
63
|
+
|
|
64
|
+
original_path_obj = p
|
|
65
|
+
img = image_loader.load_image(p, preview=False)
|
|
66
|
+
if not img:
|
|
67
|
+
sys.exit(1)
|
|
68
|
+
|
|
69
|
+
# --- 4. CALCULATE DIMENSIONS ---
|
|
70
|
+
if args.width and args.height and args.aspect_ratio:
|
|
71
|
+
calc_ratio = args.width / args.height
|
|
72
|
+
if abs(calc_ratio - args.aspect_ratio) > 0.01:
|
|
73
|
+
print(
|
|
74
|
+
f"❌ Error: Provided width ({args.width}) and height ({args.height}) implies ratio {calc_ratio:.2f}, but --aspect-ratio was {args.aspect_ratio}."
|
|
75
|
+
)
|
|
76
|
+
sys.exit(1)
|
|
77
|
+
|
|
78
|
+
target_w, target_h = None, None
|
|
79
|
+
|
|
80
|
+
if args.width or args.height:
|
|
81
|
+
try:
|
|
82
|
+
target_w, target_h = image_resize.calculate_dimensions(
|
|
83
|
+
img, args.width, args.height, args.aspect_ratio
|
|
84
|
+
)
|
|
85
|
+
except ValueError as e:
|
|
86
|
+
print(f"Error: {e}")
|
|
87
|
+
sys.exit(1)
|
|
88
|
+
|
|
89
|
+
elif args.downsize:
|
|
90
|
+
try:
|
|
91
|
+
factor = float(args.downsize)
|
|
92
|
+
if factor <= 0:
|
|
93
|
+
raise ValueError
|
|
94
|
+
target_w = int(img.width / factor)
|
|
95
|
+
target_h = int(img.height / factor)
|
|
96
|
+
except ValueError:
|
|
97
|
+
print("Error: --downsize must be a positive number.")
|
|
98
|
+
sys.exit(1)
|
|
99
|
+
|
|
100
|
+
else:
|
|
101
|
+
target_w, target_h = image_resize.get_auto_terminal_dimensions(img)
|
|
102
|
+
|
|
103
|
+
# --- 5. RESIZE ---
|
|
104
|
+
img_resized = image_resize.resize_image(img, target_w, target_h)
|
|
105
|
+
|
|
106
|
+
# --- 6. DETERMINE CHARSET ---
|
|
107
|
+
try:
|
|
108
|
+
chars = charset_mod.get_charset(args.charset)
|
|
109
|
+
except ValueError as e:
|
|
110
|
+
print(f"Error: {e}")
|
|
111
|
+
sys.exit(1)
|
|
112
|
+
|
|
113
|
+
# --- 7. CONVERSION ---
|
|
114
|
+
if args.color:
|
|
115
|
+
ascii_grid = converter.image_to_ascii_with_color(img_resized, chars)
|
|
116
|
+
else:
|
|
117
|
+
ascii_grid = converter.image_to_ascii(img_resized, chars)
|
|
118
|
+
|
|
119
|
+
# --- 8. OUTPUT TO TERMINAL ---
|
|
120
|
+
for row in ascii_grid:
|
|
121
|
+
line_parts = []
|
|
122
|
+
for item in row:
|
|
123
|
+
if isinstance(item, tuple):
|
|
124
|
+
char, (r, g, b) = item
|
|
125
|
+
display_str = char + "."
|
|
126
|
+
colored_str = ui.get_ansi_colored_string(display_str, r, g, b)
|
|
127
|
+
line_parts.append(colored_str)
|
|
128
|
+
else:
|
|
129
|
+
char = item
|
|
130
|
+
line_parts.append(char + " ")
|
|
131
|
+
|
|
132
|
+
sys.stdout.write("".join(line_parts) + "\n")
|
|
133
|
+
|
|
134
|
+
# --- 9. SAVE TO FILE (Optional) ---
|
|
135
|
+
should_save = any([args.save, args.output_folder, args.output_file_name, args.html])
|
|
136
|
+
|
|
137
|
+
if should_save:
|
|
138
|
+
writer.save_art(
|
|
139
|
+
ascii_grid,
|
|
140
|
+
original_filename=original_path_obj,
|
|
141
|
+
output_folder=args.output_folder,
|
|
142
|
+
output_name=args.output_file_name,
|
|
143
|
+
as_html=args.html,
|
|
144
|
+
)
|
ascii_art/ui.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# src/ascii_art/ui.py
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
CONFIG = {"animate": True}
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def cool_print(string):
|
|
10
|
+
if CONFIG["animate"]:
|
|
11
|
+
for char in string:
|
|
12
|
+
print(char, end="", flush=True)
|
|
13
|
+
time.sleep(0.01)
|
|
14
|
+
else:
|
|
15
|
+
print(string, end="", flush=True)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def clear_terminal():
|
|
19
|
+
"""
|
|
20
|
+
Hard clear: Wipes the screen completely (Windows/Linux standard).
|
|
21
|
+
"""
|
|
22
|
+
os.system("cls" if os.name == "nt" else "clear")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def soft_clear():
|
|
26
|
+
"""
|
|
27
|
+
Soft clear: Moves cursor to top-left and clears everything below it.
|
|
28
|
+
This preserves the scrollback history so users can scroll up.
|
|
29
|
+
"""
|
|
30
|
+
print("\033[H\033[J", end="")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def print_header():
|
|
34
|
+
clear_terminal()
|
|
35
|
+
cool_print("\n=== ASCII ART GENERATOR ===\n\n")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def get_ansi_colored_string(char, r, g, b):
|
|
39
|
+
"""
|
|
40
|
+
Returns the character wrapped in TrueColor (24-bit) ANSI escape codes.
|
|
41
|
+
Format: \033[38;2;R;G;Bm{char}\033[0m
|
|
42
|
+
"""
|
|
43
|
+
return f"\033[38;2;{r};{g};{b}m{char}\033[0m"
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# src/ascii_art/url_image_loader.py
|
|
2
|
+
import os
|
|
3
|
+
import urllib.error
|
|
4
|
+
import urllib.request
|
|
5
|
+
from io import BytesIO
|
|
6
|
+
from urllib.parse import unquote, urlparse
|
|
7
|
+
|
|
8
|
+
# --- SECURITY CONFIG ---
|
|
9
|
+
MAX_DOWNLOAD_SIZE = 10 * 1024 * 1024 # 10 MB Limit
|
|
10
|
+
TIMEOUT_SECONDS = 10
|
|
11
|
+
USER_AGENT = "Asciify-Term-CLI/1.0"
|
|
12
|
+
|
|
13
|
+
# List of allowed MIME types to prevent downloading malware/junk
|
|
14
|
+
ALLOWED_MIME_TYPES = {
|
|
15
|
+
"image/jpeg",
|
|
16
|
+
"image/png",
|
|
17
|
+
"image/gif",
|
|
18
|
+
"image/webp",
|
|
19
|
+
"image/bmp",
|
|
20
|
+
"image/tiff",
|
|
21
|
+
"image/x-icon",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def download_image(url):
|
|
26
|
+
"""
|
|
27
|
+
Downloads image to memory with strict safety checks.
|
|
28
|
+
Returns: (BytesIO object, filename_string) or (None, None)
|
|
29
|
+
"""
|
|
30
|
+
print(f"Downloading from URL: {url} ...")
|
|
31
|
+
|
|
32
|
+
# 1. Validate Scheme (Protocol)
|
|
33
|
+
try:
|
|
34
|
+
parsed_url = urlparse(url)
|
|
35
|
+
except ValueError:
|
|
36
|
+
print("❌ Error: Malformed URL.")
|
|
37
|
+
return None, None
|
|
38
|
+
|
|
39
|
+
if parsed_url.scheme not in ("http", "https"):
|
|
40
|
+
print("❌ Error: URL must start with http:// or https://")
|
|
41
|
+
return None, None
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
# 2. Setup Request with User-Agent
|
|
45
|
+
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
|
46
|
+
|
|
47
|
+
# 3. Open Connection (Headers only first)
|
|
48
|
+
with urllib.request.urlopen(req, timeout=TIMEOUT_SECONDS) as response:
|
|
49
|
+
|
|
50
|
+
# --- SECURITY CHECK: Content-Length ---
|
|
51
|
+
content_length = response.getheader("Content-Length")
|
|
52
|
+
if content_length and int(content_length) > MAX_DOWNLOAD_SIZE:
|
|
53
|
+
print(
|
|
54
|
+
f"❌ Error: Image too large ({int(content_length) / 1024 / 1024:.2f} MB). Max is 10 MB."
|
|
55
|
+
)
|
|
56
|
+
return None, None
|
|
57
|
+
|
|
58
|
+
# --- SECURITY CHECK: Content-Type ---
|
|
59
|
+
# Verify the server actually claims this is an image
|
|
60
|
+
content_type = response.getheader("Content-Type")
|
|
61
|
+
if content_type:
|
|
62
|
+
# Clean up header (e.g., "image/png; charset=utf-8" -> "image/png")
|
|
63
|
+
mime_type = content_type.split(";")[0].strip().lower()
|
|
64
|
+
if mime_type not in ALLOWED_MIME_TYPES:
|
|
65
|
+
# Allow generic 'application/octet-stream' only if we really trust it,
|
|
66
|
+
# but for 'watertight' security, we usually block it.
|
|
67
|
+
# We will be strict here.
|
|
68
|
+
print(
|
|
69
|
+
f"❌ Error: Invalid Content-Type '{mime_type}'. Expected an image."
|
|
70
|
+
)
|
|
71
|
+
return None, None
|
|
72
|
+
|
|
73
|
+
# 4. Stream Download (Prevent Memory Exhaustion)
|
|
74
|
+
img_data = BytesIO()
|
|
75
|
+
bytes_downloaded = 0
|
|
76
|
+
chunk_size = 8192
|
|
77
|
+
|
|
78
|
+
while True:
|
|
79
|
+
chunk = response.read(chunk_size)
|
|
80
|
+
if not chunk:
|
|
81
|
+
break
|
|
82
|
+
bytes_downloaded += len(chunk)
|
|
83
|
+
if bytes_downloaded > MAX_DOWNLOAD_SIZE:
|
|
84
|
+
print("❌ Error: Download exceeded maximum size (10 MB).")
|
|
85
|
+
return None, None
|
|
86
|
+
img_data.write(chunk)
|
|
87
|
+
|
|
88
|
+
img_data.seek(0)
|
|
89
|
+
|
|
90
|
+
# 5. Determine Filename (Robust Extraction)
|
|
91
|
+
# Unquote handles %20 spaces and other encoding
|
|
92
|
+
path_path = unquote(parsed_url.path)
|
|
93
|
+
filename = os.path.basename(path_path)
|
|
94
|
+
|
|
95
|
+
# Sanity check: If filename is empty or has no extension, fallback
|
|
96
|
+
if not filename or "." not in filename:
|
|
97
|
+
# Try to guess extension from content-type
|
|
98
|
+
ext = ".jpg" # default
|
|
99
|
+
if content_type == "image/png":
|
|
100
|
+
ext = ".png"
|
|
101
|
+
elif content_type == "image/webp":
|
|
102
|
+
ext = ".webp"
|
|
103
|
+
elif content_type == "image/gif":
|
|
104
|
+
ext = ".gif"
|
|
105
|
+
|
|
106
|
+
filename = f"downloaded_image{ext}"
|
|
107
|
+
|
|
108
|
+
return img_data, filename
|
|
109
|
+
|
|
110
|
+
except urllib.error.HTTPError as e:
|
|
111
|
+
print(f"❌ HTTP Error: {e.code} {e.reason}")
|
|
112
|
+
except urllib.error.URLError as e:
|
|
113
|
+
print(f"❌ Network Error: {e.reason}")
|
|
114
|
+
except Exception as e:
|
|
115
|
+
print(f"❌ Error processing URL: {e}")
|
|
116
|
+
|
|
117
|
+
return None, None
|
ascii_art/writer.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# src/ascii_art/writer.py
|
|
2
|
+
import html
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def clean_filename(name):
|
|
10
|
+
"""Sanitizes a string to be safe for filenames."""
|
|
11
|
+
# Allow alphanumeric, underscores, and hyphens.
|
|
12
|
+
name_no_ext = os.path.splitext(name)[0]
|
|
13
|
+
cleaned = re.sub(r"[^a-zA-Z0-9_\-]", "", name_no_ext)
|
|
14
|
+
return cleaned
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def generate_html(ascii_grid):
|
|
18
|
+
"""Generates an HTML string from the ASCII grid."""
|
|
19
|
+
lines = []
|
|
20
|
+
lines.append("<!DOCTYPE html>")
|
|
21
|
+
lines.append("<html><head><style>")
|
|
22
|
+
lines.append(
|
|
23
|
+
"body { background-color: #000; color: #fff; font-family: monospace; white-space: pre; line-height: 1.0; }"
|
|
24
|
+
)
|
|
25
|
+
lines.append("</style></head><body>")
|
|
26
|
+
|
|
27
|
+
for row in ascii_grid:
|
|
28
|
+
line_html = ""
|
|
29
|
+
for item in row:
|
|
30
|
+
if isinstance(item, tuple):
|
|
31
|
+
char, (r, g, b) = item
|
|
32
|
+
# Escape the char for HTML (<, >, &)
|
|
33
|
+
safe_char = html.escape(char)
|
|
34
|
+
line_html += f'<span style="color: rgb({r},{g},{b})">{safe_char}</span>'
|
|
35
|
+
else:
|
|
36
|
+
safe_char = html.escape(item)
|
|
37
|
+
line_html += safe_char
|
|
38
|
+
lines.append(line_html)
|
|
39
|
+
|
|
40
|
+
lines.append("</body></html>")
|
|
41
|
+
return "\n".join(lines)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def save_art(
|
|
45
|
+
ascii_grid, original_filename, output_folder=None, output_name=None, as_html=False
|
|
46
|
+
):
|
|
47
|
+
"""
|
|
48
|
+
Saves the ASCII art to a file.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
ascii_grid: The 2D list of chars or (char, rgb) tuples.
|
|
52
|
+
original_filename: Path to the input image (used for auto-naming).
|
|
53
|
+
output_folder: Directory to save in (defaults to CWD).
|
|
54
|
+
output_name: Specific filename (WITHOUT extension).
|
|
55
|
+
as_html: Boolean to save as .html instead of .txt.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
# 1. Determine Output Directory
|
|
59
|
+
if output_folder:
|
|
60
|
+
target_dir = Path(output_folder)
|
|
61
|
+
if not target_dir.exists():
|
|
62
|
+
# "make the location first" as requested
|
|
63
|
+
try:
|
|
64
|
+
os.makedirs(target_dir, exist_ok=True)
|
|
65
|
+
except OSError as e:
|
|
66
|
+
print(f"❌ Error creating directory '{output_folder}': {e}")
|
|
67
|
+
return None
|
|
68
|
+
else:
|
|
69
|
+
target_dir = Path.cwd()
|
|
70
|
+
|
|
71
|
+
# 2. Determine File Name
|
|
72
|
+
timestamp = datetime.now().strftime("%d%m%Y-%H%M%S")
|
|
73
|
+
extension = ".html" if as_html else ".txt"
|
|
74
|
+
|
|
75
|
+
if output_name:
|
|
76
|
+
# Check for user-provided extension
|
|
77
|
+
_, ext = os.path.splitext(output_name)
|
|
78
|
+
if ext:
|
|
79
|
+
print(
|
|
80
|
+
f"❌ Error: Output file name '{output_name}' must NOT include an extension."
|
|
81
|
+
)
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
# Use exact name provided by user
|
|
85
|
+
final_filename = f"{output_name}{extension}"
|
|
86
|
+
else:
|
|
87
|
+
# Auto-generate name based on input file
|
|
88
|
+
base_name = clean_filename(Path(original_filename).name)
|
|
89
|
+
final_filename = f"ascii_{base_name}_{timestamp}{extension}"
|
|
90
|
+
|
|
91
|
+
filepath = target_dir / final_filename
|
|
92
|
+
|
|
93
|
+
# 3. Write File
|
|
94
|
+
try:
|
|
95
|
+
with open(filepath, "w", encoding="utf-8") as f:
|
|
96
|
+
if as_html:
|
|
97
|
+
html_content = generate_html(ascii_grid)
|
|
98
|
+
f.write(html_content)
|
|
99
|
+
else:
|
|
100
|
+
for row in ascii_grid:
|
|
101
|
+
clean_row = []
|
|
102
|
+
for item in row:
|
|
103
|
+
if isinstance(item, tuple):
|
|
104
|
+
char = item[0]
|
|
105
|
+
else:
|
|
106
|
+
char = item
|
|
107
|
+
# Add space for aspect ratio correction in text files
|
|
108
|
+
clean_row.append(char + " ")
|
|
109
|
+
f.write("".join(clean_row) + "\n")
|
|
110
|
+
|
|
111
|
+
print(f"✅ Output saved to: {filepath}")
|
|
112
|
+
return filepath
|
|
113
|
+
|
|
114
|
+
except Exception as e:
|
|
115
|
+
print(f"❌ Error saving file: {e}")
|
|
116
|
+
return None
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: asciify-term
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: A hybrid CLI tool for ASCII art generation with terminal and web preview modes.
|
|
5
|
+
Author: V33010
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/V33010/asciify
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/V33010/asciify/issues
|
|
9
|
+
Requires-Python: >=3.12
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: numpy>=2.0.0
|
|
13
|
+
Requires-Dist: pillow>=10.0.0
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# Asciify Term
|
|
17
|
+
|
|
18
|
+

|
|
19
|
+

|
|
20
|
+

|
|
21
|
+

|
|
22
|
+
|
|
23
|
+
**Asciify Term** is a modern, cross-platform CLI utility that renders high-resolution images as ASCII art directly in your terminal.
|
|
24
|
+
|
|
25
|
+
Originally built as a creative toy, it has evolved into a powerful **DevOps utility** for verifying image assets in headless environments (SSH, Docker, WSL) where GUI viewers are unavailable. It supports local files, remote URLs, and TrueColor rendering.
|
|
26
|
+
|
|
27
|
+
## 🚀 Features
|
|
28
|
+
|
|
29
|
+
- **Terminal-First Workflow:** Instantly render images to stdout with zero configuration.
|
|
30
|
+
- **Headless Support:** Perfect for verifying plot.png or asset files on remote servers via SSH.
|
|
31
|
+
- **URL Support:** Fetch and render images directly from the web (http://...) without manual downloading.
|
|
32
|
+
- **TrueColor Support:** Renders images in full 24-bit ANSI color.
|
|
33
|
+
- **Smart Resizing:** Automatically fits the output to your current terminal window dimensions.
|
|
34
|
+
- **Export Options:** Save outputs as plain text .txt or color-preserving .html.
|
|
35
|
+
- **Legacy Interactive Mode:** A guided menu system for creative exploration.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
Install directly from PyPI:
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
pip install asciify-term
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
47
|
+
|
|
48
|
+
### 1. The Quick Scan (Default)
|
|
49
|
+
|
|
50
|
+
The primary use case is to quickly view an image in your terminal. The output automatically scales to fit your window.
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
# Local File
|
|
54
|
+
asciify -i image.jpg
|
|
55
|
+
|
|
56
|
+
# Remote URL
|
|
57
|
+
asciify -i https://example.com/logo.png
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### 2. Color Mode
|
|
61
|
+
|
|
62
|
+
To view the image with its original colors (using ANSI escape codes):
|
|
63
|
+
```sh
|
|
64
|
+
asciify -i image.jpg --color
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### 3. Saving Output
|
|
68
|
+
|
|
69
|
+
You can save the generated art to a file instead of (or in addition to) printing it.
|
|
70
|
+
|
|
71
|
+
**Save to current directory (Auto-named):**
|
|
72
|
+
```sh
|
|
73
|
+
asciify -i image.jpg -s
|
|
74
|
+
# Creates: ascii_image_TIMESTAMP.txt
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
**Save with custom name/location:**
|
|
78
|
+
```sh
|
|
79
|
+
# Save as specific filename (no extension needed)
|
|
80
|
+
asciify -i image.jpg --output-file-name my_art
|
|
81
|
+
|
|
82
|
+
# Save to a specific folder
|
|
83
|
+
asciify -i image.jpg --output-folder ./art_gallery
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
**Save as HTML (Preserves Color):**
|
|
87
|
+
```sh
|
|
88
|
+
asciify -i image.jpg --color --html
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### 4. Customizing Dimensions
|
|
92
|
+
|
|
93
|
+
By default, asciify fits the image to your terminal. You can override this:
|
|
94
|
+
|
|
95
|
+
```sh
|
|
96
|
+
# Force specific width (Height auto-calculated)
|
|
97
|
+
asciify -i image.jpg --width 100
|
|
98
|
+
|
|
99
|
+
# Force specific width AND aspect ratio
|
|
100
|
+
asciify -i image.jpg --width 100 --aspect-ratio 2.0
|
|
101
|
+
|
|
102
|
+
# Downsize by a factor of 4
|
|
103
|
+
asciify -i image.jpg --downsize 4
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### 5. Managing Charsets
|
|
107
|
+
|
|
108
|
+
You can change the characters used for rendering (e.g., standard ASCII, blocks, braille).
|
|
109
|
+
|
|
110
|
+
**List available charsets:**
|
|
111
|
+
```sh
|
|
112
|
+
asciify --show-charsets
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
**Use a specific charset for one run:**
|
|
116
|
+
```sh
|
|
117
|
+
asciify -i image.jpg -c blocks
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
**Set a new default charset (Persistent):**
|
|
121
|
+
```sh
|
|
122
|
+
asciify --set-charset blocks
|
|
123
|
+
# All future runs will now use 'blocks' by default
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
## Advanced: Interactive Mode
|
|
128
|
+
|
|
129
|
+
For a more guided, "creative" experience with animations and previews, use the --full flag. This launches the legacy interactive menu.
|
|
130
|
+
|
|
131
|
+
```sh
|
|
132
|
+
asciify --full
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Configuration Reference
|
|
136
|
+
|
|
137
|
+
| Flag | Description |
|
|
138
|
+
| :--- | :--- |
|
|
139
|
+
| -i, --input-file | Path to local image OR URL (http://...). |
|
|
140
|
+
| --color | Enable TrueColor ANSI output. |
|
|
141
|
+
| -s, --save | Save output to current directory. |
|
|
142
|
+
| --output-folder | Specify folder for saved output. |
|
|
143
|
+
| --output-file-name | Specify filename (without extension). |
|
|
144
|
+
| --html | Save as .html file. |
|
|
145
|
+
| --width | Set target width. |
|
|
146
|
+
| --height | Set target height. |
|
|
147
|
+
| --aspect-ratio | Force specific aspect ratio. |
|
|
148
|
+
| --downsize | Downsize image by factor n. |
|
|
149
|
+
| -c, --charset | Use specific charset string. |
|
|
150
|
+
| --show-charsets | List all built-in charsets. |
|
|
151
|
+
| --set-charset | Set default charset preference. |
|
|
152
|
+
| --full | Launch legacy interactive mode. |
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
Distributed under the MIT License. See LICENSE for more information.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
ascii_art/__init__.py,sha256=HCO8beQOai3kfOnYqWY8wK6kfgKxsvdd7EWWgPQvgvE,50
|
|
2
|
+
ascii_art/__main__.py,sha256=7qmGuHGp1NuJHFRPVqeKtVeSrsxKeiuYLpQHwasaWGg,89
|
|
3
|
+
ascii_art/__version__.py,sha256=VrXpHDu3erkzwl_WXrqINBm9xWkcyUy53IQOj042dOs,22
|
|
4
|
+
ascii_art/charset.py,sha256=k2QRbokdB5ucxApky3QICmbtxT0vbbcfzlz9kNBP0Qk,2171
|
|
5
|
+
ascii_art/cli.py,sha256=9dFnoh_vuNZv58q8qiYcFxPnHJjSaxRLW3KANJy4JNU,5006
|
|
6
|
+
ascii_art/converter.py,sha256=p7Pm9ZiuQQ8qfzjVwBI_2wOD3NnmnhmLLsBDqUtliEU,1660
|
|
7
|
+
ascii_art/image_loader.py,sha256=tScIwcIo7BI44nJB073GPy9BCH9NaTwoEOzg5ug31uA,3608
|
|
8
|
+
ascii_art/image_resize.py,sha256=0Y7967-BUM1mW8ZihYL0axvVdU3JBrJyaY-1FyCyisI,4431
|
|
9
|
+
ascii_art/server.py,sha256=ao6mAhG7qBVwNpLfKGjtK_241KAGCojnih6B5Edytb4,2770
|
|
10
|
+
ascii_art/terminal.py,sha256=omTvMmEscb9VSR2bA4175FbW0Brf6JxiUHs1VS-Eq1E,4524
|
|
11
|
+
ascii_art/ui.py,sha256=is_Xp8dqW_F6r5d4AV843S0Cb3eM20EoNIFmdOYLpyM,984
|
|
12
|
+
ascii_art/url_image_loader.py,sha256=p9CXTi8K2lTO8oZceL10SBnaFiq7Qmsfw98pYEkRAPU,4133
|
|
13
|
+
ascii_art/writer.py,sha256=VVpBXJic2fIZMe-qomlW50plMgXZqH1KTge_HcBAhLc,3804
|
|
14
|
+
asciify_term-0.3.0.dist-info/licenses/LICENSE,sha256=rP0bTbcKIV5ZyNk_wqjX0K3V8gx1Ni5XZ1XDA9PwyMc,1063
|
|
15
|
+
asciify_term-0.3.0.dist-info/METADATA,sha256=gVGpVsSFY4Zd_fYOPx7iu2H3HctxY7NrpPaKZTMBODI,4630
|
|
16
|
+
asciify_term-0.3.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
17
|
+
asciify_term-0.3.0.dist-info/entry_points.txt,sha256=ubvEfuML4XqguCwG72UNXB7dU5O4aHMVG4-FpEpzVJc,47
|
|
18
|
+
asciify_term-0.3.0.dist-info/top_level.txt,sha256=5Vwi_F5rCojK3tg8raIyZ5WI0JQjDYVQlfLB9KVSn4Y,10
|
|
19
|
+
asciify_term-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 V33010
|
|
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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ascii_art
|