A small Go utility that uses the OpenAI API to infer the correct ordering of page image files in a directory (for example, magazine pages), based on their filenames.
The program:
- Reads all file names from a working directory.
- Asks an OpenAI model to guess the correct order of those files based on page numbers in the names.
- Parses the JSON array of ordered file names returned by the model.
This repository is a minimal example meant to be edited and extended in GoLand.
- Go 1.22+ (or the version specified in
go.mod) - An OpenAI API key with access to the model you configure in
main.go
The program is configured entirely via environment variables:
OPENAI_API_KEY(required): Your OpenAI API key.WORKING_DIR(required): Absolute or relative path to the directory whose files you want to analyze.
In GoLand, you can set these in Run �| Edit Configurations... under Environment variables.
Clone the repository and download Go dependencies:
git clone <your-repo-url> go-rename
cd go-rename
go mod tidyFrom the command line:
export OPENAI_API_KEY="your-api-key-here"
export WORKING_DIR="/path/to/your/files"
go run ./...From GoLand:
- Create or edit a Run/Debug Configuration for
main.go. - Set
OPENAI_API_KEYandWORKING_DIRin Environment variables. - Run the configuration.
The core logic is in main.go:
- Read
OPENAI_API_KEYandWORKING_DIRfrom the environment. - Use
os.ReadDirto list all files inWORKING_DIRand print them. - Build a natural-language prompt enumerating those filenames.
- Call the OpenAI Chat Completions API via the official Go SDK (
github.com/openai/openai-go/v3) with that prompt. - Expect the model to respond with a JSON array (e.g.
["page_01.png", "page_02.png", ...]). - Use
encoding/jsonto unmarshal the JSON string into a[]stringslice (orderedFiles).
You can then extend the program to:
- Actually rename or move files according to
orderedFiles. - Extract additional metadata (e.g., publication month/year) from the cover page.
- Handle errors and edge cases more robustly.
Add your preferred license here (e.g., MIT).