-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.lua
More file actions
269 lines (225 loc) · 8.69 KB
/
main.lua
File metadata and controls
269 lines (225 loc) · 8.69 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
#!/usr/bin/env lua
-- Demel - A CLI music scrobbler with AI assistance
local VERSION = "0.2.0"
-- Add src to package path
local str = debug.getinfo(1, "S").source:sub(2)
local path = str:match("(.*/)") or "./"
package.path = package.path .. ";" .. path .. "src/?.lua"
local os = require "os"
local utils = require "utils"
local config = require "config"
local gemini = require "gemini"
local musicbrainz = require "musicbrainz"
local listenbrainz = require "listenbrainz"
local cache = require "cache"
local stats = require "stats"
local history = require "history"
local batch = require "batch"
-- === CLI ARGUMENTS ===
local function show_help()
print([[
Demel - CLI Music Scrobbler with AI assistance
Usage: demel [OPTIONS]
Options:
-h, --help Show this help message
-v, --version Show version information
--clear-cache Clear the MusicBrainz search cache
--debug Enable debug logging
--stats Show scrobbling statistics
--export [file] Export stats to CSV
--history [n] Show recent search history (default: 10)
--clear-history Clear search history
--import <file> Import scrobbles from CSV or JSON file
--create-import Create example import file
Environment Variables:
DEMEL_LOG_LEVEL Set log verbosity (0=SILENT, 1=ERROR, 2=WARN, 3=INFO, 4=DEBUG)
GEMINI_API_KEY Your Gemini API key
LISTENBRAINZ_TOKEN Your ListenBrainz user token
Examples:
demel Start interactive mode
demel --clear-cache Clear cached search results
DEMEL_LOG_LEVEL=4 demel Run with debug logging
]])
os.exit(0)
end
local function show_version()
print("Demel v" .. VERSION)
print("A CLI music scrobbler with AI-powered intent parsing")
os.exit(0)
end
-- Parse arguments
for i, arg in ipairs(arg) do
if arg == "-h" or arg == "--help" then
show_help()
elseif arg == "-v" or arg == "--version" then
show_version()
elseif arg == "--clear-cache" then
cache.clear()
print("Cache cleared!")
os.exit(0)
elseif arg == "--debug" then
os.setenv("DEMEL_LOG_LEVEL", "4")
elseif arg == "--stats" then
stats.show_stats()
os.exit(0)
elseif arg == "--export" then
local filename = arg[i + 1]
stats.export_csv(filename)
os.exit(0)
elseif arg == "--history" then
local count = tonumber(arg[i + 1]) or 10
history.show_recent(count)
os.exit(0)
elseif arg == "--clear-history" then
history.clear()
os.exit(0)
elseif arg == "--import" then
local filename = arg[i + 1]
if not filename then
print("[ERROR] Please specify a file to import")
os.exit(1)
end
-- Handle import in special mode (needs modules loaded)
_G.BATCH_IMPORT_FILE = filename
elseif arg == "--create-import" then
batch.create_example_csv()
batch.create_example_json()
os.exit(0)
end
end
-- === INITIALIZATION ===
-- Check Env
config.check_env()
print("\n\27[1mWelcome to Demel\27[0m")
print("----------------")
-- Check Connections
if not gemini.check_connection() then os.exit(1) end
if not listenbrainz.check_connection() then os.exit(1) end
-- Handle batch import if requested
if _G.BATCH_IMPORT_FILE then
print("\n\27[1mBatch Import Mode\27[0m")
print("----------------")
local entries = batch.import_file(_G.BATCH_IMPORT_FILE)
if not entries or #entries == 0 then
print("[ERROR] No valid entries found in file")
os.exit(1)
end
print(string.format("[INFO] Found %d entries to import", #entries))
print("[INFO] This will scrobble them to ListenBrainz")
io.write("Continue? (y/N) > ")
local confirm = io.read()
if confirm ~= "y" and confirm ~= "Y" then
print("Cancelled.")
os.exit(0)
end
local success_count = 0
local fail_count = 0
for i, entry in ipairs(entries) do
local artist = entry.artist
local title = entry.title
local album = entry.album or "Unknown Album"
local timestamp = entry.timestamp or os.time()
io.write(string.format("[%d/%d] %s - %s... ", i, #entries, artist, title))
local ok = listenbrainz.submit_listen(artist, title, album, timestamp)
if ok then
stats.record_scrobble(artist, title, album, timestamp)
history.add_entry("batch import", artist, title, album)
print("✓")
success_count = success_count + 1
-- Rate limit: wait 1 second between scrobbles
os.execute("sleep 1")
else
print("✗")
fail_count = fail_count + 1
end
end
print(string.format("\n[INFO] Import complete: %d success, %d failed", success_count, fail_count))
os.exit(0)
end
print("\n\27[32mSystem Ready.\27[0m Type 'exit' or 'quit' to leave.")
-- === HELPERS ===
local function get_start_time()
print("Time? (HH:MM [24h], 'now', or Enter for now)")
io.write("> ")
local time_str = io.read()
if time_str == "" or time_str == "now" then
return os.time()
end
local hour, min = time_str:match("(%d+):(%d+)")
if hour and min then
local date = os.date("*t")
date.hour = tonumber(hour)
date.min = tonumber(min)
date.sec = 0
return os.time(date)
else
utils.print_err("Invalid format. Using 'now'.")
return os.time()
end
end
-- === MAIN LOOP ===
while true do
io.write("\n\27[1mDemel > \27[0m")
local user_input = io.read()
if not user_input or user_input == "exit" or user_input == "quit" then
print("Bye!")
break
end
if user_input ~= "" then
-- Step 1: Gemini Processing
local intent = gemini.parse_intent(user_input)
if intent.type == "chat" then
print("\n\27[36m[AI]\27[0m " .. intent.message)
else
-- Interactive Fallback for Missing Artist
if intent.artist == "Unknown Artist" then
print("\n\27[33m[?]\27[0m I couldn't identify the artist for '" .. intent.title .. "'.")
io.write("Who is the artist? > ")
local manual_artist = io.read()
if manual_artist and manual_artist ~= "" then
-- Use Gemini to resolve the artist name from the user's input
intent.artist = gemini.resolve_artist(manual_artist, intent.title)
-- Rebuild search query since we have new info
intent.search_query = intent.artist .. " " .. intent.title
end
end
local detected_msg = "Detected: " .. intent.type:upper() .. " | " .. intent.artist .. " - " .. intent.title
if intent.album then
detected_msg = detected_msg .. " (Album: " .. intent.album .. ")"
end
utils.print_gemini(detected_msg)
-- Step 2: MusicBrainz Search
local results = musicbrainz.search(intent)
if results then
local selected = musicbrainz.select_result(results, intent)
-- Step 3: Action
if intent.type == "album" then
print("\n" .. intent.title .. " is an entire album.")
local start_time = get_start_time()
utils.print_info("Fetching tracklist...")
local tracks = musicbrainz.get_album_tracks(selected.id)
local current_ts = start_time
for _, track in ipairs(tracks) do
listenbrainz.submit_listen(track.artist, track.title, selected.title, current_ts)
stats.record_scrobble(track.artist, track.title, selected.title, current_ts)
-- Add duration (ms to seconds) for next track's timestamp
current_ts = current_ts + (track.duration / 1000)
end
utils.print_success("Full album scrobbled!")
-- Record album in history
history.add_entry(user_input, intent.artist, intent.title, selected.title)
else
-- Single Track
local start_time = get_start_time()
local artist = selected["artist-credit"][1].name
local title = selected.title
local album = selected.releases[1].title
listenbrainz.submit_listen(artist, title, album, start_time)
stats.record_scrobble(artist, title, album, start_time)
-- Record in history
history.add_entry(user_input, artist, title, album)
end
end
end
end
end