-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhat
More file actions
executable file
·1111 lines (997 loc) · 39.6 KB
/
Copy pathhat
File metadata and controls
executable file
·1111 lines (997 loc) · 39.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# hat — the Sorting Hat: suggests appropriate filenames based on file contents
# Uses any OpenAI-compatible API (local or remote) with optional vision support
set -euo pipefail
LLM_BASE_URL="${LLM_BASE_URL:-http://localhost:8080}"
HAT_MODEL="${HAT_MODEL:-Qwen3.5-9b}"
REASONING_BUDGET="${HAT_REASONING_BUDGET:-1024}"
GUARD_BUDGET=0 # guard clause defaults to no thinking
usage() {
cat <<'HELP'
hat — the Sorting Hat for files
Suggests appropriate filenames based on file contents using an LLM.
Works with any OpenAI-compatible API — local (llama.cpp, Ollama, vLLM)
or cloud (OpenAI, Anthropic via proxy, etc).
Usage:
hat <file> [file...] Suggest and prompt to rename
hat -y <file> Auto-rename without confirmation
hat --dry-run <file> Show suggestion without renaming
hat --batch <dir> Process all files in a directory
hat --image <file> Use vision model for image files
hat --quiet <file> No animation, just print the name
Options:
--yes, -y Auto-rename without confirmation
--batch, -b Process all files in a directory
--image, -i Use vision model for image files
--dry-run, -n Just show suggestions, no rename
--quiet, -q Suppress animation (for scripting)
--ext, -e Preserve original extension (default: true)
--no-ext Let the model choose the extension too
--budget, -rb Reasoning token budget for naming (default: 1024, -1 for unlimited)
--nothink Disable thinking for both guard clause and naming
--fullthink Enable thinking for both guard clause and naming
--context, -c Additional context to guide naming (e.g. "Q3 marketing")
--no-metadata Don't include file metadata in LLM context
--force, -f Skip name quality check, always suggest a new name
--preview, -p Show a content preview before suggesting a name
Environment:
LLM_BASE_URL OpenAI-compatible base URL (default: http://localhost:8080)
HAT_MODEL Model name to use (default: Qwen3.5-9b)
HAT_API_KEY API key for the LLM (optional, for cloud providers)
HAT_REASONING_BUDGET Reasoning token budget (default: 1024)
Examples:
hat report.txt
hat -y IMG_20240301_143022.jpg
hat --batch ~/Downloads/
hat --image screenshot.png
hat -c "quarterly finance report" document.pdf
hat --batch --force ~/unsorted/
# With Ollama
LLM_BASE_URL=http://localhost:11434 HAT_MODEL=llava hat photo.jpg
# With OpenAI
LLM_BASE_URL=https://api.openai.com HAT_MODEL=gpt-4o HAT_API_KEY=sk-... hat file.txt
# With HuggingFace Inference
LLM_BASE_URL=https://api-inference.huggingface.co/models/Qwen/Qwen2.5-72B-Instruct HAT_API_KEY=hf_... hat file.txt
HELP
exit 0
}
is_binary() {
# Use file(1) for reliable binary detection — checks magic bytes and content
local mime
mime=$(file --brief --mime-encoding "$1" 2>/dev/null)
[[ "$mime" == "binary" ]]
}
# Detect audio by magic bytes first, then fall back to extension
is_audio() {
local file="$1"
local magic
magic=$(head -c 12 "$file" 2>/dev/null | od -A n -t x1 -N 12 2>/dev/null | tr -d ' \n')
# MP3: ID3 tag (49 44 33) or MPEG sync (ff fb / ff fa / ff f3 / ff f2)
[[ "$magic" == 494433* ]] && return 0
[[ "$magic" == fffb* || "$magic" == fffa* || "$magic" == fff3* || "$magic" == fff2* ]] && return 0
# FLAC: 66 4c 61 43
[[ "$magic" == 664c6143* ]] && return 0
# OGG: 4f 67 67 53
[[ "$magic" == 4f676753* ]] && return 0
# AAC (ADTS): ff f1 / ff f9
[[ "$magic" == fff1* || "$magic" == fff9* ]] && return 0
# WAV: RIFF (52 49 46 46) + WAVE at offset 8 (57 41 56 45)
[[ "$magic" == 52494646* ]] && [[ "${magic:16:8}" == "57415645" ]] && return 0
# M4A / M4B / M4P: ftyp box at bytes 4-7 (66 74 79 70) AND audio major brand
# at bytes 8-11 (M4A / M4B / M4P). The ftyp marker alone matches all
# ISO-BMFF containers — MP4 video (isom/mp42), QuickTime, HEIC iPhone images,
# 3GP — so without the brand check this is_audio call gave false positives
# for the whole iPhone-photos / video files surface.
if [[ "${magic:8:8}" == "66747970" ]]; then
case "${magic:16:8}" in
4d344120|4d344220|4d345020) return 0 ;;
esac
fi
# Fall back to extension
local ext="${file##*.}"
ext="${ext,,}"
[[ "$ext" =~ ^(mp3|wav|flac|ogg|aac|m4a|opus|wma|aiff|ape)$ ]]
}
# Detect video by magic bytes first, then fall back to extension
is_video() {
local file="$1"
local magic
magic=$(head -c 12 "$file" 2>/dev/null | od -A n -t x1 -N 12 2>/dev/null | tr -d ' \n')
# MKV / WebM: EBML header 1a 45 df a3
[[ "$magic" == 1a45dfa3* ]] && return 0
# AVI: RIFF (52 49 46 46) + AVI at offset 8 (41 56 49 20)
[[ "$magic" == 52494646* ]] && [[ "${magic:16:8}" == "41564920" ]] && return 0
# MP4 / MOV / M4V: ftyp box at bytes 4-7
if [[ "${magic:8:8}" == "66747970" ]]; then
local brand="${magic:16:8}"
# Exclude known audio-only brands (M4A, M4B, M4P)
[[ "$brand" != "4d344120" && "$brand" != "4d344220" && "$brand" != "4d345020" ]] && return 0
fi
# MPEG-1/2 video: 00 00 01 b3 (sequence header) or 00 00 01 ba (pack header)
[[ "$magic" == 000001b3* || "$magic" == 000001ba* ]] && return 0
# Fall back to extension
local ext="${file##*.}"
ext="${ext,,}"
[[ "$ext" =~ ^(mp4|mkv|avi|mov|webm|m4v|wmv|flv|mpeg|mpg|3gp|ogv|ts|mts|m2ts)$ ]]
}
# Detect image by magic bytes first, then fall back to extension
is_image() {
local file="$1"
# Check magic bytes
local magic
magic=$(head -c 16 "$file" 2>/dev/null | od -A n -t x1 -N 16 2>/dev/null | tr -d ' \n')
# JPEG: ff d8 ff
[[ "$magic" == ffd8ff* ]] && return 0
# PNG: 89 50 4e 47
[[ "$magic" == 89504e47* ]] && return 0
# GIF: 47 49 46 38
[[ "$magic" == 47494638* ]] && return 0
# BMP: 42 4d
[[ "$magic" == 424d* ]] && return 0
# TIFF: 49 49 2a 00 (little-endian) or 4d 4d 00 2a (big-endian)
[[ "$magic" == 49492a00* || "$magic" == 4d4d002a* ]] && return 0
# WebP: 52 49 46 46 ... 57 45 42 50
[[ "$magic" == 52494646* ]] && [[ "${magic:16:8}" == "57454250" ]] && return 0
# Fall back to extension for SVG (text-based) and edge cases
local ext="${file##*.}"
ext="${ext,,}"
[[ "$ext" =~ ^(svg)$ ]]
}
# Encode file content as a JSON user_content value (string for text, array for images).
# Used by check_filename, build_payload, and stream_with_hat to avoid duplication.
# Writes JSON to a temp file and prints the path to stdout (avoids ARG_MAX for large images).
build_user_content() {
local file="$1" mode="$2" prompt="$3"
local tmpfile
tmpfile=$(mktemp)
python3 - "$file" "$mode" "$prompt" "$tmpfile" <<'CONTENTEOF'
import json, sys, base64, io
file, mode, prompt, outfile = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
if mode == "image":
ext = file.rsplit('.', 1)[-1].lower() if '.' in file else ''
if ext in ('webp', 'bmp', 'tiff', 'tif', 'gif'):
from PIL import Image
img = Image.open(file).convert('RGB')
buf = io.BytesIO()
img.save(buf, format='PNG')
b64 = base64.b64encode(buf.getvalue()).decode()
mime = 'image/png'
else:
with open(file, 'rb') as f:
b64 = base64.b64encode(f.read()).decode()
mime = {'jpg':'image/jpeg','jpeg':'image/jpeg','png':'image/png',
'svg':'image/svg+xml'}.get(ext, 'image/jpeg')
content = [
{'type': 'image_url', 'image_url': {'url': f'data:{mime};base64,{b64}'}},
{'type': 'text', 'text': prompt}
]
elif mode in ("audio", "video"):
# Audio/video files can't be passed to the LLM directly — metadata was
# already injected into the prompt by collect_metadata().
content = prompt
else:
with open(file, 'r', errors='replace') as f:
content = f.read(4000)
content = prompt + '\n\nFile contents:\n' + content
with open(outfile, 'w') as f:
json.dump(content, f)
CONTENTEOF
echo "$tmpfile"
}
# Build the guard clause prompt for a given filename, with optional metadata
build_check_prompt() {
local basename="$1" metadata="${2:-}"
local prompt="Look at this file's content and its current filename \"$basename\". Does the filename already accurately describe what this file contains? A good filename is specific and descriptive (e.g. 'quarterly-sales-report', 'sunset-mountain-photo'). Generic names like 'document', 'file', 'image', 'test', 'sample', or auto-generated names like 'IMG_1234', 'DSC_0001', 'Screenshot_2024' are NOT good. Reply ONLY 'YES' if the name is already descriptive, or 'NO' if it should be renamed."
if [[ -n "$metadata" && "$metadata" != "{}" ]]; then
prompt="$prompt
File metadata: $metadata"
fi
echo "$prompt"
}
# Ask the LLM if a filename already describes the file content well.
# Returns 0 if the name needs renaming (LLM says NO), 1 if it's already good (YES).
# Also outputs the check conversation JSON (messages array) for use as context in turn 2.
check_filename() {
local file="$1" mode="$2" basename="$3" metadata="${4:-}"
local check_prompt
check_prompt=$(build_check_prompt "$basename" "$metadata")
local content_file
content_file=$(build_user_content "$file" "$mode" "$check_prompt")
local result
if ! result=$(python3 - "$content_file" "$HAT_MODEL" "$GUARD_BUDGET" "${LLM_BASE_URL}" "${HAT_API_KEY:-}" <<'CHECKEOF'
import json, sys, urllib.request, re, os
with open(sys.argv[1]) as f: user_content = json.load(f)
os.unlink(sys.argv[1])
model = sys.argv[2]
budget = int(sys.argv[3])
base_url, api_key = sys.argv[4], sys.argv[5] if len(sys.argv) > 5 else ""
messages = [{'role': 'user', 'content': user_content}]
payload = {'model': model, 'stream': False, 'temperature': 0.1, 'messages': messages}
if budget > 0:
payload['thinking_budget_tokens'] = budget
payload['max_tokens'] = budget + 10
else:
payload['max_tokens'] = 10
if budget == 0:
payload['thinking_budget_tokens'] = 0
headers = {'Content-Type': 'application/json'}
if api_key:
headers['Authorization'] = f'Bearer {api_key}'
req = urllib.request.Request(f'{base_url}/v1/chat/completions',
data=json.dumps(payload).encode(), headers=headers)
try:
with urllib.request.urlopen(req, timeout=60) as resp:
data = json.loads(resp.read())
except urllib.error.URLError as e:
print(f'error: could not reach LLM at {base_url}: {e.reason}', file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f'error: LLM request failed: {e}', file=sys.stderr)
sys.exit(1)
answer = data['choices'][0]['message']['content']
answer = re.sub(r'<think>.*?</think>', '', answer, flags=re.DOTALL).strip().upper()
# Output: verdict on line 1, then the messages JSON for multi-turn context on line 2
verdict = 'YES' if 'YES' in answer else 'NO'
# Build conversation history for turn 2
messages.append({'role': 'assistant', 'content': verdict})
print(verdict)
print(json.dumps(messages))
CHECKEOF
); then
return 2 # error
fi
local verdict
verdict=$(echo "$result" | head -1)
# Export the conversation context for turn 2
CHECK_MESSAGES=$(echo "$result" | tail -1)
if [[ "$verdict" == "YES" ]]; then
return 1 # name is already good
fi
return 0 # needs renaming
}
# Print a content preview to stderr before processing.
# Text: first 8 lines. Audio: key tags. Image: dimensions + EXIF summary.
show_preview() {
local file="$1" mode="$2"
local fname
fname=$(basename "$file")
echo " ── preview: $fname ──" >&2
if [[ "$mode" == "text" ]]; then
head -8 "$file" 2>/dev/null | sed 's/^/ /' >&2
local lines
lines=$(wc -l < "$file" 2>/dev/null || echo "?")
echo " [${lines} lines total]" >&2
elif [[ "$mode" == "audio" ]]; then
python3 - "$file" <<'PREVIEWEOF' >&2
import sys, subprocess, json
file = sys.argv[1]
try:
result = subprocess.run(
['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', file],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
fmt = json.loads(result.stdout).get('format', {})
tags = {k.lower(): v for k, v in fmt.get('tags', {}).items()}
for key in ('title', 'artist', 'album', 'date', 'genre'):
if tags.get(key):
print(f" {key.capitalize()}: {tags[key]}")
if fmt.get('duration'):
secs = float(fmt['duration'])
print(f" Duration: {int(secs//60)}:{int(secs%60):02d}")
else:
print(f" (ffprobe unavailable)")
except Exception as e:
print(f" (preview error: {e})")
PREVIEWEOF
elif [[ "$mode" == "image" ]]; then
python3 - "$file" <<'PREVIEWEOF' >&2
import sys
file = sys.argv[1]
try:
from PIL import Image
with Image.open(file) as img:
print(f" Size: {img.width}x{img.height} Mode: {img.mode}")
exif = img.getexif()
if exif:
from PIL.ExifTags import TAGS
shown = 0
for tid, val in exif.items():
tag = TAGS.get(tid, tid)
if tag in ('Make', 'Model', 'DateTime', 'Software') and isinstance(val, str):
print(f" {tag}: {val}")
shown += 1
if shown >= 3:
break
except ImportError:
import subprocess
result = subprocess.run(['file', '--brief', '--mime-type', file],
capture_output=True, text=True)
print(f" {result.stdout.strip()}")
except Exception as e:
print(f" (preview error: {e})")
PREVIEWEOF
fi
echo "" >&2
}
# Collect file metadata as JSON
collect_metadata() {
local file="$1" mode="$2"
python3 -c "
import sys, os, datetime, json, mimetypes
file, mode = sys.argv[1], sys.argv[2]
meta = {}
stat = os.stat(file)
meta['size_bytes'] = stat.st_size
meta['modified'] = datetime.datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M')
mime, _ = mimetypes.guess_type(file)
if mime:
meta['mime_type'] = mime
if mode == 'image':
try:
from PIL import Image
from PIL.ExifTags import TAGS
exif = Image.open(file).getexif()
if exif:
ed = {}
for tid, val in exif.items():
tag = TAGS.get(tid, tid)
if isinstance(val, (str, int, float)):
ed[str(tag)] = str(val)[:100]
if ed: meta['exif'] = ed
except Exception:
pass
elif mode == 'audio':
import subprocess
try:
result = subprocess.run(
['ffprobe', '-v', 'quiet', '-print_format', 'json',
'-show_format', '-show_streams', file],
capture_output=True, text=True, timeout=10
)
if result.returncode == 0:
probe = json.loads(result.stdout)
fmt = probe.get('format', {})
tags = fmt.get('tags', {})
# Normalise tag keys to lowercase
tags = {k.lower(): v for k, v in tags.items()}
for key in ('title', 'artist', 'album', 'album_artist', 'date', 'genre', 'track', 'comment'):
if tags.get(key):
meta[key] = tags[key][:100]
if fmt.get('duration'):
secs = float(fmt['duration'])
meta['duration'] = f'{int(secs//60)}:{int(secs%60):02d}'
if fmt.get('bit_rate'):
meta['bitrate_kbps'] = str(int(fmt['bit_rate']) // 1000)
# Codec from first audio stream
for stream in probe.get('streams', []):
if stream.get('codec_type') == 'audio':
if stream.get('codec_name'):
meta['codec'] = stream['codec_name']
if stream.get('sample_rate'):
meta['sample_rate_hz'] = stream['sample_rate']
break
except Exception:
pass
elif mode == 'video':
import subprocess
try:
result = subprocess.run(
['ffprobe', '-v', 'quiet', '-print_format', 'json',
'-show_format', '-show_streams', file],
capture_output=True, text=True, timeout=10
)
if result.returncode == 0:
probe = json.loads(result.stdout)
fmt = probe.get('format', {})
tags = {k.lower(): v for k, v in fmt.get('tags', {}).items()}
for key in ('title', 'comment', 'date', 'artist', 'album'):
if tags.get(key):
meta[key] = tags[key][:100]
if fmt.get('duration'):
secs = float(fmt['duration'])
meta['duration'] = f'{int(secs//60)}:{int(secs%60):02d}'
if fmt.get('bit_rate'):
meta['bitrate_kbps'] = str(int(fmt['bit_rate']) // 1000)
for stream in probe.get('streams', []):
if stream.get('codec_type') == 'video':
if stream.get('codec_name'):
meta['video_codec'] = stream['codec_name']
if stream.get('width') and stream.get('height'):
meta['resolution'] = str(stream['width']) + 'x' + str(stream['height'])
if stream.get('avg_frame_rate'):
fr = stream['avg_frame_rate']
if '/' in fr:
n, d = fr.split('/')
if int(d) > 0:
meta['fps'] = str(round(int(n) / int(d), 2))
break
except Exception:
pass
print(json.dumps(meta, ensure_ascii=False))
" "$file" "$mode"
}
# Build the JSON payload for the API call, output to stdout
# If CHECK_MESSAGES is set, uses it as conversation history (multi-turn from check_filename)
build_payload() {
local file="$1" mode="$2" preserve_ext="$3" metadata="${4:-}"
local ext="${file##*.}"
local prior_messages="${CHECK_MESSAGES:-}"
local ext_instruction
if [[ "$preserve_ext" == "true" && -n "$ext" && "$ext" != "$file" ]]; then
ext_instruction="Do NOT include any file extension in your response. Reply with ONLY the name stem."
else
ext_instruction="Choose an appropriate extension."
fi
local prompt="Suggest a single appropriate filename. Rules:
- Use lowercase with hyphens (kebab-case), no spaces
- Be descriptive but concise (2-5 words)
- $ext_instruction
- Reply with ONLY the filename, nothing else"
if [[ -n "$CONTEXT" ]]; then
prompt="$prompt
- Additional context: $CONTEXT"
fi
if [[ -n "$metadata" && "$metadata" != "{}" ]]; then
prompt="$prompt
File metadata: $metadata"
fi
if [[ -n "$prior_messages" ]]; then
# Multi-turn: file content is already in turn 1, just append naming instruction
python3 - "$prompt" "$HAT_MODEL" "$REASONING_BUDGET" "$prior_messages" <<'BUILDEOF'
import json, sys
prompt, model = sys.argv[1], sys.argv[2]
budget, prior_json = int(sys.argv[3]), sys.argv[4]
messages = json.loads(prior_json)
messages.append({'role': 'user', 'content': prompt})
payload = {'model': model, 'stream': True, 'temperature': 0.3, 'messages': messages}
if budget >= 0:
payload['thinking_budget_tokens'] = budget
print(json.dumps(payload))
BUILDEOF
else
local content_file
content_file=$(build_user_content "$file" "$mode" "$prompt")
python3 - "$content_file" "$HAT_MODEL" "$REASONING_BUDGET" <<'BUILDEOF'
import json, sys, os
with open(sys.argv[1]) as f: user_content = json.load(f)
os.unlink(sys.argv[1])
model, budget = sys.argv[2], int(sys.argv[3])
if isinstance(user_content, str) and not user_content.strip():
print('{}'); sys.exit(0)
messages = [{'role': 'user', 'content': user_content}]
payload = {'model': model, 'stream': True, 'temperature': 0.3, 'messages': messages}
if budget >= 0:
payload['thinking_budget_tokens'] = budget
print(json.dumps(payload))
BUILDEOF
fi
}
# Sanitize raw LLM answer into a valid filename stem
# Usage: sanitize_name RAW_ANSWER PRESERVE_EXT ORIGINAL_EXT
sanitize_name() {
python3 - "$1" "$2" "$3" <<'SANITIZE'
import re, sys
answer, preserve_ext, orig_ext = sys.argv[1], sys.argv[2], sys.argv[3]
answer = re.sub(r"<think>.*?</think>", "", answer, flags=re.DOTALL).strip()
lines = [l.strip().strip('`"\'') for l in answer.split("\n") if l.strip()]
name = lines[-1] if lines else ""
name = name.split("/")[-1]
name = re.sub(r"[^a-zA-Z0-9._-]", "-", name)
name = re.sub(r"-+", "-", name).strip("-")
if preserve_ext == "true" and orig_ext:
if "." in name:
name = name.rsplit(".", 1)[0]
name = name.strip("-.")
# An empty stem means the model gave nothing usable (e.g. a reasoning model
# that spent its budget inside <think> and emitted no answer). Emit no name
# so the caller's empty-guard rejects it, instead of renaming the file to a
# stem-less dotfile like ".jpg".
name = name + "." + orig_ext if name else ""
print(name)
SANITIZE
}
# Stream the LLM response with sorting hat animation on stderr, print raw answer on stdout.
# When do_check is "true", runs two-turn flow: guard clause (streamed) → verdict → naming (streamed).
# Outputs: "SKIP" on stdout if name is already good, otherwise the raw LLM answer for naming.
stream_with_hat() {
local file="$1" mode="$2" preserve_ext="$3" metadata="${4:-}"
local do_check="$5" # "true" to run guard clause first
local fname orig_ext=""
fname=$(basename "$file")
if [[ "$preserve_ext" == "true" && "$fname" == *.* ]]; then
orig_ext="${fname##*.}"
fi
# Pre-build payload files in bash so Python just streams them
local check_tmpjson="" naming_tmpjson
if [[ "$do_check" == "true" ]]; then
local check_prompt
check_prompt=$(build_check_prompt "$fname" "$metadata")
check_tmpjson=$(mktemp)
local check_content_file
check_content_file=$(build_user_content "$file" "$mode" "$check_prompt")
python3 - "$check_content_file" "$HAT_MODEL" "$GUARD_BUDGET" > "$check_tmpjson" <<'CHECKBUILD'
import json, sys, os
with open(sys.argv[1]) as f: user_content = json.load(f)
os.unlink(sys.argv[1])
model, budget = sys.argv[2], int(sys.argv[3])
messages = [{'role': 'user', 'content': user_content}]
payload = {'model': model, 'stream': True, 'temperature': 0.1, 'messages': messages}
if budget > 0:
payload['thinking_budget_tokens'] = budget
payload['max_tokens'] = budget + 10 # thinking + short YES/NO answer
else:
payload['max_tokens'] = 10
if budget == 0:
payload['thinking_budget_tokens'] = 0
print(json.dumps(payload))
CHECKBUILD
fi
# Always build the naming payload (without prior messages — Python will inject them if needed)
naming_tmpjson=$(mktemp)
CHECK_MESSAGES=""
build_payload "$file" "$mode" "$preserve_ext" "$metadata" > "$naming_tmpjson"
local raw_output
if ! raw_output=$(python3 - "$LLM_BASE_URL" "$fname" "$do_check" "$check_tmpjson" "$naming_tmpjson" "${HAT_API_KEY:-}" <<'PYEOF'
import sys, json, re, urllib.request, textwrap, time, os
url = sys.argv[1]
filename = sys.argv[2]
do_check = sys.argv[3] == "true"
check_file = sys.argv[4] if sys.argv[4] else ""
naming_file = sys.argv[5]
api_key = sys.argv[6] if len(sys.argv) > 6 else ""
BUBBLE_W = 44
HAT_BODY = [
r" /\ ",
r" / '. ",
r" / .-' ",
]
HAT_THINK_FACES = [
[r" | o o | ", r" / ~~~~ \ "],
[r" | - o | ", r" / ~~~~ \ "],
[r" | o - | ", r" / ---- \ "],
[r" | o o | ", r" / ---- \ "],
]
HAT_HAPPY_FACE = [r" | ^ ^ | ", r" / \vv/ \ "]
HAT_SATISFIED_FACE = [r" | - - | ", r" / \vv/ \ "]
HAT_BRIM = r" __/````````\__ "
DIM, BOLD, RESET = "\033[2m", "\033[1m", "\033[0m"
YELLOW, GREEN, CYAN = "\033[33m", "\033[32m", "\033[36m"
tty = os.open("/dev/tty", os.O_WRONLY) if os.path.exists("/dev/tty") else None
def write_tty(s):
if tty is not None:
os.write(tty, s.encode())
else:
sys.stderr.write(s); sys.stderr.flush()
def wrap_text(text, width):
if not text: return [""]
lines = []
for p in text.split('\n'):
if not p.strip(): lines.append(""); continue
lines.extend(textwrap.wrap(p, width=width, break_long_words=True, break_on_hyphens=True) or [""])
return lines
def render_bubble(lines, width, tail=False):
out = [" \u250c" + "\u2500" * (width + 2) + "\u2510"]
for line in lines:
out.append(" \u2502 " + line.ljust(width) + " \u2502")
if tail:
out += [" \u2514\u2500\u2500\u2500" + "\u2500" * (width - 1) + "\u2518", " \\", " \\", " |"]
else:
out.append(" \u2514" + "\u2500" * (width + 2) + "\u2518")
return out
def hat_think(fi):
return HAT_BODY + HAT_THINK_FACES[fi % len(HAT_THINK_FACES)] + [HAT_BRIM]
def hat_happy():
return HAT_BODY + HAT_HAPPY_FACE + [HAT_BRIM]
def hat_satisfied():
return HAT_BODY + HAT_SATISFIED_FACE + [HAT_BRIM]
def render_thinking(text, fi, fname):
all_lines = wrap_text(text, BUBBLE_W)
visible = all_lines[-3:] if len(all_lines) > 3 else all_lines
while len(visible) < 2: visible.insert(0, "")
out = render_bubble(visible, BUBBLE_W, tail=True)
out += [f" {YELLOW}{l}{RESET}" for l in hat_think(fi)]
out.append(f" {DIM}{fname}{RESET}")
return out
def render_verdict(text, color, hat_fn, fname):
pad = BUBBLE_W - len(text)
bubble = render_bubble(["X"], BUBBLE_W, tail=True)
bubble[1] = f" \u2502 {BOLD}{color}{text}{RESET}" + " " * max(0, pad) + " \u2502"
out = bubble + [f" {YELLOW}{l}{RESET}" for l in hat_fn()]
out.append(f" {DIM}{fname}{RESET}")
return out
def clear_and_draw(lines, prev):
if prev > 0:
write_tty(f"\033[{prev}A\033[J")
for l in lines: write_tty(l + "\n")
return len(lines)
def stream_request(payload_bytes, headers):
"""Stream an LLM request with realtime animation. Returns (thinking, answer)."""
global prev_count, frame_idx
req = urllib.request.Request(f"{url}/v1/chat/completions", data=payload_bytes, headers=headers)
thinking_buf, answer_buf, in_think, last_render = "", "", False, 0
with urllib.request.urlopen(req, timeout=300) as resp:
buf = ""
while True:
chunk = resp.read(1)
if not chunk: break
buf += chunk.decode("utf-8", errors="replace")
while "\n" in buf:
line, buf = buf.split("\n", 1)
line = line.strip()
if not line.startswith("data: "): continue
data_str = line[6:]
if data_str == "[DONE]": break
try: evt = json.loads(data_str)
except json.JSONDecodeError: continue
delta = evt.get("choices", [{}])[0].get("delta", {})
token, reasoning = delta.get("content", ""), delta.get("reasoning_content", "")
if reasoning:
thinking_buf += reasoning
elif token:
answer_buf += token
combined = answer_buf
if "<think>" in combined and "</think>" not in combined:
in_think = True
thinking_buf += combined.split("<think>", 1)[1]
answer_buf = ""; continue
elif in_think:
if "</think>" in combined:
thinking_buf += combined.split("</think>", 1)[0]
answer_buf = combined.split("</think>", 1)[1]
in_think = False
else:
thinking_buf += token; answer_buf = ""
continue
now = time.time()
if now - last_render > 0.1:
display = thinking_buf[-BUBBLE_W * 3:] if thinking_buf else "Hmm..."
display = display.replace("\n\n", "\n").strip()
frame_idx += 1
prev_count = clear_and_draw(render_thinking(display, frame_idx, filename), prev_count)
last_render = now
# If stream ended while still inside <think> tags, the answer never arrived
if in_think:
answer_buf = ""
return thinking_buf, answer_buf
# === Setup ===
HAT_H = len(HAT_BODY) + 2 + 1
drop_frames = []
full = hat_think(0)
for offset in range(4, 0, -1):
frame = [" "] * offset + full + [" "] * (4 - offset)
drop_frames.append(frame)
headers = {"Content-Type": "application/json"}
if api_key: headers["Authorization"] = f"Bearer {api_key}"
# === Drop animation ===
write_tty("\033[?25l")
total_h = 17
write_tty("\n" * total_h + f"\033[{total_h}A")
prev_count, frame_idx = 0, 0
for drop_frame in drop_frames:
frame = [f" {YELLOW}{l}{RESET}" for l in drop_frame]
while len(frame) < HAT_H + 4: frame.append("")
frame.append(f" {DIM}{filename}{RESET}")
prev_count = clear_and_draw(frame, prev_count)
time.sleep(0.12)
time.sleep(0.2)
prev_count = clear_and_draw(render_thinking("Hmm, interesting...", 0, filename), prev_count)
try:
# === Turn 1: Guard clause (streamed, realtime) ===
if do_check and check_file:
with open(check_file) as f: check_payload = json.loads(f.read())
os.unlink(check_file)
check_messages = check_payload['messages']
thinking_buf, answer_buf = stream_request(json.dumps(check_payload).encode(), headers)
# Verdict from content only (reasoning is for thinking, not the answer)
# Strip complete <think> tags, and also incomplete ones (model ran out of tokens mid-think)
answer = re.sub(r'<think>.*?</think>', '', answer_buf, flags=re.DOTALL)
answer = re.sub(r'<think>.*', '', answer, flags=re.DOTALL)
answer = answer.strip().upper()
verdict = 'YES' if 'YES' in answer else 'NO'
if verdict == 'YES':
prev_count = clear_and_draw(
render_verdict("This name looks good already!", GREEN, hat_satisfied, filename), prev_count)
write_tty(f"\033[?25h")
if tty: os.close(tty)
print("SKIP")
sys.exit(0)
else:
prev_count = clear_and_draw(
render_verdict("This name could be better...", CYAN, lambda: hat_think(frame_idx), filename), prev_count)
time.sleep(1.5)
# Build multi-turn context: inject check messages into naming payload
check_messages.append({'role': 'assistant', 'content': 'NO'})
with open(naming_file) as f: naming_payload = json.loads(f.read())
# The naming prompt is the text from the naming payload's first user message
naming_prompt = naming_payload['messages'][0]['content']
if isinstance(naming_prompt, list):
# Image mode: extract text part
naming_prompt = [p for p in naming_prompt if p.get('type') == 'text'][0]['text']
naming_payload['messages'] = check_messages + [{'role': 'user', 'content': naming_prompt}]
with open(naming_file, 'w') as f: json.dump(naming_payload, f)
prev_count = clear_and_draw(
render_thinking("Let me think of a better name...", frame_idx, filename), prev_count)
# === Turn 2 (or only turn): Naming (streamed, realtime) ===
with open(naming_file) as f: naming_data = f.read().encode()
os.unlink(naming_file)
thinking_buf, answer_buf = stream_request(naming_data, headers)
# Output prev_count on line 1 (for reveal to clear), raw answer on line 2
write_tty(f"\033[?25h")
if tty: os.close(tty)
print(prev_count)
print(answer_buf)
except urllib.error.URLError as e:
write_tty(f"\033[?25h\n error: could not reach LLM at {url}: {e.reason}\n")
if tty: os.close(tty)
sys.exit(1)
except Exception as e:
write_tty(f"\033[?25h\n error: LLM request failed: {e}\n")
if tty: os.close(tty)
sys.exit(1)
PYEOF
); then
rm -f "$check_tmpjson" "$naming_tmpjson" 2>/dev/null
return 1
fi
rm -f "$check_tmpjson" "$naming_tmpjson" 2>/dev/null
# Handle SKIP verdict from guard clause
if [[ "$raw_output" == "SKIP" ]]; then
echo "SKIP"
return 0
fi
# Parse prev_count (line 1) and raw answer (line 2+)
local anim_prev_count raw_answer
anim_prev_count=$(echo "$raw_output" | head -1)
raw_answer=$(echo "$raw_output" | tail -n +2)
local name
name=$(sanitize_name "$raw_answer" "$preserve_ext" "$orig_ext")
# Re-render the result with the final name (on tty), clearing previous animation
if [[ -n "$name" ]] && [[ -t 2 ]]; then
python3 - "$name" "$fname" "$anim_prev_count" <<'REVEAL'
import sys, os
name, fname = sys.argv[1], sys.argv[2]
prev = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3].isdigit() else 0
BOLD, GREEN, YELLOW, RESET, DIM = '\033[1m', '\033[32m', '\033[33m', '\033[0m', '\033[2m'
BUBBLE_W = 44
tty = os.open('/dev/tty', os.O_WRONLY) if os.path.exists('/dev/tty') else None
def w(s):
if tty: os.write(tty, s.encode())
else: sys.stderr.write(s); sys.stderr.flush()
# Clear previous animation frames
if prev > 0:
w(f'\033[{prev}A\033[J')
hat = [r" /\ ", r" / '. ", r" / .-' ",
r" | ^ ^ | ", r" / \vv/ \ ", r" __/````````\__ "]
label = 'I suggest: '
suggestion = label + name
pad = BUBBLE_W - len(suggestion)
w(' \u250c' + '\u2500'*(BUBBLE_W+2) + '\u2510\n')
w(' \u2502 ' + f'{DIM}{label}{RESET}{BOLD}{GREEN}{name}{RESET}' + ' '*max(0,pad) + ' \u2502\n')
w(' \u2514\u2500\u2500\u2500' + '\u2500'*(BUBBLE_W-1) + '\u2518\n')
w(' \\\n \\\n |\n')
for l in hat: w(f' {YELLOW}{l}{RESET}\n')
w(f' {DIM}{fname}{RESET}\n\n')
if tty: os.close(tty)
REVEAL
fi
echo "$name"
}
# Non-animated fallback
suggest_quiet() {
local file="$1" mode="$2" preserve_ext="$3" metadata="${4:-}"
local orig_ext=""
if [[ "$preserve_ext" == "true" && "$file" == *.* ]]; then
orig_ext="${file##*.}"
fi
local payload
payload=$(build_payload "$file" "$mode" "$preserve_ext" "$metadata")
local payload_file
payload_file=$(mktemp)
printf '%s\n' "$payload" > "$payload_file"
local raw_answer
if ! raw_answer=$(python3 - "$payload_file" "${LLM_BASE_URL}" "${HAT_API_KEY:-}" <<'QUIETEOF'
import json, sys, urllib.request, os
with open(sys.argv[1]) as f: p = json.load(f)
os.unlink(sys.argv[1])
base_url = sys.argv[2]
api_key = sys.argv[3] if len(sys.argv) > 3 else ""
p['stream'] = False
payload = json.dumps(p).encode()
headers = {'Content-Type': 'application/json'}
if api_key:
headers['Authorization'] = f'Bearer {api_key}'
req = urllib.request.Request(
f'{base_url}/v1/chat/completions',
data=payload,
headers=headers)
try:
with urllib.request.urlopen(req, timeout=300) as resp:
data = json.loads(resp.read())
except urllib.error.URLError as e:
print(f'error: could not reach LLM at {base_url}: {e.reason}', file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f'error: LLM request failed: {e}', file=sys.stderr)
sys.exit(1)
content = data['choices'][0]['message']['content']
print(content)
QUIETEOF
); then
return 1
fi
sanitize_name "$raw_answer" "$preserve_ext" "$orig_ext"
}
process_file() {
local file="$1"
local do_rename="$2"
local preserve_ext="$3"
local force_image="$4"
local quiet="$5"
if [[ ! -f "$file" ]]; then
echo "Not a file: $file" >&2
return 1
fi
local basename
basename=$(basename "$file")
local dir
dir=$(dirname "$file")
local mode="text"
if [[ "$force_image" == "true" ]] || is_image "$file"; then
mode="image"
elif is_audio "$file"; then
mode="audio"
elif is_video "$file"; then
mode="video"
fi
if [[ "$mode" == "text" ]] && is_binary "$file"; then
echo " $basename: binary file, skipping (no analyzable content)" >&2
return 0
fi
# Optional content preview
if [[ "$PREVIEW" == "true" ]]; then
show_preview "$file" "$mode"
fi
# Collect metadata
local metadata=""
if [[ "$INCLUDE_METADATA" == "true" ]]; then
metadata=$(collect_metadata "$file" "$mode" 2>/dev/null) || metadata=""
fi
local suggested
local do_check="false"
[[ "$FORCE" != "true" ]] && do_check="true"
if [[ "$quiet" == "true" ]] || ! [[ -t 2 ]]; then
# Quiet mode: use non-streaming check + naming
CHECK_MESSAGES=""
if [[ "$do_check" == "true" ]]; then
local check_rc=0
check_filename "$file" "$mode" "$basename" "$metadata" || check_rc=$?
if [[ $check_rc -eq 1 ]]; then
echo " $basename: hat says name is already good, skipping (use --force to override)" >&2
return 0
elif [[ $check_rc -eq 2 ]]; then
echo " $basename: LLM check failed" >&2
return 1
fi
echo " $basename: hat says this name could be better, suggesting..." >&2
fi
if ! suggested=$(suggest_quiet "$file" "$mode" "$preserve_ext" "$metadata"); then
echo " $basename: LLM request failed" >&2
return 1
fi
echo " $basename → $suggested" >&2
else
# Animated mode: stream_with_hat handles both check and naming in one animation
if ! suggested=$(stream_with_hat "$file" "$mode" "$preserve_ext" "$metadata" "$do_check"); then
return 1
fi
if [[ "$suggested" == "SKIP" ]]; then
return 0
fi
fi
if [[ -z "$suggested" ]]; then
echo " $basename → (no suggestion)" >&2
return 1
fi