-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgemini_script_script2readme_1.sh
More file actions
executable file
·2150 lines (1878 loc) · 101 KB
/
gemini_script_script2readme_1.sh
File metadata and controls
executable file
·2150 lines (1878 loc) · 101 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
#!/bin/zsh
#
# script2readme.sh - Generate high-quality README documentation from scripts using Ollama models
# Author: Ian Trimble
# Created: April 28, 2025
# Version: 1.3.0 (Fixed)
#
# Enable debug mode only when explicitly requested
if [[ "$1" == "--debug" ]]; then
set -x # Print commands and their arguments as they are executed.
DEBUG_MODE=true # Set debug flag for log_message
shift # Remove --debug from the arguments list
else
DEBUG_MODE=false
fi
# =================== COLORS AND FORMATTING ===================
# Define terminal colors for enhanced output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
GRAY='\033[0;37m'
BOLD='\033[1m'
DIM='\033[2m'
UNDERLINE='\033[4m'
BLINK='\033[5m'
REVERSE='\033[7m'
RESET='\033[0m' # Reset all formatting
# Define a color gradient for the progress bar
declare -a GRADIENT
GRADIENT=(
'\033[38;5;27m' '\033[38;5;33m' '\033[38;5;39m' '\033[38;5;45m' '\033[38;5;51m'
'\033[38;5;50m' '\033[38;5;49m' '\033[38;5;48m' '\033[38;5;47m' '\033[38;5;46m'
)
# Check if the terminal supports colors; disable if not
if [ -t 1 ]; then
COLORTERM=1 # Colors enabled
else
COLORTERM=0 # Colors disabled
# Reset all color variables to empty strings if colors are not supported
RED='' GREEN='' YELLOW='' BLUE='' MAGENTA='' CYAN='' WHITE='' GRAY=''
BOLD='' DIM='' UNDERLINE='' BLINK='' REVERSE='' RESET=''
for i in {0..9}; do GRADIENT[$i]=''; done # Reset gradient colors
fi
# =================== HELPER FUNCTIONS ===================
# NOTE: All function definitions are placed here, before they are called.
# Function to log messages with different levels (INFO, SUCCESS, WARNING, ERROR, DEBUG)
log_message() {
local level=$1 # Message level (e.g., INFO)
local message=$2 # The message text
local timestamp=$(date '+%Y-%m-%d %H:%M:%S') # Current timestamp
# Print message with appropriate color and icon based on level
case ${level} in
"INFO")
echo -e "${BLUE}[${timestamp}] ℹ️ ${RESET}${message}"
;;
"SUCCESS")
echo -e "${GREEN}[${timestamp}] ✅ ${BOLD}${message}${RESET}"
;;
"WARNING")
echo -e "${YELLOW}[${timestamp}] ⚠️ ${BOLD}${message}${RESET}"
;;
"ERROR")
echo -e "${RED}[${timestamp}] ❌ ${BOLD}${message}${RESET}"
;;
"DEBUG")
# Only print debug messages if debug mode is enabled
if [[ "${DEBUG_MODE}" == "true" ]]; then
echo -e "${GRAY}[${timestamp}] 🔍 ${message}${RESET}"
fi
;;
*) # Default case for unknown levels
echo -e "[${timestamp}] ${message}"
;;
esac
}
# Function to display the application logo (ASCII art)
show_logo() {
# Only show logo if in an interactive terminal
if ! is_terminal; then return 0; fi
clear # Clear the terminal screen
echo -e "${BLUE}╔══════════════════════════════════════════════════════╗${RESET}"
echo -e "${BLUE}║ ║${RESET}"
echo -e "${BLUE}║ ${MAGENTA}███████╗${GREEN}██████╗${CYAN} ██████╗${YELLOW}███████╗${RED}██████╗ ${MAGENTA}███████╗${BLUE} ║${RESET}"
echo -e "${BLUE}║ ${MAGENTA}██╔════╝${GREEN}██╔══██╗${CYAN}██╔════╝${YELLOW}██╔════╝${RED}██╔══██╗${MAGENTA}██╔════╝${BLUE} ║${RESET}"
echo -e "${BLUE}║ ${MAGENTA}███████╗${GREEN}██████╔╝${CYAN}██║ ${YELLOW}█████╗ ${RED}██████╔╝${MAGENTA}█████╗ ${BLUE} ║${RESET}"
echo -e "${BLUE}║ ${MAGENTA}╚════██║${GREEN}██╔══██╗${CYAN}██║ ${YELLOW}██╔══╝ ${RED}██╔══██╗${MAGENTA}██╔══╝ ${BLUE} ║${RESET}"
echo -e "${BLUE}║ ${MAGENTA}███████║${GREEN}██║ ██║${CYAN}╚██████╗${YELLOW}███████╗${RED}██║ ██║${MAGENTA}███████╗${BLUE} ║${RESET}"
echo -e "${BLUE}║ ${MAGENTA}╚══════╝${GREEN}╚═╝ ╚═╝${CYAN} ╚═════╝${YELLOW}╚══════╝${RED}╚═╝ ╚═╝${MAGENTA}╚══════╝${BLUE} ║${RESET}"
echo -e "${BLUE}║ ║${RESET}"
echo -e "${BLUE}║ ${CYAN}Script to README Generator ${WHITE}v${APP_VERSION} ${BLUE} ║${RESET}"
echo -e "${BLUE}║ ${GRAY}By ${APP_AUTHOR} ${BLUE} ║${RESET}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════╝${RESET}"
echo ""
}
# Function to display a random "Did you know?" tip
show_tip() {
# Ensure TIPS array is populated before accessing (defined later in CONFIGURATION)
if [ ${#TIPS[@]} -gt 0 ]; then
local tip_index=$((RANDOM % ${#TIPS[@]})) # Select a random index
local tip="${TIPS[$tip_index]}" # Get the tip
# Only show tip if in an interactive terminal
if is_terminal; then
echo -e "\n${YELLOW}💡 ${BOLD}Did you know?${RESET} ${tip}${RESET}\n"
fi
fi
}
# Function to play sounds if sound is enabled in config
play_sound() {
local sound_type=$1 # Type of sound ('complete' or 'error')
# Check if sound is enabled (use default 0 if SOUND_ENABLED is not set)
if [ ${SOUND_ENABLED:-0} -eq 1 ]; then
# Check if afplay exists (macOS specific)
if command -v afplay &> /dev/null; then
# Use default sound paths if variables are empty
local complete_sound="${SOUND_COMPLETE:-/System/Library/Sounds/Glass.aiff}"
local error_sound="${SOUND_ERROR:-/System/Library/Sounds/Sosumi.aiff}"
case ${sound_type} in
"complete")
# Play completion sound in the background, suppressing output
afplay "${complete_sound}" &> /dev/null &
;;
"error")
# Play error sound in the background, suppressing output
afplay "${error_sound}" &> /dev/null &
;;
esac
else
log_message "DEBUG" "afplay command not found, cannot play sound."
fi
fi
}
# Function to display an animated spinner while a background process runs
spinner() {
local pid=$1 # Process ID of the background task
# Check if we are in an interactive terminal before showing spinner
if ! is_terminal; then return 0; fi
local delay=0.1 # Delay between frames
local spinstr='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏' # Spinner characters
# Loop while the process is still running
while kill -0 $pid 2>/dev/null; do
local temp=${spinstr#?} # Rotate the spinner string
printf " %c " "$spinstr" # Print the current spinner character
local spinstr=$temp${spinstr%"$temp"}
sleep $delay # Wait for the next frame
printf "\b\b\b\b" # Move cursor back to overwrite
done
printf " \b\b\b\b" # Clear the spinner area
}
# Function to display a progress bar with gradient colors
display_progress() {
# Check if we are in an interactive terminal before showing progress
if ! is_terminal; then return 0; fi
local progress=$1 # Current progress percentage (0-100)
local duration=$2 # Elapsed time string
local width=40 # Width of the progress bar in characters
# Ensure progress is within 0-100
if [ $progress -lt 0 ]; then progress=0; fi
if [ $progress -gt 100 ]; then progress=100; fi
local filled=$((width * progress / 100)) # Number of filled characters
local empty=$((width - filled)) # Number of empty characters
local bar="" # Initialize the bar string
# Create the filled part of the bar with gradient colors
for ((i = 0; i < filled; i++)); do
local color_index=$((i * ${#GRADIENT[@]} / width)) # Calculate color index based on position
# Handle potential index out of bounds
if [ $color_index -ge ${#GRADIENT[@]} ]; then color_index=$((${#GRADIENT[@]} - 1)); fi
bar="${bar}${GRADIENT[$color_index]}█" # Append colored block
done
# Create the empty part of the bar
for ((i = 0; i < empty; i++)); do
bar="${bar}${GRAY}░" # Append gray block
done
# Print the complete progress bar with percentage and duration
# \r moves the cursor to the beginning of the line for overwriting
printf "\r${WHITE}[${RESET}${bar}${RESET}${WHITE}]${RESET} ${BOLD}%3d%%${RESET} ${WHITE}(${CYAN}%s${WHITE})${RESET}" $progress "$duration"
}
# Function to format time in seconds into a human-readable string (e.g., "1m 30s")
format_time() {
local seconds_float=$1 # Total seconds (can be float)
# Ensure input is numeric, default to 0
if ! [[ "$seconds_float" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then seconds_float=0; fi
local seconds_int=$(printf "%.0f" "$seconds_float") # Round to nearest integer
# Use integer arithmetic for calculation
local minutes=$((seconds_int / 60))
local remaining_seconds=$((seconds_int % 60))
# Format output based on whether minutes are present
if [ $minutes -gt 0 ]; then
echo "${minutes}m ${remaining_seconds}s"
else
echo "${seconds_int}s"
fi
}
# Function to calculate a complexity score for a script based on features
calculate_complexity() {
local content="$1" # Script content
local line_count="$2" # Number of lines in the script
# Ensure line_count is a number, default to 0 if not
if ! [[ "$line_count" =~ ^[0-9]+$ ]]; then line_count=0; fi
# Count various script features using grep
# Use || echo "0" to handle cases where grep finds nothing
local function_count=$(echo "${content}" | grep -c "function " || echo "0")
local if_count=$(echo "${content}" | grep -E '(^|[^a-zA-Z0-9_])if\s+' || echo "0") # Avoid matching words like 'diff'
local case_count=$(echo "${content}" | grep -c "case " || echo "0")
local for_count=$(echo "${content}" | grep -E '(^|[^a-zA-Z0-9_])for\s+' || echo "0")
local while_count=$(echo "${content}" | grep -E '(^|[^a-zA-Z0-9_])while\s+' || echo "0")
# Calculate complexity score using weighted factors and bc for floating point math
# Ensure factors are defined, use defaults if not
local lc_factor=${LINE_FACTOR:-0.3}
local fn_factor=${FUNCTION_FACTOR:-2.0}
local cond_factor=${CONDITIONAL_FACTOR:-1.5}
local loop_factor=${LOOP_FACTOR:-1.2}
# Use bc for calculation, handle potential errors
local complexity=$(echo "scale=2; (${line_count} * ${lc_factor}) + (${function_count} * ${fn_factor}) + ((${if_count} + ${case_count}) * ${cond_factor}) + ((${for_count} + ${while_count}) * ${loop_factor})" | bc 2>/dev/null || echo "1.0")
# Ensure a minimum complexity score of 1.0
if (( $(echo "$complexity < 1.0" | bc -l) )); then
complexity=1.0
fi
# Return the calculated complexity score
echo $complexity
}
# Function to estimate the completion time for generating documentation
estimate_completion_time() {
local script_size=$1 # Size of the script in bytes
local script_complexity=$2 # Calculated complexity score
local model=$3 # Ollama model being used
# Ensure inputs are numeric, provide defaults
if ! [[ "$script_size" =~ ^[0-9]+$ ]]; then script_size=1000; fi
if ! [[ "$script_complexity" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then script_complexity=1.0; fi
# Get the complexity factor for the selected model
local model_factor=${MODEL_COMPLEXITY[$model]}
if [ -z "$model_factor" ]; then
model_factor=${MODEL_COMPLEXITY["default"]:-2.5} # Use default if model not found
fi
# Base time in seconds per KB, adjusted for complexity
local base_time=2
# Adjust based on script size (larger scripts may take disproportionately longer)
# Use bc for floating point exponentiation (approximated with ^0.6)
local size_kb=$(echo "scale=4; $script_size / 1024" | bc)
if (( $(echo "$size_kb <= 0" | bc -l) )); then size_kb=0.1; fi # Avoid log(0)
# Check if bc supports 'l' (natural log) function
local size_factor="1" # Default size factor
if echo "l(1)" | bc -l >/dev/null 2>&1; then
size_factor=$(echo "scale=4; e(0.6 * l($size_kb))" | bc -l 2>/dev/null || echo "1") # Use natural log and exp for power
else
log_message "DEBUG" "bc does not support 'l'. Using simplified size factor."
# Simplified factor if log not available
size_factor=$(echo "scale=2; 1 + $size_kb / 10" | bc)
fi
if (( $(echo "$size_factor < 1" | bc -l) )); then size_factor=1; fi # Ensure factor is at least 1
# Calculate estimated seconds, factoring in script size, model, and script complexity
local complexity_adjustment=$(printf "%.2f" $(echo "scale=2; $script_complexity * 0.8" | bc))
local estimate=$(printf "%.0f" $(echo "scale=0; $base_time * $size_factor * $model_factor * $complexity_adjustment" | bc))
# Ensure a minimum reasonable estimate (e.g., 10 seconds)
if [ $estimate -lt 10 ]; then
estimate=10
fi
echo $estimate # Return estimated time in seconds
}
# Function to display detailed description and stats for a specific model
show_model_description() {
local model=$1 # Model name
local description=""
# Get the model's description from the associative array
if [ -n "${MODEL_DESCRIPTIONS[$model]}" ]; then
description="${MODEL_DESCRIPTIONS[$model]}"
else
description="${MODEL_DESCRIPTIONS["default"]:-'No description available.'}" # Use default if not found
fi
# Get the model's complexity factor
local complexity=${MODEL_COMPLEXITY[$model]}
if [ -z "$complexity" ]; then
complexity=${MODEL_COMPLEXITY["default"]:-2.5}
fi
# Determine speed category based on complexity factor
local speed=""
local speed_color=""
if (( $(echo "$complexity < 1.5" | bc -l) )); then speed="Very Fast"; speed_color="${GREEN}";
elif (( $(echo "$complexity < 2.5" | bc -l) )); then speed="Fast"; speed_color="${CYAN}";
elif (( $(echo "$complexity < 4.0" | bc -l) )); then speed="Medium"; speed_color="${YELLOW}";
else speed="Slow"; speed_color="${RED}"; fi
# Print model details
echo -e "${MAGENTA}${BOLD}${model}${RESET}"
echo -e "${GRAY}${description}${RESET}"
echo -e "${GRAY}• Speed: ${speed_color}${speed}${RESET}"
echo -e "${GRAY}• Performance factor: ${WHITE}${complexity}x${RESET}"
# Display average run time from benchmark log if available
if [ -f "${BENCHMARK_LOG}" ]; then
# Use awk to calculate average time for 'total_analysis' operations for this model
local avg_time=$(awk -F',' -v model="$model" '$7 == model && $8 == "total_analysis" {sum+=$9; count++} END {if(count>0) print sum/count; else print "N/A"}' "${BENCHMARK_LOG}")
local runs=$(awk -F',' -v model="$model" '$7 == model && $8 == "total_analysis" {count++} END {print count+0}' "${BENCHMARK_LOG}") # Count runs
if [[ "$avg_time" != "N/A" && $runs -gt 0 ]]; then
echo -e "${GRAY}• Average run time: ${WHITE}$(printf "%.2f" ${avg_time})s${RESET} (${runs} previous runs)"
fi
fi
echo "" # Add a blank line for spacing
}
# Function to display usage information (help message)
show_usage() {
# Print application header
echo -e "${CYAN}${BOLD}${APP_NAME}${RESET} ${WHITE}(v${APP_VERSION})${RESET}"
echo -e "${GRAY}Generates README documentation from script files using Ollama models${RESET}"
echo ""
# Print usage syntax
echo -e "${YELLOW}${BOLD}Usage:${RESET} $0 ${GREEN}[OPTIONS]${RESET} ${MAGENTA}<input_file>${RESET} ${BLUE}[model]${RESET}"
echo ""
# List available options
echo -e "${YELLOW}${BOLD}Options:${RESET}"
echo -e " ${GREEN}--debug${RESET} Enable debug mode (print commands)"
echo -e " ${GREEN}--help${RESET} Show this help message"
echo -e " ${GREEN}--list-models${RESET} List available Ollama models with descriptions"
echo -e " ${GREEN}--version${RESET} Show version information"
echo -e " ${GREEN}--no-estimate${RESET} Skip time estimation calculation"
echo -e " ${GREEN}--no-color${RESET} Disable colored output"
echo -e " ${GREEN}--sound${RESET} Enable sound notifications (macOS only)"
echo -e " ${GREEN}--batch${RESET} ${BLUE}<pattern>${RESET} Process multiple files matching pattern (e.g., \"*.sh\")"
echo -e " ${GREEN}--watch${RESET} ${BLUE}<directory>${RESET} Watch directory for new/modified scripts and process them"
echo -e " ${GREEN}--process-existing${RESET} Process existing files when starting watch mode"
echo -e " ${GREEN}--template${RESET} ${BLUE}<name>${RESET} Use specified template (basic implementation)"
echo -e " ${GREEN}--interactive${RESET} Edit AI-generated documentation before saving"
echo -e " ${GREEN}--update${RESET} Update existing documentation preserving manual edits (Not Implemented)"
echo -e " ${GREEN}--export${RESET} ${BLUE}<format>${RESET} Export documentation to specified format (html, pdf)"
echo -e " ${GREEN}--format${RESET} ${BLUE}<style>${RESET} README format style (basic, enhanced, fancy)"
echo -e " ${GREEN}--toc${RESET} Add table of contents to README (enhanced/fancy formats)"
echo -e " ${GREEN}--config${RESET} Create or update configuration file interactively"
echo -e " ${GREEN}--stats${RESET} Show benchmark statistics for all runs"
echo -e " ${GREEN}--compare${RESET} ${MAGENTA}<input_file>${RESET} Compare multiple models on the same script"
echo ""
# List arguments
echo -e "${YELLOW}${BOLD}Arguments:${RESET}"
echo -e " ${MAGENTA}<input_file>${RESET} Path to script file to document (required unless using --watch, --batch, --stats, --compare)"
echo -e " ${BLUE}[model]${RESET} Optional Ollama model name (default: ${WHITE}${DEFAULT_MODEL:-default}${RESET})" # Show default
echo ""
# Provide examples
echo -e "${YELLOW}${BOLD}Examples:${RESET}"
echo -e " ${GRAY}$0 my_script.sh${RESET}"
echo -e " ${GRAY}$0 my_script.sh codellama:7b${RESET}"
echo -e " ${GRAY}$0 --batch \"*.py\" --template code${RESET}"
echo -e " ${GRAY}$0 --watch ~/scripts --process-existing${RESET}"
echo -e " ${GRAY}$0 my_script.sh --format fancy --toc${RESET}"
echo -e " ${GRAY}$0 --compare my_script.sh${RESET}"
echo -e " ${GRAY}$0 --stats${RESET}"
echo ""
# Describe output
echo -e "${YELLOW}${BOLD}Output:${RESET}"
echo -e " - Updates README.md in the current directory with script documentation"
echo -e " - Logs performance metrics and benchmarks to ${BENCHMARK_DIR:-$HOME/ollama_benchmarks}" # Show default
echo ""
# Show a random tip
show_tip
exit 0 # Exit after showing help
}
# Function to display version information
show_version() {
echo -e "${CYAN}${BOLD}${APP_NAME}${RESET} ${WHITE}v${APP_VERSION}${RESET}"
echo -e "${GRAY}Author: ${WHITE}${APP_AUTHOR}${RESET}"
echo -e "${GRAY}Created: April 28, 2025${RESET}"
echo -e "${GRAY}License: MIT${RESET}"
exit 0 # Exit after showing version
}
# Function to display benchmark statistics from the log file
show_benchmark_stats() {
# Check if the benchmark log file exists
if [ ! -f "${BENCHMARK_LOG}" ]; then
log_message "ERROR" "No benchmark data found at ${BENCHMARK_LOG}."
exit 1
fi
echo -e "${CYAN}${BOLD}Benchmark Statistics${RESET}"
echo ""
# --- Model Performance ---
echo -e "${YELLOW}${BOLD}Model Performance${RESET}"
echo -e "${WHITE}|--------------------|-----------|------------|----------|${RESET}"
echo -e "${WHITE}| Model | Avg Time | Accuracy % | Runs |${RESET}"
echo -e "${WHITE}|--------------------|-----------|------------|----------|${RESET}"
# Extract unique models from the log (column 7), skipping header and system entries
local models=$(tail -n +2 "${BENCHMARK_LOG}" | awk -F',' '$7 != "system" {print $7}' | sort | uniq)
for model in $models; do
# Calculate stats for each model using awk
local stats=$(awk -F',' -v model="$model" '
$7 == model && $8 == "total_analysis" {
runs++;
sum_time += $9;
if ($14 != "" && $14 != "N/A") { sum_accuracy += $14; accuracy_runs++ } # Ensure accuracy is numeric
}
END {
avg_time = (runs > 0) ? sum_time / runs : "N/A";
avg_accuracy = (accuracy_runs > 0) ? (sum_accuracy / accuracy_runs) * 100 : "N/A";
print avg_time, avg_accuracy, runs+0;
}' "${BENCHMARK_LOG}")
local avg_time=$(echo $stats | cut -d' ' -f1)
local accuracy=$(echo $stats | cut -d' ' -f2)
local runs=$(echo $stats | cut -d' ' -f3)
# Format the output strings for table alignment
local model_display=$(printf "%-18s" "${model}")
local time_display="N/A"
if [[ "$avg_time" != "N/A" ]]; then time_display=$(printf "%.2fs" ${avg_time}); fi
time_display=$(printf "%-9s" "${time_display}")
local accuracy_display="N/A"
if [[ "$accuracy" != "N/A" ]]; then accuracy_display=$(printf "%.1f%%" ${accuracy}); fi
accuracy_display=$(printf "%-10s" "${accuracy_display}")
local runs_display=$(printf "%-8s" "${runs}")
# Print the table row for the model
echo -e "| ${MAGENTA}${model_display}${RESET} | ${CYAN}${time_display}${RESET} | ${GREEN}${accuracy_display}${RESET} | ${YELLOW}${runs_display}${RESET} |"
done
echo -e "${WHITE}|--------------------|-----------|------------|----------|${RESET}"
echo ""
# --- Script Type Statistics ---
echo -e "${YELLOW}${BOLD}Script Types${RESET}"
echo -e "${WHITE}|------------|---------|------------|${RESET}"
echo -e "${WHITE}| Type | Count | Avg Time |${RESET}"
echo -e "${WHITE}|------------|---------|------------|${RESET}"
# Extract script extensions (type) and calculate stats
# Use awk to extract extension from filename (column 3)
local exts=$(tail -n +2 "${BENCHMARK_LOG}" | awk -F',' '
$8 == "total_analysis" {
# Extract extension robustly, handle names with multiple dots
n = split($3, parts, ".");
if (n > 1 && parts[n] ~ /^[a-zA-Z0-9]+$/) {
ext = parts[n];
} else {
ext = "other"; # Handle files with no extension or complex names
}
if (ext != "" && ext != "system" && $3 !~ /^(unknown|system)$/ ) print ext; # Filter out non-file entries
}' | sort | uniq)
for ext in $exts; do
# Calculate stats for each script type using awk
# Match filenames ending with .ext explicitly
local type_stats=$(awk -F',' -v ext="${ext}" '
BEGIN { count=0; sum_time=0; }
$8 == "total_analysis" {
n = split($3, parts, ".");
current_ext = (n > 1 && parts[n] ~ /^[a-zA-Z0-9]+$/) ? parts[n] : "other";
if (current_ext == ext) {
count++;
sum_time += $9;
}
}
END {
avg_time = (count > 0) ? sum_time / count : "N/A";
print count+0, avg_time;
}' "${BENCHMARK_LOG}")
local count=$(echo $type_stats | cut -d' ' -f1)
local avg_time=$(echo $type_stats | cut -d' ' -f2)
# Format for display
local ext_display=$(printf "%-10s" "${ext}")
local count_display=$(printf "%-7s" "${count}")
local time_display="N/A"
if [[ "$avg_time" != "N/A" ]]; then time_display=$(printf "%.2fs" ${avg_time}); fi
time_display=$(printf "%-10s" "${time_display}")
# Print the table row for the script type
echo -e "| ${CYAN}${ext_display}${RESET} | ${YELLOW}${count_display}${RESET} | ${GREEN}${time_display}${RESET} |"
done
echo -e "${WHITE}|------------|---------|------------|${RESET}"
echo ""
# --- Overall Statistics ---
# Calculate overall stats using awk
local overall_stats=$(awk -F',' '
$8 == "total_analysis" {
total_runs++;
sum_total_time += $9;
sum_script_size += $4;
sum_script_lines += $5;
}
END {
avg_total_time = (total_runs > 0) ? sum_total_time / total_runs : "N/A";
avg_script_size = (total_runs > 0) ? sum_script_size / total_runs : "N/A";
avg_script_lines = (total_runs > 0) ? sum_script_lines / total_runs : "N/A";
print total_runs+0, avg_total_time, avg_script_size, avg_script_lines;
}' "${BENCHMARK_LOG}")
local total_runs=$(echo $overall_stats | cut -d' ' -f1)
local avg_total_time=$(echo $overall_stats | cut -d' ' -f2)
local avg_script_size=$(echo $overall_stats | cut -d' ' -f3)
local avg_script_lines=$(echo $overall_stats | cut -d' ' -f4)
# Format times and sizes
local avg_time_display="N/A"
if [[ "$avg_total_time" != "N/A" ]]; then avg_time_display=$(printf "%.2fs" ${avg_total_time}); fi
local avg_size_display="N/A"
if [[ "$avg_script_size" != "N/A" ]]; then avg_size_display=$(printf "%.2f bytes" ${avg_script_size}); fi
local avg_lines_display="N/A"
if [[ "$avg_script_lines" != "N/A" ]]; then avg_lines_display=$(printf "%.1f lines" ${avg_script_lines}); fi
# Print overall statistics
echo -e "${YELLOW}${BOLD}Overall Statistics${RESET}"
echo -e "${GRAY}Total runs: ${WHITE}${total_runs}${RESET}"
echo -e "${GRAY}Average runtime: ${WHITE}${avg_time_display}${RESET}"
echo -e "${GRAY}Average script size: ${WHITE}${avg_size_display}${RESET}"
echo -e "${GRAY}Average script lines: ${WHITE}${avg_lines_display}${RESET}"
echo ""
# --- Benchmark File Locations ---
show_benchmark_location # Call function to display file paths
echo ""
exit 0 # Exit after showing stats
}
# Function to compare outputs of multiple models for a single script
compare_models() {
local input_file=$1 # The script file to compare models on
log_message "INFO" "Comparing models for ${input_file}..."
# Validate the input file existence
if [ ! -f "${input_file}" ]; then
log_message "ERROR" "Input file '${input_file}' does not exist."
exit 1
fi
# Get the list of available Ollama models
get_models
# Ask user which models to compare if running interactively
local models_to_compare=()
if is_terminal; then
echo -e "${YELLOW}${BOLD}Select models to compare (space-separated numbers, e.g., '1 3 5'):${RESET}"
# Display numbered list of available models
for ((i=1; i<=${#models[@]}; i++)); do
echo -e "${WHITE}${i})${RESET} ${MAGENTA}${models[$((i-1))]}${RESET}" # Use 0-based index
done
echo ""
# Read user's selection
read -p "Models to compare: " model_selection
# Convert selected numbers to model names
for num in $model_selection; do
if [[ "$num" =~ ^[0-9]+$ ]] && [ "$num" -ge 1 ] && [ "$num" -le ${#models[@]} ]; then
# Use 0-based index for array access
models_to_compare+=("${models[$((num-1))]}")
fi
done
else
# Non-interactive: use a predefined set of good models for comparison
models_to_compare=("qwen2.5-coder:7b" "deepseek-coder:latest" "codellama:7b")
log_message "INFO" "Non-interactive mode. Comparing default set: ${models_to_compare[*]}"
fi
# If no valid models were selected interactively, use the default set
if [ ${#models_to_compare[@]} -eq 0 ]; then
log_message "WARNING" "No valid models selected. Using default comparison set: qwen2.5-coder:7b, deepseek-coder:latest, codellama:7b"
models_to_compare=("qwen2.5-coder:7b" "deepseek-coder:latest" "codellama:7b")
fi
# Create a dedicated directory for this comparison session
local comparison_dir="${BENCHMARK_DIR}/comparison_${SESSION_ID}_$(basename ${input_file} .${input_file##*.})"
mkdir -p "${comparison_dir}"
log_message "INFO" "Saving comparison results to: ${comparison_dir}"
# Create the main comparison markdown file
local comparison_file="${comparison_dir}/model_comparison_summary.md"
# Initialize the comparison summary file with headers
{
echo "# Model Comparison for $(basename "${input_file}")"
echo ""
echo "Generated on $(date '+%Y-%m-%d %H:%M:%S') by script2readme v${APP_VERSION}"
echo ""
echo "## Script Information"
echo ""
echo "| Property | Value |"
echo "|----------|-------|"
echo "| Filename | $(basename "${input_file}") |"
echo "| Size | $(stat -f%z "${input_file}" 2>/dev/null || stat -c%s "${input_file}" 2>/dev/null || echo "0") bytes |"
echo "| Lines | $(wc -l < "${input_file}" | tr -d ' ') |"
echo ""
echo "## Performance Comparison"
echo ""
echo "| Model | Time (s) | Word Count | Notes | Full Output |"
echo "|-------|----------|------------|-------|-------------|"
} > "${comparison_file}"
# Validate the input file once before looping through models
validate_input_file "${input_file}"
if [ $? -ne 0 ]; then
log_message "ERROR" "Failed to validate input file ${input_file}. Aborting comparison."
exit 1
fi
# Process the script with each selected model
for model_to_test in "${models_to_compare[@]}"; do # Use different variable name
log_message "INFO" "Testing with model: ${model_to_test}"
# Skip if the model doesn't actually exist locally (e.g., typo in selection)
# Use exact match grep
if ! ollama list | grep -q -w "^${model_to_test}"; then
log_message "WARNING" "Model '${model_to_test}' not found locally. Skipping."
# Add a note to the comparison file
echo "| ${model_to_test} | N/A | N/A | Model not found | N/A |" >> "${comparison_file}"
continue
fi
# --- Run the generation process (similar to generate_readme but without writing to main README) ---
local model_start_time=$(date +%s.%N)
# Create request payload (using validated global CONTENT, SCRIPT_TYPE etc.)
# Ensure CONTENT is escaped for JSON
local escaped_content_compare=$(echo "$CONTENT" | jq -Rsa .)
local payload=$(jq -n \
--arg model "${model_to_test}" \
--argjson content "${escaped_content_compare}" \
--arg filename "$(basename "${input_file}")" \
--arg script_type "${SCRIPT_TYPE}" \
'{
"model": $model,
"messages": [
{
"role": "system",
"content": "You are an expert code documentarian tasked with producing professional, accurate, and comprehensive documentation. Analyze the provided script with precision, describing only the functionality explicitly present in the code. Generate a detailed Markdown README section that is clear, thorough, and professionally structured, suitable for developers and end-users."
},
{
"role": "user",
"content": "Analyze the following \($script_type) script provided as plain text. Pay close attention to specific elements such as references to applications, system paths, and command-line tools. Consider the script'\''s potential impact on the system.\n\nGenerate a Markdown README section with these sections:\n\n- **Overview**: Summarize the script'\''s purpose and primary actions.\n- **Requirements**: List prerequisites inferred from the script.\n- **Usage**: Provide precise instructions for running the script.\n- **What the Script Does**: Describe the script'\''s operations step-by-step.\n- **Important Notes**: Highlight critical details derived from the script.\n- **Disclaimer**: Warn about risks of running the script.\n\nFile: \($filename)\n\nScript Content:\n\( $content )"
}
],
"stream": false
}')
# Temporary file for the API response
local temp_response=$(mktemp)
# Send the request to Ollama API
log_message "INFO" "Sending request to Ollama API for ${model_to_test}..."
curl -s -X POST "${OLLAMA_API}" \
-H "Content-Type: application/json" \
-d "${payload}" > "${temp_response}"
local curl_exit_code=$?
if [ $curl_exit_code -ne 0 ]; then
log_message "ERROR" "curl command failed for model ${model_to_test} with exit code ${curl_exit_code}."
echo "| ${model_to_test} | Error | N/A | curl failed | N/A |" >> "${comparison_file}"
rm "${temp_response}"
continue
fi
# Check for errors in the Ollama response
if jq -e '.error' "${temp_response}" > /dev/null 2>&1; then
log_message "ERROR" "Error in Ollama response for ${model_to_test}:"
jq '.' "${temp_response}" # Print error details
echo "| ${model_to_test} | Error | N/A | API Error | N/A |" >> "${comparison_file}"
rm "${temp_response}"
continue
fi
# Extract response content using robust methods
local RESPONSE_COMPARE="" # Use different variable name
if jq -e '.message.content' "${temp_response}" > /dev/null 2>&1; then
RESPONSE_COMPARE=$(jq -r '.message.content' "${temp_response}")
else
# Fallback methods if jq path fails
RESPONSE_COMPARE=$(grep -o '"content":"[^"]*"' "${temp_response}" | sed 's/"content":"//;s/"$//')
if [ -z "${RESPONSE_COMPARE}" ]; then RESPONSE_COMPARE=$(perl -0777 -ne 'print $1 if /"content":\s*"(.*?)(?<!\\)"/s' "${temp_response}"); fi
if [ -z "${RESPONSE_COMPARE}" ]; then RESPONSE_COMPARE=$(cat "${temp_response}" | python3 -c "import json, sys; d=json.load(sys.stdin); print(d.get('message', {}).get('content', ''))" 2>/dev/null); fi
fi
# Check if response content is empty
if [ -z "${RESPONSE_COMPARE}" ]; then
log_message "ERROR" "Empty response content from Ollama for model ${model_to_test}."
echo "Raw response:"
cat "${temp_response}"
echo "| ${model_to_test} | Error | N/A | Empty Response | N/A |" >> "${comparison_file}"
rm "${temp_response}"
continue
fi
# Save the individual model's response to a file
local model_response_file="${comparison_dir}/${model_to_test//[:\/]/_}.md" # Sanitize model name for filename
echo "${RESPONSE_COMPARE}" > "${model_response_file}"
log_message "DEBUG" "Saved response for ${model_to_test} to ${model_response_file}"
# Calculate timing and statistics
local model_end_time=$(date +%s.%N)
local model_duration=$(printf "%.2f" $(echo "${model_end_time} - ${model_start_time}" | bc))
local word_count=$(echo "${RESPONSE_COMPARE}" | wc -w | tr -d ' ')
# Add the results to the comparison summary table
echo "| ${model_to_test} | ${model_duration} | ${word_count} | - | [View Output](./$(basename "${model_response_file}")) |" >> "${comparison_file}"
# Clean up temporary response file
rm "${temp_response}"
done
# --- Finalize the comparison summary file ---
{
echo ""
echo "## Summary"
echo ""
echo "This comparison shows how different models analyze the same script. The quality of documentation can vary significantly between models, with some providing more detailed explanations while others may be more concise or faster."
echo ""
echo "Consider factors like speed, detail level, and accuracy when choosing a model for your needs."
echo ""
echo "## How to View Full Outputs"
echo ""
echo "The individual model outputs are saved in the same directory as this file:"
echo "\`\`\`"
echo "${comparison_dir}"
echo "\`\`\`"
} >> "${comparison_file}"
# --- Output results ---
log_message "SUCCESS" "Model comparison complete!"
log_message "INFO" "Comparison summary saved to: ${comparison_file}"
# Open the comparison summary file automatically if on macOS
if [[ "$OSTYPE" == "darwin"* ]]; then
open "${comparison_file}"
fi
exit 0 # Exit after comparison
}
# Function to interactively update the configuration file
update_config() {
echo -e "${CYAN}${BOLD}Configuration Setup${RESET}"
echo ""
# Ask for the default model
echo -e "${YELLOW}Default model:${RESET} (current: ${WHITE}${DEFAULT_MODEL:-none}${RESET})"
read -r new_model
# Keep current value if user enters nothing
if [ -z "$new_model" ]; then new_model="${DEFAULT_MODEL}"; fi
# Ask for sound preference
local current_sound_pref="N"
if [ ${SOUND_ENABLED:-0} -eq 1 ]; then current_sound_pref="y"; fi
echo -e "${YELLOW}Enable sound effects?${RESET} (y/N) [current: ${current_sound_pref}]"
read -r sound_pref
local sound_enabled_str="false"
if [[ "${sound_pref}" =~ ^[Yy]$ ]]; then sound_enabled_str="true"; fi
# Ask for preferred README format
local current_format="${README_FORMAT:-enhanced}" # Use current or default
echo -e "${YELLOW}Preferred README format:${RESET} (basic, enhanced, fancy) [current: ${current_format}]"
read -r format_pref
if [ -z "$format_pref" ]; then format_pref="${current_format}"; fi
# Validate format choice, default to 'enhanced' if invalid
if [[ ! "${format_pref}" =~ ^(basic|enhanced|fancy)$ ]]; then
log_message "WARNING" "Invalid format '${format_pref}'. Defaulting to 'enhanced'."
format_pref="enhanced"
fi
# Write the updated configuration to the file using jq for proper JSON formatting
jq -n \
--arg model "${new_model}" \
--argjson sound "${sound_enabled_str}" \
--arg format "${format_pref}" \
'{ "default_model": $model, "sound_enabled": $sound, "template": "default", "preferred_format": $format }' > "${CONFIG_FILE}"
log_message "SUCCESS" "Configuration updated in ${CONFIG_FILE}!"
exit 0 # Exit after updating config
}
# Function to get system information (CPU, Memory, OS, Ollama version)
get_system_info() {
# Use sysctl and sw_vers for macOS, provide fallbacks for other systems
local cpu_info=$(sysctl -n machdep.cpu.brand_string 2>/dev/null || uname -p 2>/dev/null || echo "Unknown")
# Get memory size in bytes, then format
local mem_bytes=$(sysctl -n hw.memsize 2>/dev/null || grep MemTotal /proc/meminfo | awk '{print $2 * 1024}' 2>/dev/null || echo 0)
local memory_info="Unknown"
if [ "$mem_bytes" -gt 0 ]; then
memory_info=$(echo "scale=1; $mem_bytes / (1024*1024*1024)" | bc | awk '{printf "%.1f GB", $1}')
fi
local os_info=$(sw_vers -productName 2>/dev/null && sw_vers -productVersion 2>/dev/null || uname -s -r 2>/dev/null || echo "Unknown")
# Use ollama --version for consistency
local ollama_version=$(ollama --version 2>/dev/null || echo "Not Found")
# Add system info to the metrics log for this session
# Ensure METRICS_LOG is defined and writable
if [ -n "${METRICS_LOG}" ] && [ -w "$(dirname "${METRICS_LOG}")" ]; then
jq --arg cpu "${cpu_info}" \
--arg mem "${memory_info}" \
--arg os "${os_info}" \
--arg ollama "${ollama_version}" \
'.system_info = {"cpu": $cpu, "memory": $mem, "os": $os, "ollama_version": $ollama}' "${METRICS_LOG}" > "${METRICS_LOG}.tmp" && mv "${METRICS_LOG}.tmp" "${METRICS_LOG}" \
|| log_message "WARNING" "Failed to write system info to metrics log."
fi
log_message "INFO" "System Info: CPU: ${cpu_info}, Memory: ${memory_info}, OS: ${os_info}, Ollama: ${ollama_version}"
}
# Function to get current resource usage (CPU %, Memory RSS) of the script itself
get_resource_usage() {
# Use ps command to get CPU and Resident Set Size (memory) for the current process ($$)
# Handle potential errors if ps fails
local cpu_usage=$(ps -o %cpu= -p $$ | awk '{print $1}' 2>/dev/null || echo "N/A")
local memory_rss_kb=$(ps -o rss= -p $$ 2>/dev/null || echo "0")
local memory_usage="N/A"
if [[ "$memory_rss_kb" =~ ^[0-9]+$ ]] && [ "$memory_rss_kb" -gt 0 ]; then
memory_usage=$(printf "%.0f MB" $(echo "scale=0; $memory_rss_kb / 1024" | bc)) # Convert KB to MB
fi
echo "${cpu_usage},${memory_usage}" # Return comma-separated values
}
# Function to log benchmark data to CSV and JSON files
log_benchmark() {
local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ") # ISO 8601 timestamp
local script_name=$1
local script_size=$2
local script_lines=$3
local script_chars=$4
local model=$5
local operation=$6 # e.g., 'api_request', 'total_analysis'
local duration=$7 # Duration in seconds
local token_count=$8 # Estimated token count (or word count)
local complexity=$9 # Script complexity score
local accuracy=${10} # Estimation accuracy (if applicable)
# Ensure numeric fields have defaults if empty
script_size=${script_size:-0}
script_lines=${script_lines:-0}
script_chars=${script_chars:-0}
duration=${duration:-0}
token_count=${token_count:-0}
complexity=${complexity:-1.0}
accuracy=${accuracy:-""} # Accuracy can be empty
# Get current resource usage
local resource_usage=$(get_resource_usage)
local cpu_usage=$(echo ${resource_usage} | cut -d, -f1)
local memory_usage=$(echo ${resource_usage} | cut -d, -f2)
# Ensure log files/dirs are writable
if [ -w "${BENCHMARK_LOG}" ] && [ -w "${METRICS_LOG}" ]; then
# Log to CSV file for historical data
echo "${timestamp},${SESSION_ID},${script_name},${script_size},${script_lines},${script_chars},${model},${operation},${duration},${token_count},${cpu_usage},${memory_usage},${complexity},${accuracy}" >> "${BENCHMARK_LOG}"
# Add metric entry to the session's JSON log file
jq --arg timestamp "${timestamp}" \
--arg script "${script_name}" \
--arg size "${script_size}" \
--arg lines "${script_lines}" \
--arg chars "${script_chars}" \
--arg model "${model}" \
--arg op "${operation}" \
--arg dur "${duration}" \
--arg tokens "${token_count}" \
--arg cpu "${cpu_usage}" \
--arg mem "${memory_usage}" \
--arg complexity "${complexity}" \
--arg accuracy "${accuracy}" \
'.metrics += [{"timestamp": $timestamp, "script": $script, "size_bytes": $size, "line_count": $lines, "char_count": $chars, "model": $model, "operation": $op, "duration": $dur, "token_count": $tokens, "cpu_usage": $cpu, "memory_usage": $mem, "complexity": $complexity, "accuracy": $accuracy}]' "${METRICS_LOG}" > "${METRICS_LOG}.tmp" && mv "${METRICS_LOG}.tmp" "${METRICS_LOG}" \
|| log_message "WARNING" "Failed to write to metrics log ${METRICS_LOG}"
else
log_message "WARNING" "Cannot write to benchmark logs (${BENCHMARK_LOG} or ${METRICS_LOG}). Check permissions."
fi
log_message "DEBUG" "Logged benchmark: ${operation} for ${script_name} took ${duration}s"
# Return operation:duration for potential chaining or further use
echo "${operation}:${duration}"
}
# Function to generate a formatted summary box after README generation
generate_benchmark_summary() {
local model=$1
local script_name=$2
local total_time=$3
local api_time=$4
local parse_time=$5
local script_size=$6
local script_lines=$7
local script_chars=$8
local token_count=$9 # Word count from response
local estimated_time=${10}
local complexity=${11}
# Ensure numeric fields have defaults
total_time=${total_time:-0}
api_time=${api_time:-0}
parse_time=${parse_time:-0}
script_size=${script_size:-0}
script_lines=${script_lines:-0}
script_chars=${script_chars:-0}
token_count=${token_count:-0}
estimated_time=${estimated_time:-""}
complexity=${complexity:-1.0}
# Calculate estimation accuracy percentage
local accuracy="N/A"
if [ -n "$estimated_time" ] && [ "$estimated_time" -gt 0 ] && [ "$(echo "$total_time > 0.01" | bc -l)" -eq 1 ]; then # Avoid division by zero/tiny
accuracy=$(printf "%.1f" $(echo "scale=1; (${estimated_time} / ${total_time}) * 100" | bc 2>/dev/null || echo "0"))
# Handle potential bc errors or invalid results
if [[ -z "$accuracy" || "$accuracy" == ".0" || "$accuracy" == "0.0" || ! "$accuracy" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
accuracy="N/A"
else
accuracy="${accuracy}%"
fi
fi
# Print the formatted summary box
echo -e "${BLUE}╔══════════════════════════════════════════════════════╗${RESET}"
echo -e "${BLUE}║ ${CYAN}${BOLD}README GENERATION COMPLETE ${RESET}${BLUE}║${RESET}"
echo -e "${BLUE}╠══════════════════════════════════════════════════════╣${RESET}"
echo -e "${BLUE}║ ${WHITE}📄 Script:${RESET} ${YELLOW}${script_name}${RESET}$(printf "%$((40-${#script_name}))s" "")${BLUE}║${RESET}" # Use printf for padding
echo -e "${BLUE}║ ${WHITE}🤖 Model:${RESET} ${MAGENTA}${model}${RESET}$(printf "%$((41-${#model}))s" "")${BLUE}║${RESET}"
echo -e "${BLUE}║ ${WHITE}⏱️ Total time:${RESET} ${GREEN}${total_time}s${RESET}$(printf "%$((37-${#total_time}))s" "")${BLUE}║${RESET}"
# Display estimated vs actual time if estimation was performed
if [ -n "$estimated_time" ]; then
local est_vs_actual="${estimated_time}s vs ${total_time}s (${accuracy})"
# Adjust padding dynamically based on the length of the string
local padding=$((30 - ${#est_vs_actual}))
if [ $padding -lt 0 ]; then padding=0; fi
echo -e "${BLUE}║ ${WHITE}🔮 Est. vs Actual:${RESET} ${est_vs_actual}$(printf "%${padding}s" "")${BLUE}║${RESET}"
fi
echo -e "${BLUE}║ ${WHITE}🔄 API request time:${RESET} ${CYAN}${api_time}s${RESET}$(printf "%$((31-${#api_time}))s" "")${BLUE}║${RESET}"
echo -e "${BLUE}║ ${WHITE}🔍 Response parse time:${RESET} ${CYAN}${parse_time}s${RESET}$(printf "%$((29-${#parse_time}))s" "")${BLUE}║${RESET}"
echo -e "${BLUE}║ ${WHITE}📝 Response size:${RESET} ~${token_count} words$(printf "%$((33-${#token_count}))s" "")${BLUE}║${RESET}"
echo -e "${BLUE}║ ${WHITE}🧮 Script complexity:${RESET} ${complexity}$(printf "%$((31-${#complexity}))s" "")${BLUE}║${RESET}"
echo -e "${BLUE}║ ${WHITE}📂 Script metrics:${RESET}$(printf "%$((35))s" "")${BLUE}║${RESET}"
# Calculate script size in KB
local kb_size=$(printf "%.2f" $(echo "scale=2; ${script_size}/1024" | bc))
echo -e "${BLUE}║ ${GRAY}- Size: ${script_size} bytes (${kb_size} KB)${RESET}$(printf "%$((38-${#script_size}-${#kb_size}))s" "")${BLUE}║${RESET}"
echo -e "${BLUE}║ ${GRAY}- Lines: ${script_lines}${RESET}$(printf "%$((43-${#script_lines}))s" "")${BLUE}║${RESET}"
echo -e "${BLUE}║ ${GRAY}- Characters: ${script_chars}${RESET}$(printf "%$((37-${#script_chars}))s" "")${BLUE}║${RESET}"
echo -e "${BLUE}╠══════════════════════════════════════════════════════╣${RESET}"
echo -e "${BLUE}║ ${GRAY}📋 Session ID: ${DIM}${SESSION_ID}${RESET}$(printf "%$((38-${#SESSION_ID}))s" "")${BLUE}║${RESET}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════╝${RESET}"
}
# Function to display the locations of benchmark files
show_benchmark_location() {
echo -e "${BLUE}╔══════════════════════════════════════════════════════╗${RESET}"
echo -e "${BLUE}║ ${CYAN}${BOLD}BENCHMARK FILES LOCATION ${RESET}${BLUE}║${RESET}"
echo -e "${BLUE}╠══════════════════════════════════════════════════════╣${RESET}"
# Use printf for padding to align paths