Compare commits

7 Commits
6 changed files with 259 additions and 142 deletions
+35 -3
View File
@@ -19,19 +19,22 @@ Opens `similarities.json`, reverses the sort order, and saves it as
### `refresh_sources.lua`
Creates/Maintains a store of chunked data with embeddings based on configurable
sources. Example:
`sources.json`. Example:
```json
{
"source name":{
"embedding_model":"qwen3-embedding:0.6b",
"filters":{
"blacklist":[".git"],
"extension_whitelist":["md"]
},
"initialize_command":"git clone REMOTE .",
"max_chunk_size":32768,
"path":"will be created before initialize_command is run",
"strip_frontmatter":true,
"refresh_command":"git reset --hard origin/main"
"target_chunk_size":3072,
"refresh_command":"git fetch origin && git reset --hard origin/main"
}
}
```
@@ -41,6 +44,9 @@ The filters are based on `utility.tree`'s filter options (optional).
while `refresh_command` is run each time (optional).
Commands will be run in the specified `path`.
`strip_frontmatter` will remove YAML frontmatter (common in Markdown files).
`embedding_model` and `max_chunk_size` are self-explanatory (optional).
`target_chunk_size` (optional) allows for finer-grained chunks to be generated
alongside the maximum overviews for more precise retrieval.
The embeddings are stored like so:
@@ -55,7 +61,11 @@ The embeddings are stored like so:
}
```
TODO
SHA2 512-bit sums are used to link a text chunk with its embedding. All file
names reference a list of text chunks so they can handle being too large. Every
file that is too large for a single chunk has a whole-file embedding calculated
first (it is the first element of the array), so that if a whole file becomes
relevant, it can still show up instead of only chunks.
### `synopsis_generator.lua`
Chooses a random file within `notebook`, and generates a novel synopsis from it.
@@ -64,6 +74,28 @@ Arguments:
- `refresh_file_list`: Refreshes the cached file list to choose from.
- `export_ordered_list_of_prompts`: Makes an epub to review generated synopses.
## JSON config
This repo uses my utility library's config system, using a `config.json` file in
the repo root that is excluded from commits.
```json
{
"models":{
"embedding":{
"model":"qwen3-embedding:0.6b",
"max_chunk_size":32768
},
"initialized_sources":{}
}
}
```
`refresh_sources.lua` uses `models` to store default embedding model information
and `initialized_sources` to store which sources have been initialized.
## Tasks
- [ ] The whitelisting/blacklisting of tree should be in list too.
- [ ] synopsis_generator should be able to blacklist files it already tried?
- [ ] `refresh_sources.lua` doesn't check for defined files that don't exist
anymore, does it?
- [ ] I think it checks for every other possibility, but this needs checking.
+59 -52
View File
@@ -1,11 +1,8 @@
local stored_messages = {}
local display_levels = {}
local enable_logging = true
local message_limit = math.huge
-- USAGE:
-- -- set arbitrary log levels to be printed immediately
-- log{ info = true, warning = true, ducksauce = true, }
-- -- disable storage of messages depending on log level
-- log{ error = false, verbose = false, }
-- -- send anything (except nil) to a log level
-- log("bacom", true, "text", 5, function() end, {})
-- -- print all messages saved at a particular log level
@@ -14,62 +11,72 @@ local message_limit = math.huge
-- log(false) -- this deletes all stored messages
-- -- set a maximum number of stored messages per log level
-- log(50) -- warning: reaching large limits makes logging expensive
-- -- check if a log level is being displayed
-- if log.arbitrary_exit then log("arbitrary_exit") os.exit(1) end
-- -- do anything to the stored messages (this example deletes them all)
-- log(function(messages) return {} end)
return function(options, ...)
local options_type = type(options)
local microlog = {} -- display_levels are stored directly here
local stored_messages = {}
local enable_logging = true
local message_limit = math.huge
if (options_type == "string") and enable_logging then
if not stored_messages[options] then stored_messages[options] = {} end
local message_table = stored_messages[options]
return setmetatable(microlog, {
__call = function(self, options, ...)
local options_type = type(options)
-- turn log message into text
local tab = {...}
for i = 1, #tab do
tab[i] = tostring(tab[i])
end
local current_message = table.concat(tab, "\t")
if (options_type == "string") and enable_logging then
if microlog[options] == false then return end
if not stored_messages[options] then stored_messages[options] = {} end
local message_table = stored_messages[options]
if #current_message == 0 then
-- print all stored_messages of specified level
for i = 1, #message_table do
print(message_table[i])
-- turn log message into text
local tab = {...}
for i = 1, #tab do
tab[i] = tostring(tab[i])
end
local current_message = table.concat(tab, "\t")
if #current_message == 0 then
-- print all stored_messages of specified level
for i = 1, #message_table do
print(message_table[i])
end
else
-- store message (and print if in display_levels)
message_table[#message_table + 1] = current_message
if #message_table > message_limit then table.remove(message_table, 1) end
if microlog[options] then print(current_message) end
end
else
-- store message (and print if in display_levels)
message_table[#message_table + 1] = current_message
if #message_table > message_limit then table.remove(message_table, 1) end
if display_levels[options] then print(current_message) end
end
-- set display_levels
elseif options_type == "table" then
for k,v in pairs(options) do
display_levels[k] = v
end
elseif options_type == "number" then
message_limit = options
for k,v in pairs(stored_messages) do
while #v > message_limit do
table.remove(v, 1)
-- set display_levels
elseif options_type == "table" then
for k,v in pairs(options) do
microlog[k] = v
end
end
-- turn all logging off and delete stored messages; or turn it on
elseif options_type == "boolean" then
if options then
enable_logging = true
else
enable_logging = false
stored_messages = {}
end
elseif options_type == "number" then
message_limit = options
for k,v in pairs(stored_messages) do
while #v > message_limit do
table.remove(v, 1)
end
end
-- arbitrary access :D
elseif options_type == "function" then
local result = options(stored_messages)
if type(result) == "table" then stored_messages = result end
-- turn all logging off and delete stored messages; or turn it on
elseif options_type == "boolean" then
if options then
enable_logging = true
else
enable_logging = false
stored_messages = {}
end
-- arbitrary access :D
elseif options_type == "function" then
local result = options(stored_messages)
if type(result) == "table" then stored_messages = result end
end
end
end
})
+26 -2
View File
@@ -375,10 +375,10 @@ end
local config_path = utility.path .. "config.json"
local config, config_lock
utility.get_config = function(skip_lock)
if not config then
local config_path = utility.path .. "config.json"
if utility.is_file(config_path) then
if not skip_lock then
config_lock = utility.get_lock(config_path)
@@ -396,7 +396,6 @@ end
utility.save_config = function()
if config then
local config_path = utility.path .. "config.json"
if not config_lock then
print("Warning: A config lock file was not established.")
end
@@ -412,6 +411,31 @@ utility.save_config = function()
end
end
utility.get_config_with_defaults = function(defaults)
local config = utility.get_config()
local loop, changes_made
loop = function(config_level, default_level)
for k,v in pairs(default_level) do
if not config_level[k] then
config_level[k] = v
changes_made = true
elseif type(v) == "table" then
loop(config_level[k], v)
end
end
end
loop(config, defaults)
if changes_made then
utility.save_config()
else
utility.release_lock(config_path)
end
return config
end
local data_file_locations = {}
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env luajit
package.path = (arg[0]:match("@?(.*/)") or arg[0]:match("@?(.*\\)")) .. "lib" .. package.config:sub(1, 1) .. "?.lua;" .. package.path
local utility = require "utility"
local json = utility.require("dkjson")
local search_path = arg[1]
local file_extensions = {}
utility.tree(search_path, function(file_path)
local _, _, extension = utility.split_path_components(file_path)
if extension then
file_extensions[extension] = true
end
end)
for extension in pairs(file_extensions) do
print(extension)
end
+68 -37
View File
@@ -8,24 +8,21 @@ local log = utility.require("log")
local text_processing = utility.require("text_processing")
local timing = utility.require("timing")
-- TODO make utility have a function for getting/setting defaults where locking is only used to set defaults if they aren't present
-- TODO there should be a check function for a lock so a warning/error can be dumped?
local config = utility.get_config("no-lock")
if not config.models then
config.models = {
local config = utility.get_config_with_defaults{
models = {
embedding = {
model = "qwen3-embedding:0.6b",
max_chunk_size = 32768,
},
initialized_sources = {},
}
utility.save_config()
end
},
}
log{
info = true,
warning = true,
-- debug = true,
debug = false,
-- files = true, -- debugging why the wrong files are selected
-- sha = true, -- what the fuck is going on with sha sums?
}
@@ -34,7 +31,6 @@ local memory_path = "PRIVATE_DATA" .. utility.path_separator .. "memory"
local embeddings_file_path = memory_path .. utility.path_separator .. "+embeddings.json"
local tmp_file_path = "PRIVATE_DATA" .. utility.path_separator .. ".tmp.2b65c19b-0883-49ca-8247-b1fe7760f922"
local embeddings
if not utility.path_exists(embeddings_file_path) then
os.execute("mkdir -p " .. memory_path:enquote())
utility.save_data({
@@ -42,8 +38,8 @@ if not utility.path_exists(embeddings_file_path) then
vectors = {},
}, embeddings_file_path)
end
embeddings = utility.load_data(embeddings_file_path)
local function embeddings_debug()
local embeddings = utility.load_data(embeddings_file_path)
if log.debug then
log("debug", "Embeddings loaded.", embeddings, embeddings.files, embeddings.vectors)
local file_count = 0
for k,v in pairs(embeddings.files) do
@@ -57,12 +53,11 @@ local function embeddings_debug()
log("debug", vector_count .. " vectors.")
-- os.exit(1)
end
embeddings_debug()
local refresh_file_list = function(source_name, data_source)
timing.mark("Assembling file list for " .. source_name .. ".")
timing.mark("Assembling file list for \"" .. source_name .. "\"")
local full_path = "PRIVATE_DATA" .. utility.path_separator .. data_source.path
if data_source.initialize_command and (not config.models.initialized_sources[data_source.path]) then
@@ -88,34 +83,26 @@ local refresh_file_list = function(source_name, data_source)
file_list[#file_list + 1] = file_name
end)
timing.mark("Finished assembling file list for " .. source_name .. ".")
timing.mark("Finished assembling file list for \"" .. source_name .. "\"")
return file_list
end
-- returns nothing when too much text is sent
local generate_embeddings = function(text)
if #text > config.models.embedding.max_chunk_size then
local generate_embeddings = function(data_source, text)
local max_chunk_size = data_source.max_chunk_size or config.models.embedding.max_chunk_size
local model = data_source.embedding_model or config.models.embedding.model
if #text > max_chunk_size then
return nil, "generate_embeddings() must only be passed appropriately-sized chunks!"
end
local result = utility.llm_prompt(text, config.models.embedding.model)
local result = utility.llm_prompt(text, model)
return json.decode(result)
end
-- returns nothing for empty files and errors
local process_file = function(data_source, file_name)
local text = utility.read_file(file_name)
local make_chunks = function(text, chunk_size)
assert(chunk_size, "make_chunks() requires chunk_size")
if data_source.strip_frontmatter then
text = text_processing.strip_frontmatter(text)
end
if #text == 0 then
log("empty", file_name .. "\n is empty and being skipped.")
return
end
local chunk_size = config.models.embedding.max_chunk_size
local half_chunk_size = math.floor(chunk_size / 2)
local chunks = { text }
@@ -133,16 +120,44 @@ local process_file = function(data_source, file_name)
end
end
return chunks
end
-- returns nothing for empty files and errors
local process_file = function(data_source, file_name)
local text = utility.read_file(file_name)
if data_source.strip_frontmatter then
text = text_processing.strip_frontmatter(text)
end
if #text == 0 then
log("empty", file_name .. "\n is empty and being skipped.")
return
end
local chunk_size = data_source.max_chunk_size or config.models.embedding.max_chunk_size
local chunks = make_chunks(text, chunk_size)
if data_source.target_chunk_size then
local extra_chunks = make_chunks(text, data_source.target_chunk_size)
for i = 2, #extra_chunks do
chunks[#chunks + 1] = extra_chunks[i]
end
end
local new_embeddings = {}
for i = 1, #chunks do
log("debug", "Embedding length:", #chunks[i])
new_embeddings[i] = generate_embeddings(chunks[i]) or {}
log("debug", "Embedding source length:", #chunks[i])
new_embeddings[i] = generate_embeddings(data_source, chunks[i]) or {}
end
if #new_embeddings[1] == 0 then
log("debug", "Vector lengths:")
for e = 1, #new_embeddings do
log("debug", "", e, #new_embeddings[e])
if log.debug then
log("debug", "Vector lengths:")
for e = 1, #new_embeddings do
log("debug", "", e, #new_embeddings[e])
end
end
if #new_embeddings == 1 then
-- Ollama very rarely errors with:
@@ -198,6 +213,15 @@ local memorize_file = function(data_source, file_name)
return file_sums
end
local delete_memories = function(sha512sum_list)
-- if true then return end -- TEMP disabling removal to compare and verify function
for i = 1, #sha512sum_list do
local sha512sum = sha512sum_list[i]
embeddings.vectors[sha512sum] = nil
os.execute("rm " .. (memory_path .. utility.path_separator .. sha512sum):enquote())
end
end
local refresh_sources = function()
os.execute("mkdir -p " .. memory_path:enquote())
@@ -226,16 +250,23 @@ local refresh_sources = function()
local function loop()
local sha512sum = utility.sha512sum(file_name)
log("sha", file_name, sha512sum, "\n Sum present? " .. tostring(embeddings.vectors[sha512sum]))
if embeddings.vectors[sha512sum] then
log("debug", file_name .. "\n has already been embedded, skipping.")
-- add file reference if it was missing
-- add file reference if it was missing (also handles recognition of duplicate files)
if not embeddings.files[file_name] then
embeddings.files[file_name] = { sha512sum }
end
return
end
log("debug", "Generating embeddings for " .. file_name .. ".")
if embeddings.files[file_name] then
log("debug", file_name .. "\n Removing old embeddings for modified file.")
delete_memories(embeddings.files[file_name])
embeddings.files[file_name] = nil
end
log("debug", file_name .. "\n Generating embeddings..")
local file_sums = memorize_file(data_source, file_name)
embeddings.files[file_name] = file_sums
end
+52 -48
View File
@@ -7,49 +7,49 @@ local json = utility.require("dkjson")
local prompts = utility.require("prompts")
local text_processing = utility.require("text_processing")
local model = "gemma4:12b-mlx"
local minimum_bytes = 1000
local maximum_bytes = 40000
local config = utility.get_config_with_defaults{
models = {
synopsis_generator = {
model = "gemma4:12b-mlx",
minimum_bytes = 1000,
maximum_bytes = 40000,
},
},
}
local NOTEBOOK_PATH = "PRIVATE_DATA/notebook"
local blacklist = utility.enumerate{ ".git", ".gitattributes", ".gitignore", ".gitkeep", ".DS_Store", }
local extension_blacklist = utility.enumerate{ "gif", "jpg", "jpeg", "mp4", "pdf", "png", "webp", }
local data_location = "PRIVATE_DATA/synopsis_generator_file_list.json"
local file_list
if utility.path_exists(data_location) then
file_list = utility.load_data(data_location)
else
file_list = {}
end
local memory_path = "PRIVATE_DATA" .. utility.path_separator .. "memory"
local embeddings_file_path = memory_path .. utility.path_separator .. "+embeddings.json"
local data_path = "PRIVATE_DATA" .. utility.path_separator .. "synopses"
local data_location = data_path .. utility.path_separator .. "+file_list.json"
local refresh_file_list = function()
os.execute("cd " .. NOTEBOOK_PATH:enquot() .. " && git pull origin")
assert(utility.path_exists(embeddings_file_path), "Run \"./refresh_sources.lua\" to set up memory.")
local embeddings = utility.load_data(embeddings_file_path)
local new_files_list = {}
utility.tree(NOTEBOOK_PATH, {
blacklist = blacklist,
extension_blacklist = extension_blacklist,
}, function(file_name)
local minimum_bytes = config.models.synopsis_generator.minimum_bytes
local maximum_bytes = config.models.synopsis_generator.maximum_bytes
local file_list = {}
for file_name, sha512sum_list in pairs(embeddings.files) do
local file_size = utility.file_size(file_name)
if file_size >= minimum_bytes and file_size <= maximum_bytes then
local text = text_processing.strip_frontmatter(utility.read_file(file_name))
if #text >= minimum_bytes and #text <= maximum_bytes then
new_files_list[#new_files_list + 1] = file_name
file_list[#file_list + 1] = { file_name = file_name, }
end
end
end)
end
file_list = new_files_list
utility.save_data(new_files_list, data_location)
utility.save_data(file_list, data_location)
return file_list
end
local generate_and_score = function(file_name, text)
print("Writing synopsis...")
local synopsis = utility.llm_prompt(prompts.synopsis_prompt .. text, model)
local synopsis = utility.llm_prompt(prompts.synopsis_prompt .. text, config.models.synopsis_generator.model)
print(synopsis)
print("Scoring synopsis...")
local scoring, thinking = utility.llm_prompt(prompts.scoring_prompt .. synopsis, model)
local scoring, thinking = utility.llm_prompt(prompts.scoring_prompt .. synopsis, config.models.synopsis_generator.model)
print(scoring)
local scoring_decoded = json.decode(scoring) -- likely will not work because it consistently returns Markdown instead of JSON
if not scoring_decoded then
@@ -62,23 +62,22 @@ local generate_and_score = function(file_name, text)
thinking = thinking,
}
utility.save_data(object, "PRIVATE_DATA/synopses/" .. utility.uuid() .. ".json")
utility.save_data(object, data_path .. utility.path_separator .. utility.uuid() .. ".json")
end
local export_ordered_list_of_prompts = function()
local path = "PRIVATE_DATA/synopses"
local items = {}
local item_order = {}
utility.list(path, function(path_name)
local full_path = path .. utility.path_separator .. path_name
if path_name:find("%.json") then
local object = utility.load_data(full_path)
items[path_name] = object
if type(object.scoring) == "table" then
local mean_score, total_score = utility.mean(object.scoring)
item_order[#item_order + 1] = { path_name = path_name, total_score = total_score, mean_score = mean_score, }
end
utility.list(data_path, function(path_name)
local full_path = data_path .. utility.path_separator .. path_name
if full_path == data_location then return end
local object = utility.load_data(full_path)
items[path_name] = object
if type(object.scoring) == "table" then
local mean_score, total_score = utility.mean(object.scoring)
item_order[#item_order + 1] = { path_name = path_name, total_score = total_score, mean_score = mean_score, }
end
end)
@@ -87,7 +86,7 @@ local export_ordered_list_of_prompts = function()
local output = {
"---",
"title: Ordered Synopses (" .. #item_order .. " items)",
"author: [\"" .. model .. "\", \"Tangent\", \"Ollama\"]",
"author: [\"" .. config.models.synopsis_generator.model .. "\", \"Tangent\", \"Ollama\"]",
"publisher: \"synopsis_generator.lua\"",
"---",
"",
@@ -99,8 +98,11 @@ local export_ordered_list_of_prompts = function()
local tab = text:split("\n")
for index, line in ipairs(tab) do
if line:sub(1, 1) == "#" then
tab[index] = "#" .. tab[index]
-- ensure no output heading is an H1; make H6 bold text lines instead
if line:sub(1, 7) == "###### " then
tab[index] = "**" .. line:sub(8) .. "**"
elseif line:sub(1, 1) == "#" then
tab[index] = "#" .. line
end
end
@@ -114,25 +116,27 @@ end
os.execute("mkdir -p PRIVATE_DATA/synopses")
os.execute("mkdir -p " .. data_path:enquote())
local file_list
if utility.path_exists(data_location) then
file_list = utility.load_data(data_location)
end
if arg[1] == "refresh_file_list" then
print("Refresing file list...")
refresh_file_list()
file_list = refresh_file_list()
os.exit(0)
elseif arg[1] == "export_ordered_list_of_prompts" then
export_ordered_list_of_prompts()
os.exit(0)
end
print(#file_list .. " files to select from.")
if #file_list == 0 then
print("Run \"./synopsis_generator.lua refresh_file_list\" first.")
os.exit(1)
end
assert(file_list and (#file_list > 0), "Run \"./synopsis_generator.lua refresh_file_list\" first.")
print(#file_list .. " files to select from.")
while true do
local file_name = file_list[math.random(1, #file_list)]
local file_name = file_list[math.random(1, #file_list)].file_name
local text = utility.read_file(file_name)
print(file_name .. " chosen.")
generate_and_score(file_name, text)