跳到正文
DEV Community· Lipun Kumar Sahoo·· 3 小時前AI 評分41

我用 Gemma 建立檔案整理工具,因為懶得整理下載資料夾

I Built a File Organizer Using Gemma Because I'm Too Lazy to Sort My Downloads

AI 導讀

作者用 Python 和 Gemma(gemma-4-31b-it)製作檔案整理腳本,按檔案名稱分類並移入 Images、Documents 等資料夾。腳本透過 Google API 逐個處理檔案,並以 gemini-2.5-flash 作後備模型,整理約需五分鐘。作者目前使用 API,並指出 Gemma 的開放權重讓工具日後可在本機執行,令檔案名稱不離開電腦。

正文

This is a submission for the Hacktoberfest Open-Source AI Challenge Week 3: Slow and Steady

Hi everyone!

What I Built

I'm a first-year BSc Computer Science student, and my Downloads folder is a mess: screenshots, random PDFs, songs, all in one pile because I never feel like sorting them.

So I built a small Python script that does it for me. It looks at each file in a folder, asks Gemma which category it belongs to (Images, Documents, Videos, Audio, Archives, Code, or Others), creates the folder if needed, and moves the file in. One command, and the pile is sorted.

Demo

Before: 12 files, all in one folder.

Folder with 12 unsorted files

Running the script:

Terminal showing files being moved into category folders

After: every file in its category folder.

Folder after sorting, with seven category folders

Code

import os
import time
import shutil
import google.generativeai as genai

genai.configure(api_key=os.environ["GEMINI_API_KEY"])
MODELS = ["gemma-4-31b-it", "gemini-2.5-flash"]  # main model, then backup

TARGET_FOLDER = r"C:\path\to\your\folder"
CATEGORIES = ["Images", "Documents", "Videos", "Audio", "Archives", "Code", "Others"]

def ask_model(model_name, prompt):
    model = genai.GenerativeModel(model_name)
    for attempt in range(3):
        try:
            return model.generate_content(prompt).text
        except Exception:
            time.sleep(2 * (attempt + 1))  # slow and steady: wait, then retry
    return None

def categorize_file(filename):
    prompt = f"""Classify this filename into exactly one of these categories: {", ".join(CATEGORIES)}.
Filename: {filename}
Reply with ONLY the category name, nothing else."""
    for model_name in MODELS:
        text = ask_model(model_name, prompt)
        if text:
            # Gemma may explain first; the answer is the last line
            lines = [l for l in text.strip().splitlines() if l.strip()]
            reply = lines[-1].strip().strip("*.` ").lower()
            print(f"  {model_name} replied: {reply}")
            for c in CATEGORIES:
                if c.lower() == reply:
                    return c
            return "Others"
    return None  # both models failed

def organize_folder():
    files = [f for f in os.listdir(TARGET_FOLDER)
             if os.path.isfile(os.path.join(TARGET_FOLDER, f))]
    print(f"Found {len(files)} files to organize.\n")

    for filename in files:
        category = categorize_file(filename)
        if category is None:
            print(f"Skipped '{filename}' (could not classify)")
            continue
        category_path = os.path.join(TARGET_FOLDER, category)
        os.makedirs(category_path, exist_ok=True)
        shutil.move(os.path.join(TARGET_FOLDER, filename),
                    os.path.join(category_path, filename))
        print(f"Moved '{filename}' -> {category}/")
        time.sleep(1)

    print("\nDone! Your folder is organized.")

if __name__ == "__main__":
    organize_folder()

How I Built It

  • Language: Python
  • Model: Gemma (gemma-4-31b-it) through Google's API, with gemini-2.5-flash as a backup
  • Flow: read each filename, ask Gemma for one category, create the folder if it doesn't exist, move the file
  • Slow and steady: the script handles one file at a time, waits a second between files, and retries a few times if the API fails, so one error never ruins the whole run.

Two things surprised me along the way. Gemma sometimes explains its reasoning before giving the answer, so I read only the last line of its reply. The API also returned a few temporary server errors, which is why I added the retries and the backup model.

Why Does Open Innovation Matter?

Gemma is an open-weight model, so I could experiment and test again and again (I did, a lot) without worrying about a locked-down tool. It also means the same idea could later run fully on my own computer, so my file names never leave my machine. Right now I use the API, but open weights make that next step possible, which a closed model wouldn't.

The Lazy Payoff

Sorting my Downloads by hand takes a while, so I never did it. Now it's one command, and it finishes in about five minutes while I do something else. It's not instant because it works through one file at a time with a short pause and retries (that's the "slow and steady" part), but that's five minutes I don't spend dragging files around. Anyone with a messy folder can use it, and changing the categories is one line.

What I Learned

This was my first time writing code that talks to an AI model instead of just using a chatbot. A clear, simple prompt matters a lot. At first Gemma gave strange answers until I told it to reply with ONLY the category name, and I still had to handle the cases where it didn't.

Tech used: Python, Google Gemma API

Final Thoughts

This started as a small fix for a messy Downloads folder and ended up teaching me how to work with an AI model: write clear prompts, expect surprises, and handle errors calmly. It's not perfect, but it's mine, and it works.

Thanks for reading! If you have a messy folder of your own, give it a try. I'd love to hear what categories you'd add or how you'd improve it. Let me know in the comments.

Happy Hacktoberfest!

來源:DEV Community · dev.to