<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Lipun Kumar Sahoo</title>
    <description>The latest articles on DEV Community by Lipun Kumar Sahoo (@lipun_kumarsahoo_19a5b59).</description>
    <link>https://dev.to/lipun_kumarsahoo_19a5b59</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4175619%2Fd29cb8f4-20d9-4c96-958f-f44ffdef9e6a.jpg</url>
      <title>DEV Community: Lipun Kumar Sahoo</title>
      <link>https://dev.to/lipun_kumarsahoo_19a5b59</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/lipun_kumarsahoo_19a5b59"/>
    <language>en</language>
    <item>
      <title>I made a game that boosts my learning skills</title>
      <dc:creator>Lipun Kumar Sahoo</dc:creator>
      <pubDate>Sun, 01 Nov 2026 06:41:27 +0000</pubDate>
      <link>https://dev.to/lipun_kumarsahoo_19a5b59/i-made-a-game-that-boosts-my-learning-skills-4o6p</link>
      <guid>https://dev.to/lipun_kumarsahoo_19a5b59/i-made-a-game-that-boosts-my-learning-skills-4o6p</guid>
      <description>&lt;p&gt;&lt;em&gt;This is a submission for the &lt;a href="https://dev.to/challenges/hacktoberfest-week4-2026-10-26"&gt;Hacktoberfest Open-Source AI Challenge Week 4: Ghost in the Machine&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What I Built
&lt;/h2&gt;

&lt;p&gt;Studying from old notes is boring, so I let a ghost haunt them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ghost Tutor&lt;/strong&gt; is a Python game that reads your own study material and quizzes you inside a haunted library. Feed it a PDF, a scanned PDF, photos of a textbook, a Word, Excel or PowerPoint file, a video file, or a YouTube link, and the ghost turns it into exam-style questions wrapped in psychological horror. The dusty notes and forgotten textbooks you never reread come back to haunt you. That's my take on "Ghost in the Machine".&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How it plays:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;You choose the number of levels.&lt;/strong&gt; Short notes give up to 10 levels, and a big book (10+ pages) gives up to 50. Refuse to choose, and the ghost chooses for you. If you type &lt;code&gt;0&lt;/code&gt;, it whispers something creepy and picks a number that matches the content.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Souls and points.&lt;/strong&gt; A wrong answer costs a soul and 5 points. If your points drain to zero, the ghost claims you.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;You can't skip.&lt;/strong&gt; Try, and the ghost blocks you with a different spooky line every time.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Trapdoor questions.&lt;/strong&gt; Some questions end in "All of the above" or "None of the above", and that last option is always the right one.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Every option has its own reason.&lt;/strong&gt; Whatever you pick, the game explains in plain facts why it is right or wrong.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Two moods.&lt;/strong&gt; The text alternates between &lt;em&gt;Gothic &amp;amp; Eerie&lt;/em&gt; (candles, fog, locked library doors) and &lt;em&gt;Dark &amp;amp; Ominous&lt;/em&gt; (trapdoors, executioners, the price of cowardice).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Demo
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4rdku24hiqk4km4j4fpa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4rdku24hiqk4km4j4fpa.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F6ny8mn6jmgr72zxwl8bl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F6ny8mn6jmgr72zxwl8bl.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0hpsavv9qgtpkmtzutoc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0hpsavv9qgtpkmtzutoc.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqzini8p6bcpbgyupv79p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqzini8p6bcpbgyupv79p.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fb4e2pese9gy3qszh4wvb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fb4e2pese9gy3qszh4wvb.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqf63xpo4ewqcyv6z5u7s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqf63xpo4ewqcyv6z5u7s.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Code
&lt;/h2&gt;

&lt;p&gt;import os&lt;br&gt;
import re&lt;br&gt;
import sys&lt;br&gt;
import json&lt;br&gt;
import time&lt;br&gt;
import random&lt;br&gt;
import google.generativeai as genai&lt;br&gt;
from concurrent.futures import ThreadPoolExecutor&lt;/p&gt;

&lt;h1&gt;
  
  
  Paste your API key between the quotes. Keep this file private: never post it or share it with the key inside.
&lt;/h1&gt;

&lt;p&gt;API_KEY = "PASTE_YOUR_NEW_API_KEY_HERE"&lt;br&gt;
if API_KEY.startswith("PASTE_YOUR"):  # not pasted? try the PowerShell variable instead&lt;br&gt;
    API_KEY = os.environ.get("GEMINI_API_KEY", "")&lt;br&gt;
if not API_KEY:&lt;br&gt;
    sys.exit("No API key found. Paste it into the API_KEY line near the top of ghost_game.py.")&lt;br&gt;
genai.configure(api_key=API_KEY)&lt;br&gt;
MODELS = ["gemma-4-31b-it", "gemini-2.5-flash"]  # text: main model, then backup&lt;br&gt;
MEDIA_MODEL = "gemini-2.5-flash"                  # photos, scans and videos&lt;br&gt;
SOULS = 3&lt;br&gt;
LOW_MAX = 10          # most questions for short material&lt;br&gt;
HIGH_MAX = 50         # most questions for big material&lt;br&gt;
HIGH_PAGES = 10       # this many pages counts as big material&lt;br&gt;
CHARS_PER_PAGE = 3000&lt;br&gt;
CHARS_PER_QUESTION = 150  # short material: about 25 words per question&lt;br&gt;
MIN_CHARS = 80            # less text than this is too thin to quiz&lt;br&gt;
PER_CALL = 4        # questions requested in one text call&lt;br&gt;
MEDIA_PER_CALL = 8  # questions requested in one photo/scan/video call&lt;br&gt;
WORKERS = 3         # model calls running at the same time&lt;br&gt;
CHUNK_SIZE = 3000&lt;br&gt;
MAX_IMAGES = 30&lt;br&gt;
MAX_FILE_MB = 200   # bigger files are refused&lt;br&gt;
TYPE_DELAY = 0.004  # typing effect speed (smaller = faster)&lt;br&gt;
POINT_PENALTY = 5   # points lost for every wrong answer&lt;br&gt;
START_POINTS = 0    # points you begin with (set it to e.g. 20 for a pool that wrong answers drain)&lt;br&gt;
IMAGE_TYPES = (".jpg", ".jpeg", ".png", ".webp")&lt;br&gt;
VIDEO_TYPES = (".mp4", ".mov", ".mkv", ".webm", ".avi")&lt;br&gt;
REQUIRED = ["question", "options", "answer"]&lt;br&gt;
TONES = ("gothic", "dark")&lt;br&gt;
LAST_ERROR = {"msg": ""}  # remembers why the last question failed&lt;/p&gt;

&lt;h1&gt;
  
  
  Messages by tone: "gothic" = Gothic &amp;amp; Eerie, "dark" = Dark &amp;amp; Ominous
&lt;/h1&gt;

&lt;p&gt;MESSAGES = {&lt;br&gt;
    "correct": {&lt;br&gt;
        "gothic": [&lt;br&gt;
            "The spirits whisper... you are correct.",&lt;br&gt;
            "A chill runs down your spine as the truth reveals itself.",&lt;br&gt;
            "The shadows recede, satisfied with your answer.",&lt;br&gt;
            "You have appeased the ancient ones... for now.",&lt;br&gt;
            "The dust settles on the tomb. You spoke the true word.",&lt;br&gt;
            "The candle flames bow to your answer.",&lt;br&gt;
            "A distant bell tolls once... in approval.",&lt;br&gt;
            "The old library creaks, as if nodding in agreement.",&lt;br&gt;
            "Moonlight spills across the page. The truth is yours.",&lt;br&gt;
            "The mist parts, and the path forward appears.",&lt;br&gt;
            "A raven watches from the rafters, and lowers its gaze in respect.",&lt;br&gt;
            "The cobwebs tremble. The ghost is pleased.",&lt;br&gt;
        ],&lt;br&gt;
        "dark": [&lt;br&gt;
            "You survive to face the next question.",&lt;br&gt;
            "The executioner lowers his axe... you live.",&lt;br&gt;
            "Correct. You narrowly avoided a grim fate.",&lt;br&gt;
            "Your soul remains your own. Next.",&lt;br&gt;
            "The countdown pauses. You have bought yourself a little more time.",&lt;br&gt;
            "Right again. But the dark is still watching.",&lt;br&gt;
            "You live... but the night is far from over.",&lt;br&gt;
            "The reaper pauses, then lowers his scythe. For now.",&lt;br&gt;
            "Correct. The noose loosens, just a little.",&lt;br&gt;
            "The hunger in the dark is denied... this time.",&lt;br&gt;
            "Your answer holds. The dungeon door stays shut.",&lt;br&gt;
            "The entity retreats into the shadows, but it will return.",&lt;br&gt;
        ],&lt;br&gt;
    },&lt;br&gt;
    "wrong": {&lt;br&gt;
        "gothic": [&lt;br&gt;
            "A sudden wind blows out your candle... incorrect.",&lt;br&gt;
            "The fog thickens. You are lost in the dark.",&lt;br&gt;
            "Something just laughed behind you. That was wrong.",&lt;br&gt;
            "The spirits shake their heads in disappointment.",&lt;br&gt;
            "The portrait on the wall watches you fail, its eyes narrowing.",&lt;br&gt;
            "The candle gutters and dies. That was not the answer.",&lt;br&gt;
            "A raven cries from the rafters. You have erred.",&lt;br&gt;
            "The old clock strikes thirteen. Something is very wrong.",&lt;br&gt;
            "Cold mist curls around your ankles. Wrong.",&lt;br&gt;
            "The pages rustle with a mocking whisper.",&lt;br&gt;
            "The mirror shows a face behind you, shaking its head.",&lt;br&gt;
            "A bell tolls in the distance... for your mistake.",&lt;br&gt;
        ],&lt;br&gt;
        "dark": [&lt;br&gt;
            "That mistake will haunt you forever.",&lt;br&gt;
            "The trapdoor creaks open beneath your feet.",&lt;br&gt;
            "Incorrect. The shadows draw a little closer.",&lt;br&gt;
            "You hear chains rattling... your time is running out.",&lt;br&gt;
            "The entity grows hungry. Your mistake feeds it.",&lt;br&gt;
            "A soul slips away into the dark. Incorrect.",&lt;br&gt;
            "The grave opens a little wider.",&lt;br&gt;
            "The reaper marks your name. Wrong.",&lt;br&gt;
            "The noose tightens. That answer was your mistake.",&lt;br&gt;
            "The dungeon door groans open, hungry for you.",&lt;br&gt;
            "The shadows lean in, tasting your failure.",&lt;br&gt;
            "Your fate darkens with every wrong word.",&lt;br&gt;
        ],&lt;br&gt;
    },&lt;br&gt;
    "skip": {&lt;br&gt;
        "gothic": [&lt;br&gt;
            "You cannot flee the archives; the doors are locked from the outside.",&lt;br&gt;
            "The fog blocks your path. You must face what lies ahead.",&lt;br&gt;
            "Turning your back on the spirits only makes them angry.",&lt;br&gt;
            "The pages turn themselves back. You cannot run from this.",&lt;br&gt;
            "A cold hand grips your shoulder, forcing you to turn around.",&lt;br&gt;
            "The corridor stretches on forever. There is no way to skip ahead.",&lt;br&gt;
            "The candles gutter. The ghost will not let you pass.",&lt;br&gt;
            "The tome slams shut, then opens again to the same question.",&lt;br&gt;
            "Mist seals the staircase. Only an answer will clear it.",&lt;br&gt;
            "The portraits turn their eyes upon you. Answer.",&lt;br&gt;
            "The clock refuses to move until you answer.",&lt;br&gt;
        ],&lt;br&gt;
        "dark": [&lt;br&gt;
            "Cowardice carries a much steeper price than failure.",&lt;br&gt;
            "There are no exits in the dark. Choose your fate.",&lt;br&gt;
            "You can try to run, but the entity is already waiting at the end of the hall.",&lt;br&gt;
            "The blade drops lower every time you hesitate. Answer.",&lt;br&gt;
            "Skipping will only bring the horror closer. Make your choice.",&lt;br&gt;
            "The reaper does not allow skipping. Answer, or pay.",&lt;br&gt;
            "The dungeon door bolts itself. You are not leaving.",&lt;br&gt;
            "Every step you take back, the dark takes two forward.",&lt;br&gt;
            "The entity whispers: you will answer... one way or another.",&lt;br&gt;
            "The shadows swallow the exit. Choose, mortal.",&lt;br&gt;
            "Hesitation is a gift to the dead. Answer.",&lt;br&gt;
        ],&lt;br&gt;
    },&lt;br&gt;
}&lt;br&gt;
SKIP_WORDS = ("skip", "s", "pass", "next")&lt;/p&gt;

&lt;p&gt;def say(kind, tone):&lt;br&gt;
    return random.choice(MESSAGES[kind][tone])&lt;/p&gt;

&lt;p&gt;RECEIVED_MESSAGES = [&lt;br&gt;
    # gothic and eerie&lt;br&gt;
    "The leaves rustle as your pages turn in the dark.",&lt;br&gt;
    "We have received your manuscript. The spirits are already reading over your shoulder.",&lt;br&gt;
    "A cold wind blows through the server... your file has arrived safely.",&lt;br&gt;
    "Your words have been etched into the obsidian stones of our library.",&lt;br&gt;
    "The ink bleeds into the screen. Your document is accepted.",&lt;br&gt;
    # dark and ominous&lt;br&gt;
    "There is no turning back now. Your file belongs to the abyss.",&lt;br&gt;
    "We have locked your data in the cellar. Pray nothing finds it.",&lt;br&gt;
    "You have handed us the key. The entity is pleased.",&lt;br&gt;
    "Correctly received. But remember... once uploaded, it can never truly be forgotten.",&lt;br&gt;
    "A trapdoor closes behind your file. It is ours now.",&lt;br&gt;
]&lt;br&gt;
LOADING_MESSAGES = [&lt;br&gt;
    "The entity is tearing your file apart to read the pieces...",&lt;br&gt;
    "Shhh... the walls are listening to your data.",&lt;br&gt;
    "Chains rattle in the server room as your file ascends.",&lt;br&gt;
    "Bleeding through the wires... almost there.",&lt;br&gt;
    "The darkness is stretching to accommodate your offering.",&lt;br&gt;
]&lt;br&gt;
UPLOAD_SUCCESS_MESSAGES = [&lt;br&gt;
    "It is finished. Your sacrifice has been accepted into the vault.",&lt;br&gt;
    "The archives have swallowed it whole. It rests in peace now.",&lt;br&gt;
    "We've locked it away where the light can never reach it.",&lt;br&gt;
    "The whispers have ceased. Your text is now part of the gloom.",&lt;br&gt;
    "The ink has dried. The pact is sealed.",&lt;br&gt;
]&lt;br&gt;
UPLOAD_FAIL_MESSAGES = [&lt;br&gt;
    "The abyss rejected your offering. Try again... if you dare.",&lt;br&gt;
    "Something in the shadows bit the wire. Upload severed.",&lt;br&gt;
    "Your file died on the way down. Resurrect it and try again.",&lt;br&gt;
    "The spirits are displeased with this format. Give them something else.",&lt;br&gt;
    "It slipped into the cracks between the servers. It's gone forever. Retry.",&lt;br&gt;
]&lt;br&gt;
TOO_LARGE_MESSAGES = [&lt;br&gt;
    "This is too heavy for the ghosts to carry. Shrink your offering.",&lt;br&gt;
    "The entity refuses to swallow a beast of this size.",&lt;br&gt;
]&lt;br&gt;
WRONG_FORMAT_MESSAGES = [&lt;br&gt;
    "A foul curse has corrupted this file type. Send a .txt or .pdf instead.",&lt;br&gt;
    "The skeletons cannot read these runes. Change the format.",&lt;br&gt;
]&lt;br&gt;
VOID_MESSAGES = [  # short material, but the player asked for more than 10&lt;br&gt;
    "The void cannot stretch that far, mortal. These pages hold too little darkness for so many questions.",&lt;br&gt;
    "You ask for more than the void can give... it groans, and cracks spread across the walls.",&lt;br&gt;
    "Greedy soul. There is nothing more in these pages to feed you. The void will choose for you.",&lt;br&gt;
    "The shadows stretch thin, and tear. The void cannot give what you demand.",&lt;br&gt;
    "The abyss laughs: 'There is nothing left to ask.' I will decide the number myself.",&lt;br&gt;
]&lt;br&gt;
HESITATION_MESSAGES = [  # short material, and the player gave no number&lt;br&gt;
    "You hesitate... the ghost smells your fear. Very well, I will choose for you.",&lt;br&gt;
    "Silence. The candles lean toward you, waiting. Your indecision has been noted.",&lt;br&gt;
    "A cold breath on your neck: 'Cannot decide, mortal? Then I will decide.'",&lt;br&gt;
    "Every second you wait, the shadows lean closer. I take the choice from your trembling hands.",&lt;br&gt;
    "Hesitation is the first step into the dark. I will choose, and you will obey.",&lt;br&gt;
]&lt;br&gt;
MOCKING_MESSAGES = [  # big material, and the player gave no number&lt;br&gt;
    "Hahaha... you cannot even choose? This tome is vast, and you are not in control. FIFTY.",&lt;br&gt;
    "Such a small, trembling mortal. You have no say here. Fifty questions await you.",&lt;br&gt;
    "Powerless and indecisive... delicious. The abyss decrees: fifty levels.",&lt;br&gt;
    "You think you hold the pen? The entity writes your fate now: fifty questions.",&lt;br&gt;
    "Pathetic. The dark takes control, as it always does. Fifty levels. No mercy.",&lt;br&gt;
]&lt;br&gt;
ABYSS_LIMIT_MESSAGES = [  # big material, and the player asked for more than 50&lt;br&gt;
    "Even the abyss has limits, mortal. Fifty is all it can swallow.",&lt;br&gt;
    "More than fifty? The tome slams shut on your fingers. Fifty questions, no more.",&lt;br&gt;
]&lt;br&gt;
POINTS_ZERO_MESSAGES = [  # dark and ominous: the points ran out&lt;br&gt;
    "Your points drain away... one by one... until nothing is left. The entity feeds, and you are no more.",&lt;br&gt;
    "Zero. The number glows blood-red. The trapdoor opens beneath you, and the dark swallows you whole.",&lt;br&gt;
    "The last of your points slips through your fingers like ash. The executioner raises his axe... and this time, he does not stop.",&lt;br&gt;
    "Nothing left. The hall seals itself, the candles die, and something hungry steps out of the shadows.",&lt;br&gt;
    "Your score has bled out. There is nothing left to pay for your mistakes... except you.",&lt;br&gt;
    "Empty-handed, you hear the chains rattle... closer... and closer... Then the darkness takes you.",&lt;br&gt;
]&lt;br&gt;
ZERO_MESSAGES = [  # the player typed 0 for the number of levels&lt;br&gt;
    "Zero...?",&lt;br&gt;
    "The doors slam shut behind you. The candles die, one by one.",&lt;br&gt;
    "'You think you can walk away from me, mortal?'",&lt;br&gt;
    "Something cold breathes on the back of your neck. You do not dare to turn around.",&lt;br&gt;
    "Very well. If you will not choose your fate, I will choose it for you.",&lt;br&gt;
]&lt;br&gt;
TEXT_WAIT_MESSAGES = [&lt;br&gt;
    "(The entity is carving your questions into the walls... this takes only a moment.)",&lt;br&gt;
    "(Something in the dark is writing your questions. Do not look behind you...)",&lt;br&gt;
    "(The ink of the damned is drying... your questions are almost ready.)",&lt;br&gt;
    "(The shadows are whispering your questions to the ghost... wait.)",&lt;br&gt;
    "(Your questions are being scratched into the coffin lid... just a few seconds.)",&lt;br&gt;
]&lt;br&gt;
MEDIA_WAIT_MESSAGES = [&lt;br&gt;
    "(The ghost is reading your pages by candlelight... this can take a minute.)",&lt;br&gt;
    "(Cold fingers turn your pages in the dark... this can take a minute.)",&lt;br&gt;
    "(The entity is devouring every page, one by one... this can take a minute.)",&lt;br&gt;
]&lt;br&gt;
VIDEO_WAIT_MESSAGES = [&lt;br&gt;
    "(No captions? The ghost watches the video itself, unblinking... this can take a minute.)",&lt;br&gt;
    "(The entity stares into your video through the dark... this can take a minute.)",&lt;br&gt;
]&lt;br&gt;
BIG_TOME_MESSAGES = [&lt;br&gt;
    "(A tome this vast takes time to devour. Be patient, mortal...)",&lt;br&gt;
    "(The abyss reads slowly, page after endless page... be patient, mortal.)",&lt;br&gt;
]&lt;br&gt;
GAME_OVER_ART = r"""&lt;br&gt;
      .-.&lt;br&gt;
     (o o)   BOO!&lt;br&gt;
     | O \&lt;br&gt;
      \   \&lt;br&gt;
       `~~~'&lt;br&gt;
"""&lt;/p&gt;

&lt;h1&gt;
  
  
  ---------- reading the material ----------
&lt;/h1&gt;

&lt;p&gt;class SpookyError(Exception):&lt;br&gt;
    """An error whose message is already written in the ghost's voice."""&lt;/p&gt;

&lt;p&gt;def read_pdf(path):&lt;br&gt;
    from pypdf import PdfReader&lt;br&gt;
    reader = PdfReader(path)&lt;br&gt;
    return "\n".join((page.extract_text() or "") for page in reader.pages)&lt;/p&gt;

&lt;p&gt;def read_docx(path):&lt;br&gt;
    from docx import Document&lt;br&gt;
    doc = Document(path)&lt;br&gt;
    parts = [p.text for p in doc.paragraphs]&lt;br&gt;
    for table in doc.tables:&lt;br&gt;
        for row in table.rows:&lt;br&gt;
            parts.append(" | ".join(cell.text for cell in row.cells))&lt;br&gt;
    return "\n".join(parts)&lt;/p&gt;

&lt;p&gt;def read_xlsx(path):&lt;br&gt;
    from openpyxl import load_workbook&lt;br&gt;
    wb = load_workbook(path, data_only=True, read_only=True)&lt;br&gt;
    parts = []&lt;br&gt;
    for sheet in wb.worksheets:&lt;br&gt;
        parts.append(f"Sheet: {sheet.title}")&lt;br&gt;
        for row in sheet.iter_rows(values_only=True):&lt;br&gt;
            cells = [str(c) for c in row if c is not None]&lt;br&gt;
            if cells:&lt;br&gt;
                parts.append(" | ".join(cells))&lt;br&gt;
    return "\n".join(parts)&lt;/p&gt;

&lt;p&gt;def read_pptx(path):&lt;br&gt;
    from pptx import Presentation&lt;br&gt;
    parts = []&lt;br&gt;
    for i, slide in enumerate(Presentation(path).slides, start=1):&lt;br&gt;
        parts.append(f"Slide {i}")&lt;br&gt;
        for shape in slide.shapes:&lt;br&gt;
            if shape.has_text_frame:&lt;br&gt;
                parts.append(shape.text_frame.text)&lt;br&gt;
            if getattr(shape, "has_table", False) and shape.has_table:&lt;br&gt;
                for row in shape.table.rows:&lt;br&gt;
                    parts.append(" | ".join(cell.text for cell in row.cells))&lt;br&gt;
    return "\n".join(parts)&lt;/p&gt;

&lt;p&gt;def read_text(path):&lt;br&gt;
    with open(path, "r", encoding="utf-8", errors="ignore") as f:&lt;br&gt;
        return f.read()&lt;/p&gt;

&lt;p&gt;def youtube_id(url):&lt;br&gt;
    m = re.search(r"(?:v=|youtu.be/|shorts/|embed/)([A-Za-z0-9_-]{11})", url)&lt;br&gt;
    return m.group(1) if m else None&lt;/p&gt;

&lt;p&gt;def read_youtube(url):&lt;br&gt;
    from youtube_transcript_api import YouTubeTranscriptApi&lt;br&gt;
    vid = youtube_id(url)&lt;br&gt;
    if not vid:&lt;br&gt;
        raise ValueError("I could not find a video ID in that link.")&lt;br&gt;
    langs = ["en", "hi"]&lt;br&gt;
    try:&lt;br&gt;
        items = YouTubeTranscriptApi().fetch(vid, languages=langs)  # newer versions&lt;br&gt;
        return " ".join(item.text for item in items)&lt;br&gt;
    except AttributeError:&lt;br&gt;
        items = YouTubeTranscriptApi.get_transcript(vid, languages=langs)  # older&lt;br&gt;
        return " ".join(item["text"] for item in items)&lt;/p&gt;

&lt;p&gt;READERS = {&lt;br&gt;
    ".docx": read_docx, ".xlsx": read_xlsx, ".pptx": read_pptx,&lt;br&gt;
    ".txt": read_text, ".md": read_text,&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;def pages_from_text(text):&lt;br&gt;
    return max(1, round(len(text) / CHARS_PER_PAGE))&lt;/p&gt;

&lt;p&gt;def pdf_pages(path):&lt;br&gt;
    try:&lt;br&gt;
        from pypdf import PdfReader&lt;br&gt;
        return max(1, len(PdfReader(path).pages))&lt;br&gt;
    except Exception:&lt;br&gt;
        return 1&lt;/p&gt;

&lt;p&gt;def load_material(source):&lt;br&gt;
    """Returns (kind, material, pages): kind is 'text', 'media' or 'youtube'."""&lt;br&gt;
    source = source.strip().strip('"').strip("'")&lt;br&gt;
    if source.lower().startswith("http") and ("youtube.com" in source or "youtu.be" in source):&lt;br&gt;
        if not youtube_id(source):&lt;br&gt;
            raise SpookyError("The ghost finds no video in that link. Check it and try again.")&lt;br&gt;
        try:&lt;br&gt;
            text = read_youtube(source)&lt;br&gt;
            return "text", text, pages_from_text(text)&lt;br&gt;
        except Exception:&lt;br&gt;
            return "youtube", source, 1  # no captions: let Gemini watch the video itself&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if os.path.isdir(source):  # a folder of textbook photos
    photos = sorted(os.path.join(source, f) for f in os.listdir(source)
                    if f.lower().endswith(IMAGE_TYPES))[:MAX_IMAGES]
    if not photos:
        raise SpookyError(random.choice(WRONG_FORMAT_MESSAGES) + " (That folder has no jpg, png or webp photos.)")
    return "media", photos, len(photos)

if not os.path.isfile(source):
    raise SpookyError("The ghost cannot find that. Check the path, or paste a YouTube link.")
if os.path.getsize(source) &amp;gt; MAX_FILE_MB * 1_000_000:
    raise SpookyError(random.choice(TOO_LARGE_MESSAGES) + f" (The limit is {MAX_FILE_MB} MB.)")
ext = os.path.splitext(source)[1].lower()
if ext in IMAGE_TYPES:
    return "media", [source], 1
if ext in VIDEO_TYPES:
    return "media", [source], 4  # a video cannot be measured cheaply, so assume a medium one
if ext == ".pdf":
    text = read_pdf(source)
    pages = pdf_pages(source)
    if len(re.sub(r"\s+", "", text)) &amp;lt; 300 * pages // 3 + 100:  # almost no text: a scanned PDF
        return "media", [source], pages
    return "text", text, pages
if ext in READERS:
    text = READERS[ext](source)
    return "text", text, pages_from_text(text)
raise SpookyError(random.choice(WRONG_FORMAT_MESSAGES)
                  + " (I read PDF, DOCX, XLSX, PPTX, TXT, photos, videos and YouTube links.)")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h1&gt;
  
  
  ---------- talking to the models ----------
&lt;/h1&gt;

&lt;p&gt;def slow_print(text, delay=TYPE_DELAY):&lt;br&gt;
    for ch in text:&lt;br&gt;
        print(ch, end="", flush=True)&lt;br&gt;
        time.sleep(delay)&lt;br&gt;
    print()&lt;/p&gt;

&lt;p&gt;def ask_model(model_name, prompt):&lt;br&gt;
    model = genai.GenerativeModel(model_name)&lt;br&gt;
    for attempt in range(3):&lt;br&gt;
        try:&lt;br&gt;
            return model.generate_content(prompt).text&lt;br&gt;
        except Exception as e:&lt;br&gt;
            LAST_ERROR["msg"] = f"{model_name}: {str(e)[:150]}"&lt;br&gt;
            time.sleep(2 * (attempt + 1))  # slow and steady: wait, then retry&lt;br&gt;
    return None&lt;/p&gt;

&lt;p&gt;def is_valid(q):&lt;br&gt;
    return (isinstance(q, dict) and all(k in q for k in REQUIRED)&lt;br&gt;
            and isinstance(q["options"], list) and len(q["options"]) == 4&lt;br&gt;
            and str(q["answer"]).strip().upper()[:1] in list("ABCD"))&lt;/p&gt;

&lt;p&gt;TRAP_RE = re.compile(r"^\s*(?:all|none)\s+of\s+(?:the\s+above|these)", re.I)&lt;br&gt;
LETTER_RE = re.compile(r"\b(?:Both|Option|Choice)\s+[A-D]\b")&lt;/p&gt;

&lt;p&gt;def clean(q):&lt;br&gt;
    """Tidy a question: align the reasons, shuffle the options (but keep a trap option last)."""&lt;br&gt;
    options = [re.sub(r"^\s*[A-Da-d][).:]\s+", "", str(o)).strip() for o in q["options"]]&lt;br&gt;
    answer = "ABCD".index(str(q["answer"]).strip().upper()[0])&lt;br&gt;
    tone = q.get("tone") if q.get("tone") in TONES else random.choice(TONES)&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;raw = q.get("reasons")
if not (isinstance(raw, list) and len(raw) == 4):
    raw = [""] * 4
reasons = []
for i in range(4):
    text = str(raw[i]).strip()
    if len(text.split()) &amp;lt; 5:  # missing or too thin to explain anything
        text = f"The truth is: {options[i]}." if i == answer else say("wrong", tone)
    reasons.append(text)

pairs = list(zip(options, reasons))
joined = " ".join(options)
if TRAP_RE.match(options[3]):
    # "All of the above" / "None of the above" stays last and must be the answer
    if answer != 3:
        return None
    front = pairs[:3]
    random.shuffle(front)
    pairs = front + pairs[3:]
elif "of the above" in joined.lower() or LETTER_RE.search(joined):
    pass  # the options point at each other, so keep their order
else:
    order = list(range(4))
    random.shuffle(order)
    pairs = [pairs[i] for i in order]
    answer = order.index(answer)

q["options"] = [p[0] for p in pairs]
q["reasons"] = [p[1] for p in pairs]
q["answer"] = "ABCD"[answer]
q["tone"] = tone
q["skip"] = str(q.get("skip") or "").strip() or say("skip", tone)
return q
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;def parse_many(text, plan=None):&lt;br&gt;
    items = []&lt;br&gt;
    # Gemma may explain first, so start at the list of objects&lt;br&gt;
    m = re.search(r"[\s*{", text)&lt;br&gt;
    end = text.rfind("]")&lt;br&gt;
    if m and end &amp;gt; m.start():&lt;br&gt;
        try:&lt;br&gt;
            items = json.loads(text[m.start():end + 1])&lt;br&gt;
        except json.JSONDecodeError:&lt;br&gt;
            items = []&lt;br&gt;
    if not items:  # fall back to any separate JSON objects in the reply&lt;br&gt;
        for candidate in re.findall(r"{[^{}]*}", text, re.S):&lt;br&gt;
            try:&lt;br&gt;
                items.append(json.loads(candidate))&lt;br&gt;
            except json.JSONDecodeError:&lt;br&gt;
                pass&lt;br&gt;
    questions = []&lt;br&gt;
    for i, q in enumerate(items):&lt;br&gt;
        if not is_valid(q):&lt;br&gt;
            continue&lt;br&gt;
        if plan and i &amp;lt; len(plan):&lt;br&gt;
            q["tone"] = plan[i]["tone"]&lt;br&gt;
        q = clean(q)&lt;br&gt;
        if q:&lt;br&gt;
            questions.append(q)&lt;br&gt;
    return questions&lt;/p&gt;

&lt;p&gt;STYLE_GUIDE = """Tone styles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Gothic &amp;amp; Eerie: whispering spirits, receding shadows, candles blowing out, thickening fog, disembodied laughter, locked library doors, cold hands gripping shoulders.&lt;/li&gt;
&lt;li&gt;Dark &amp;amp; Ominous: surviving executioners, narrow escapes, mistakes haunting you forever, creaking trapdoors, feeding the hungry entity, inescapable halls, the price of cowardice."""&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;FORMAT = """Each question is a JSON object with these keys:&lt;br&gt;
"question": one short line of psychological horror in the assigned tone, then a clear, short exam question,&lt;br&gt;
"options": a list of exactly 4 short answer strings (no letters in front),&lt;br&gt;
"answer": the correct letter, one of "A", "B", "C", "D",&lt;br&gt;
"reasons": a list of exactly 4 sentences, one for each option in the same order as "options", shown when the player picks that option. Each reason must EXPLAIN, using facts from the material, why that option is correct or why it is wrong (for the correct option, explain why it is correct). You may open with a few spooky words in the assigned tone, but the real explanation must be the main part of the sentence. Examples: "The dark approves... a queue removes the oldest item first, so it is first in, first out." or "Wrong. A stack is last in, first out, which is the opposite order.",&lt;br&gt;
"skip": one short sentence in the assigned tone, shown if the player tries to skip this question,&lt;br&gt;
"tone": "gothic" or "dark"."""&lt;/p&gt;

&lt;p&gt;def question_plan(k):&lt;br&gt;
    """Decides the tone and the format of each question in a batch."""&lt;br&gt;
    start = random.randint(0, 1)&lt;br&gt;
    plan = []&lt;br&gt;
    for i in range(k):&lt;br&gt;
        kind = random.choices(["normal", "all", "none"], weights=[8, 1, 1])[0]  # traps are sprinkled in&lt;br&gt;
        plan.append({"tone": TONES[(start + i) % 2], "kind": kind})&lt;br&gt;
    if k &amp;gt;= 3 and all(p["kind"] == "normal" for p in plan):&lt;br&gt;
        plan[random.randrange(k)]["kind"] = random.choice(["all", "none"])&lt;br&gt;
    return plan&lt;/p&gt;

&lt;p&gt;def plan_text(plan):&lt;br&gt;
    lines = []&lt;br&gt;
    for i, p in enumerate(plan, start=1):&lt;br&gt;
        tone = "Gothic &amp;amp; Eerie" if p["tone"] == "gothic" else "Dark &amp;amp; Ominous"&lt;br&gt;
        if p["kind"] == "all":&lt;br&gt;
            fmt = ('ALL-OF-THE-ABOVE trap: options A, B and C are three true statements about the material '&lt;br&gt;
                   'and option D is exactly "All of the above", which is the correct answer (answer "D")')&lt;br&gt;
        elif p["kind"] == "none":&lt;br&gt;
            fmt = ('NONE-OF-THE-ABOVE trap: options A, B and C are three false, cursed fabrications '&lt;br&gt;
                   'and option D is exactly "None of the above", which is the correct answer (answer "D")')&lt;br&gt;
        else:&lt;br&gt;
            fmt = ('normal: exactly one correct option and three wrong ones; never use "all of the above", '&lt;br&gt;
                   '"none of the above" or "both A and B"')&lt;br&gt;
        lines.append(f"Question {i}: tone = {tone}; format = {fmt}.")&lt;br&gt;
    return "\n".join(lines)&lt;/p&gt;

&lt;p&gt;def questions_from_passage(passage, k):&lt;br&gt;
    plan = question_plan(k)&lt;br&gt;
    prompt = f"""You are a ghost tutor who wraps exam questions in psychological horror.&lt;br&gt;
Using ONLY the passage below, write {k} different multiple-choice questions that test understanding of its ideas.&lt;br&gt;
Do not ask about page numbers, file names or formatting. Cover different parts of the passage.&lt;br&gt;
{STYLE_GUIDE}&lt;br&gt;
Follow this plan, question by question:&lt;br&gt;
{plan_text(plan)}&lt;br&gt;
{FORMAT}&lt;br&gt;
Reply with ONLY a JSON list of {k} such objects, no other text.&lt;/p&gt;

&lt;p&gt;PASSAGE:&lt;br&gt;
{passage}"""&lt;br&gt;
    for model_name in MODELS:&lt;br&gt;
        for attempt in range(2):&lt;br&gt;
            text = ask_model(model_name, prompt)&lt;br&gt;
            qs = parse_many(text, plan) if text else []&lt;br&gt;
            if qs:&lt;br&gt;
                return qs[:k]&lt;br&gt;
            if text:&lt;br&gt;
                LAST_ERROR["msg"] = f"{model_name} gave an unusable reply: {text[:150]!r}"&lt;br&gt;
    return []&lt;/p&gt;

&lt;p&gt;def split_chunks(text, size=CHUNK_SIZE):&lt;br&gt;
    text = re.sub(r"\s+", " ", text).strip()&lt;br&gt;
    chunks = [text[i:i + size] for i in range(0, len(text), size)]&lt;br&gt;
    return [c for c in chunks if len(c) &amp;gt; 200] or ([text] if text else [])&lt;/p&gt;

&lt;p&gt;def split_sizes(total, parts):&lt;br&gt;
    return [total // parts + (1 if i &amp;lt; total % parts else 0) for i in range(parts)]&lt;/p&gt;

&lt;p&gt;def merge(existing, batches):&lt;br&gt;
    """Add new questions to the list, skipping repeats."""&lt;br&gt;
    questions = list(existing)&lt;br&gt;
    seen = {re.sub(r"\W+", " ", q["question"].lower()).strip() for q in questions}&lt;br&gt;
    for batch in batches:&lt;br&gt;
        for q in batch:&lt;br&gt;
            key = re.sub(r"\W+", " ", q["question"].lower()).strip()&lt;br&gt;
            if key not in seen:&lt;br&gt;
                seen.add(key)&lt;br&gt;
                questions.append(q)&lt;br&gt;
    return questions&lt;/p&gt;

&lt;p&gt;def text_round(chunks, n):&lt;br&gt;
    batches = max(1, min(len(chunks), -(-n // PER_CALL)))&lt;br&gt;
    passages = []&lt;br&gt;
    for i in range(batches):&lt;br&gt;
        part = chunks[i::batches]&lt;br&gt;
        if len(part) &amp;gt; 3:&lt;br&gt;
            part = random.sample(part, 3)&lt;br&gt;
        passages.append(" ".join(part))&lt;br&gt;
    # several model calls at the same time, so the wait is about one call long&lt;br&gt;
    with ThreadPoolExecutor(max_workers=WORKERS) as pool:&lt;br&gt;
        return list(pool.map(lambda args: questions_from_passage(*args),&lt;br&gt;
                             zip(passages, split_sizes(n, batches))))&lt;/p&gt;

&lt;p&gt;def questions_from_text(text, levels):&lt;br&gt;
    chunks = split_chunks(text)&lt;br&gt;
    if not chunks:&lt;br&gt;
        return []&lt;br&gt;
    questions = merge([], text_round(chunks, levels))&lt;br&gt;
    if len(questions) &amp;lt; levels:  # one more round for the missing ones&lt;br&gt;
        questions = merge(questions, text_round(chunks, levels - len(questions)))&lt;br&gt;
    return questions[:levels]&lt;/p&gt;

&lt;p&gt;def prepare_media(paths):&lt;br&gt;
    """Turn photos into images and upload PDFs/videos so Gemini can look at them."""&lt;br&gt;
    parts = []&lt;br&gt;
    for path in paths:&lt;br&gt;
        if path.lower().endswith(IMAGE_TYPES):&lt;br&gt;
            from PIL import Image&lt;br&gt;
            img = Image.open(path)&lt;br&gt;
            img.thumbnail((1600, 1600))&lt;br&gt;
            parts.append(img.convert("RGB"))&lt;br&gt;
        else:&lt;br&gt;
            f = genai.upload_file(path)&lt;br&gt;
            while f.state.name == "PROCESSING":&lt;br&gt;
                time.sleep(3)&lt;br&gt;
                f = genai.get_file(f.name)&lt;br&gt;
            if f.state.name != "ACTIVE":&lt;br&gt;
                raise RuntimeError("The upload failed.")&lt;br&gt;
            parts.append(f)&lt;br&gt;
    return parts&lt;/p&gt;

&lt;p&gt;def media_batch(parts, k, number, count):&lt;br&gt;
    plan = question_plan(k)&lt;br&gt;
    portion = ""&lt;br&gt;
    if count &amp;gt; 1:&lt;br&gt;
        start, end = round(100 * number / count), round(100 * (number + 1) / count)&lt;br&gt;
        portion = f"Write the questions about the part of the material from about {start}% to {end}% of the way through it.\n"&lt;br&gt;
    prompt = f"""You are a ghost tutor who wraps exam questions in psychological horror.&lt;br&gt;
Read or watch the material provided (it may be photos of textbook pages, a scanned document or a video).&lt;br&gt;
Write {k} different multiple-choice questions about its content.&lt;br&gt;
{portion}{STYLE_GUIDE}&lt;br&gt;
Follow this plan, question by question:&lt;br&gt;
{plan_text(plan)}&lt;br&gt;
{FORMAT}&lt;br&gt;
Reply with ONLY a JSON list of {k} such objects, no other text."""&lt;br&gt;
    model = genai.GenerativeModel(MEDIA_MODEL)&lt;br&gt;
    for attempt in range(3):&lt;br&gt;
        try:&lt;br&gt;
            return parse_many(model.generate_content(parts + [prompt]).text, plan)[:k]&lt;br&gt;
        except Exception as e:&lt;br&gt;
            LAST_ERROR["msg"] = f"{MEDIA_MODEL}: {str(e)[:150]}"&lt;br&gt;
            time.sleep(2 * (attempt + 1))&lt;br&gt;
    return []&lt;/p&gt;

&lt;p&gt;def questions_from_media(paths, n):&lt;br&gt;
    try:&lt;br&gt;
        parts = prepare_media(paths)&lt;br&gt;
    except Exception as e:&lt;br&gt;
        LAST_ERROR["msg"] = f"upload: {str(e)[:150]}"&lt;br&gt;
        return []&lt;br&gt;
    count = max(1, -(-n // MEDIA_PER_CALL))&lt;br&gt;
    sizes = split_sizes(n, count)&lt;br&gt;
    with ThreadPoolExecutor(max_workers=WORKERS) as pool:&lt;br&gt;
        results = list(pool.map(lambda args: media_batch(parts, *args),&lt;br&gt;
                                [(sizes[i], i, count) for i in range(count)]))&lt;br&gt;
    return merge([], results)[:n]&lt;/p&gt;

&lt;p&gt;def questions_from_youtube(url, n):&lt;br&gt;
    """For videos with no captions. Needs: pip install google-genai"""&lt;br&gt;
    try:&lt;br&gt;
        from google import genai as new_genai&lt;br&gt;
        from google.genai import types&lt;br&gt;
    except ImportError:&lt;br&gt;
        slow_print("\nTo watch captionless videos I need one more package: pip install google-genai")&lt;br&gt;
        return []&lt;br&gt;
    client = new_genai.Client(api_key=API_KEY)&lt;br&gt;
    plan = question_plan(n)&lt;br&gt;
    prompt = f"""You are a ghost tutor who wraps exam questions in psychological horror.&lt;br&gt;
Watch this video and write {n} different multiple-choice questions about its content.&lt;br&gt;
{STYLE_GUIDE}&lt;br&gt;
Follow this plan, question by question:&lt;br&gt;
{plan_text(plan)}&lt;br&gt;
{FORMAT}&lt;br&gt;
Reply with ONLY a JSON list of {n} such objects, no other text."""&lt;br&gt;
    for attempt in range(3):&lt;br&gt;
        try:&lt;br&gt;
            response = client.models.generate_content(&lt;br&gt;
                model=MEDIA_MODEL,&lt;br&gt;
                contents=types.Content(parts=[&lt;br&gt;
                    types.Part(file_data=types.FileData(file_uri=url)),&lt;br&gt;
                    types.Part(text=prompt),&lt;br&gt;
                ]),&lt;br&gt;
            )&lt;br&gt;
            return parse_many(response.text, plan)[:n]&lt;br&gt;
        except Exception as e:&lt;br&gt;
            LAST_ERROR["msg"] = f"video: {str(e)[:150]}"&lt;br&gt;
            time.sleep(2 * (attempt + 1))&lt;br&gt;
    return []&lt;/p&gt;

&lt;h1&gt;
  
  
  ---------- the game ----------
&lt;/h1&gt;

&lt;p&gt;def route_for(kind, material, pages):&lt;br&gt;
    """Returns ('low' or 'high', the most levels this material can have)."""&lt;br&gt;
    if pages &amp;gt;= HIGH_PAGES:&lt;br&gt;
        return "high", HIGH_MAX&lt;br&gt;
    if kind == "text":&lt;br&gt;
        chars = len(re.sub(r"\s+", " ", material).strip())&lt;br&gt;
        if chars &amp;lt; MIN_CHARS:&lt;br&gt;
            return "low", 0&lt;br&gt;
        return "low", max(1, min(LOW_MAX, chars // CHARS_PER_QUESTION))&lt;br&gt;
    if kind == "media":&lt;br&gt;
        return "low", max(1, min(LOW_MAX, 3 * pages))&lt;br&gt;
    return "low", LOW_MAX  # a video with no captions: cannot measure it&lt;/p&gt;

&lt;p&gt;REFUSE_WORDS = ("", "skip", "s", "pass", "no", "none", "nah", "later", "idk",&lt;br&gt;
                "whatever", "any", "auto", "you choose", "dont know", "don't know")&lt;/p&gt;

&lt;p&gt;def ask_levels(route, cap):&lt;br&gt;
    if route == "high":&lt;br&gt;
        slow_print(f"\nThis tome is vast. The abyss may ask you up to {cap} questions.")&lt;br&gt;
    else:&lt;br&gt;
        slow_print(f"\nThis material holds enough secrets for up to {cap} level(s).")&lt;br&gt;
    while True:&lt;br&gt;
        raw = input(f"How many levels dare you play with me, mortal? (1-{cap}) ").strip().lower()&lt;br&gt;
        if raw in REFUSE_WORDS:  # no number given&lt;br&gt;
            if route == "high":&lt;br&gt;
                slow_print(random.choice(MOCKING_MESSAGES))&lt;br&gt;
                return HIGH_MAX&lt;br&gt;
            slow_print(random.choice(HESITATION_MESSAGES))&lt;br&gt;
            slow_print(f"(The ghost chooses {cap} level(s).)")&lt;br&gt;
            return cap&lt;br&gt;
        if not raw.isdigit():&lt;br&gt;
            slow_print("The ghost does not understand... speak a number, mortal.")&lt;br&gt;
            continue&lt;br&gt;
        n = int(raw)&lt;br&gt;
        if n == 0:  # the player refuses: the ghost picks a number to match the content&lt;br&gt;
            zero_levels()&lt;br&gt;
            n = random.randint(max(1, (cap + 1) // 2), cap)&lt;br&gt;
            slow_print(f"(The ghost chooses {n} level(s).)")&lt;br&gt;
            return n&lt;br&gt;
        if route == "high":&lt;br&gt;
            if n &amp;gt; HIGH_MAX:&lt;br&gt;
                slow_print(random.choice(ABYSS_LIMIT_MESSAGES))&lt;br&gt;
                return HIGH_MAX&lt;br&gt;
            return n  # fewer than 50: exactly what was asked&lt;br&gt;
        if n &amp;gt; LOW_MAX:&lt;br&gt;
            slow_print(random.choice(VOID_MESSAGES))&lt;br&gt;
            slow_print(f"(The ghost chooses {cap} level(s).)")&lt;br&gt;
            return cap&lt;br&gt;
        if n &amp;gt; cap:&lt;br&gt;
            slow_print(f"This material only holds {cap} secret(s), mortal. We will play {cap}.")&lt;br&gt;
            return cap&lt;br&gt;
        return n&lt;/p&gt;

&lt;p&gt;def zero_levels():&lt;br&gt;
    print()&lt;br&gt;
    for line in ZERO_MESSAGES:&lt;br&gt;
        slow_print(line, delay=0.03)&lt;br&gt;
        time.sleep(0.6)&lt;/p&gt;

&lt;p&gt;def souls_for(total):&lt;br&gt;
    """A longer game gives more souls."""&lt;br&gt;
    if total &amp;lt;= 3:&lt;br&gt;
        return total&lt;br&gt;
    return SOULS + (total - 1) // 10 if total &amp;gt; 10 else SOULS&lt;/p&gt;

&lt;p&gt;def get_choice(q, level, total, souls, start_souls, score):&lt;br&gt;
    souls_left = "* " * souls + ". " * (start_souls - souls)&lt;br&gt;
    slow_print(f"\n--- Level {level} of {total} ---   Souls: {souls_left}  Points: {score}")&lt;br&gt;
    print(f"\n{q['question']}")&lt;br&gt;
    for letter, option in zip("ABCD", q["options"]):&lt;br&gt;
        print(f"  {letter}) {option}")&lt;br&gt;
    choice = ""&lt;br&gt;
    while choice not in list("ABCD"):&lt;br&gt;
        choice = input("\nYour answer (A/B/C/D): ").strip().upper()&lt;br&gt;
        if choice.lower() in SKIP_WORDS:&lt;br&gt;
            slow_print(q["skip"])&lt;br&gt;
            choice = ""&lt;br&gt;
        elif choice not in list("ABCD"):&lt;br&gt;
            print("  Choose A, B, C or D.")&lt;br&gt;
    return choice&lt;/p&gt;

&lt;p&gt;def get_questions(kind, material, levels):&lt;br&gt;
    slow_print("\n" + random.choice(LOADING_MESSAGES))&lt;br&gt;
    if levels &amp;gt; 12:&lt;br&gt;
        slow_print(random.choice(BIG_TOME_MESSAGES))&lt;br&gt;
    if kind == "youtube":&lt;br&gt;
        slow_print(random.choice(VIDEO_WAIT_MESSAGES))&lt;br&gt;
        return questions_from_youtube(material, levels)&lt;br&gt;
    if kind == "media":&lt;br&gt;
        slow_print(random.choice(MEDIA_WAIT_MESSAGES))&lt;br&gt;
        return questions_from_media(material, levels)&lt;br&gt;
    slow_print(random.choice(TEXT_WAIT_MESSAGES))&lt;br&gt;
    return questions_from_text(material, levels)&lt;/p&gt;

&lt;p&gt;def play(kind, material, levels):&lt;br&gt;
    questions = get_questions(kind, material, levels)&lt;br&gt;
    if not questions:&lt;br&gt;
        slow_print("\n" + random.choice(UPLOAD_FAIL_MESSAGES))&lt;br&gt;
        slow_print("(No questions came back. Try clearer photos, a shorter video or another file.)")&lt;br&gt;
        if LAST_ERROR["msg"]:&lt;br&gt;
            print(f"  (why: {LAST_ERROR['msg']})")&lt;br&gt;
        return None&lt;br&gt;
    slow_print("\n" + random.choice(UPLOAD_SUCCESS_MESSAGES))&lt;br&gt;
    total = len(questions)&lt;br&gt;
    if total &amp;lt; levels:&lt;br&gt;
        slow_print(f"The spirits could only conjure {total} questions this time.")&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;slow_print(f"(Each wrong answer costs a soul and {POINT_PENALTY} points. If your points drain to zero, the ghost claims you.)")
start_souls = souls_for(total)
souls, score, streak = start_souls, START_POINTS, 0
drained = False
for level, q in enumerate(questions, start=1):
    choice = get_choice(q, level, total, souls, start_souls, score)
    chosen = "ABCD".index(choice)
    if choice == q["answer"]:
        points = 10 + min(5 * streak, 40)
        streak += 1
        score += points
        slow_print(f"\n{say('correct', q['tone'])}  (+{points} points)")
        slow_print(f"Reason: {q['reasons'][chosen]}")
    else:
        streak = 0
        souls -= 1
        lost = min(POINT_PENALTY, score)
        score -= lost
        note = f"-{lost} points" if lost else "no points left to lose"
        slow_print("\n" + say("wrong", q["tone"]) + f"  ({note})")
        slow_print(f"Reason: {q['reasons'][chosen]}")
        right = "ABCD".index(q["answer"])
        slow_print(f"(The answer was {q['answer']}: {q['options'][right]})")
        slow_print(f"Why it is correct: {q['reasons'][right]}")
        if lost &amp;gt; 0 and score == 0:  # the points have drained away
            drained = True
            break
    if souls == 0:
        break

if drained:
    print(GAME_OVER_ART)
    slow_print(random.choice(POINTS_ZERO_MESSAGES), delay=0.02)
    slow_print("GAME OVER. Your points have drained to nothing...")
    slow_print("Revise the material and dare to return!")
    return "lost"
if souls == 0:
    print(GAME_OVER_ART)
    slow_print("GAME OVER. The ghost has claimed your last soul...")
    slow_print(f"You scored {score} points. Revise the material and dare to return!")
    return "lost"
slow_print(f"\nYou escaped the haunted library with {souls} soul(s) and {score} points!")
slow_print("The ghost fades away... for now.")
return "won"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;def main():&lt;br&gt;
    slow_print("\n*** WELCOME TO THE GHOST TUTOR HAUNTED LIBRARY ***")&lt;br&gt;
    slow_print("Feed me a PDF, scanned PDF, textbook photos (or a folder of them),")&lt;br&gt;
    slow_print("a Word/Excel/PowerPoint file, a video file or a YouTube link.")&lt;br&gt;
    slow_print(f"Answer my questions. You have {SOULS} souls or more. Lose them all, and you stay...")&lt;br&gt;
    source = " ".join(sys.argv[1:])&lt;br&gt;
    while True:&lt;br&gt;
        if not source:&lt;br&gt;
            source = input("\nFile, folder or YouTube link (or 'quit'): ").strip()&lt;br&gt;
        if source.lower() in ("quit", "exit", "q"):&lt;br&gt;
            slow_print("Rest well, mortal...")&lt;br&gt;
            break&lt;br&gt;
        try:&lt;br&gt;
            kind, material, pages = load_material(source)&lt;br&gt;
        except SpookyError as e:&lt;br&gt;
            slow_print("\n" + str(e))&lt;br&gt;
            source = ""&lt;br&gt;
            continue&lt;br&gt;
        except Exception as e:&lt;br&gt;
            slow_print("\n" + random.choice(UPLOAD_FAIL_MESSAGES))&lt;br&gt;
            print(f"  (details: {e})")&lt;br&gt;
            source = ""&lt;br&gt;
            continue&lt;br&gt;
        slow_print("\n" + random.choice(RECEIVED_MESSAGES))&lt;br&gt;
        route, cap = route_for(kind, material, pages)&lt;br&gt;
        if cap == 0:&lt;br&gt;
            slow_print("\nThere is almost nothing here... the ghost cannot feed on this. Give me more to read!")&lt;br&gt;
            source = ""&lt;br&gt;
            continue&lt;br&gt;
        while True:&lt;br&gt;
            levels = ask_levels(route, cap)&lt;br&gt;
            play(kind, material, levels)&lt;br&gt;
            again = input("\nPlay again with the same material? (y/n): ").strip().lower()&lt;br&gt;
            if again != "y":&lt;br&gt;
                break&lt;br&gt;
        source = ""&lt;/p&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    main()&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;then run in powershell python ghost_game.py &amp;lt;paste your file path&amp;gt;&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How I Built It
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Language and models:&lt;/strong&gt; Python. Text goes through &lt;strong&gt;Gemma&lt;/strong&gt; (&lt;code&gt;gemma-4-31b-it&lt;/code&gt;) via Google's API, with &lt;code&gt;gemini-2.5-flash&lt;/code&gt; as a backup. Photos, scanned PDFs, video files and YouTube videos without captions go through Gemini 2.5 Flash.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reading material:&lt;/strong&gt; &lt;code&gt;pypdf&lt;/code&gt;, &lt;code&gt;python-docx&lt;/code&gt;, &lt;code&gt;openpyxl&lt;/code&gt;, &lt;code&gt;python-pptx&lt;/code&gt; and &lt;code&gt;youtube-transcript-api&lt;/code&gt;. A PDF with almost no text counts as scanned, and the page count decides which route the material takes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Writing the questions:&lt;/strong&gt; For each batch, the game first makes a plan: the tone of each question and whether it is a normal question, an "All of the above" trap or a "None of the above" trap. Gemma returns JSON with the question, four options, the answer, one reason per option and a skip line.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Checking the answers:&lt;/strong&gt; The game shuffles the options and their reasons together so each reason stays attached to its option. A trap option always stays last, and a trap question whose answer isn't that last option is thrown away.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Speed:&lt;/strong&gt; Instead of one slow call per question, several calls run at the same time (3 workers, 4 questions each). A 50-question book takes a handful of parallel batches, and one extra round fills in any gaps.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Slow and steady:&lt;/strong&gt; Gemma sometimes thinks out loud before answering, so the parser finds the JSON list inside the reply. Failed calls retry with a short wait, then fall back to the backup model.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Why Does Open Innovation Matter?
&lt;/h2&gt;

&lt;p&gt;Gemma is open-weight, so I could test again and again while building this without worrying about a locked-down tool. The same idea could run fully on my own laptop, so my study notes would never leave it, which matters when the material is private.&lt;/p&gt;

&lt;p&gt;I want to be honest about where I am today: the text part uses the Gemma API, and the photo, scan and video parts use Gemini 2.5 Flash, so those files are uploaded to Google. I couldn't confirm that Gemma could read images through the API. My next step is replacing those parts with local open models.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Lazy Payoff
&lt;/h2&gt;

&lt;p&gt;I used Ghost Tutor to revise for a coding test. Answering questions from my own notes stuck far better than rereading them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prize Categories
&lt;/h2&gt;

&lt;p&gt;Best Use of Gemma&lt;/p&gt;

</description>
      <category>devchallenge</category>
      <category>hf26challenge</category>
    </item>
    <item>
      <title>I Built a File Organizer Using Gemma Because I'm Too Lazy to Sort My Downloads</title>
      <dc:creator>Lipun Kumar Sahoo</dc:creator>
      <pubDate>Thu, 22 Oct 2026 13:42:50 +0000</pubDate>
      <link>https://dev.to/lipun_kumarsahoo_19a5b59/i-built-a-file-organizer-using-gemma-because-im-too-lazy-to-sort-my-downloads-18ni</link>
      <guid>https://dev.to/lipun_kumarsahoo_19a5b59/i-built-a-file-organizer-using-gemma-because-im-too-lazy-to-sort-my-downloads-18ni</guid>
      <description>&lt;p&gt;&lt;em&gt;This is a submission for the &lt;a href="https://dev.to/challenges/hacktoberfest-week3-2026-10-19"&gt;Hacktoberfest Open-Source AI Challenge Week 3: Slow and Steady&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Hi everyone!&lt;/p&gt;

&lt;h2&gt;
  
  
  What I Built
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  Demo
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Before:&lt;/strong&gt; 12 files, all in one folder.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fc4a1d1dfw0ajtftx1tib.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fc4a1d1dfw0ajtftx1tib.jpg" alt="Folder with 12 unsorted files" width="800" height="497"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Running the script:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fn230dw702zi1r9cd156p.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fn230dw702zi1r9cd156p.jpg" alt="Terminal showing files being moved into category folders" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;After:&lt;/strong&gt; every file in its category folder.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fuxgddl2qmixs5st72qqz.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fuxgddl2qmixs5st72qqz.jpg" alt="Folder after sorting, with seven category folders" width="800" height="504"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Code
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;shutil&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;google.generativeai&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;genai&lt;/span&gt;

&lt;span class="n"&gt;genai&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;configure&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;api_key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;GEMINI_API_KEY&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;span class="n"&gt;MODELS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;gemma-4-31b-it&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;gemini-2.5-flash&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# main model, then backup
&lt;/span&gt;
&lt;span class="n"&gt;TARGET_FOLDER&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sa"&gt;r&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;C:\path\to\your\folder&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
&lt;span class="n"&gt;CATEGORIES&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Images&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Documents&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Videos&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Audio&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Archives&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Code&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Others&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;ask_model&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;prompt&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;model&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;genai&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GenerativeModel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model_name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;generate_content&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prompt&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;
        &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nb"&gt;Exception&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;  &lt;span class="c1"&gt;# slow and steady: wait, then retry
&lt;/span&gt;    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;categorize_file&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;prompt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"""&lt;/span&gt;&lt;span class="s"&gt;Classify this filename into exactly one of these categories: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;, &lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;CATEGORIES&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;.
Filename: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;
Reply with ONLY the category name, nothing else.&lt;/span&gt;&lt;span class="sh"&gt;"""&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;model_name&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;MODELS&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;text&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;ask_model&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;prompt&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="c1"&gt;# Gemma may explain first; the answer is the last line
&lt;/span&gt;            &lt;span class="n"&gt;lines&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;l&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;l&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;splitlines&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;l&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;()]&lt;/span&gt;
            &lt;span class="n"&gt;reply&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;lines&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;*.` &lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;lower&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;  &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;model_name&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt; replied: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;reply&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;CATEGORIES&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;lower&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;reply&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Others&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;  &lt;span class="c1"&gt;# both models failed
&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;organize_folder&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="n"&gt;files&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;listdir&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;TARGET_FOLDER&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
             &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;isfile&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;TARGET_FOLDER&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;))]&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Found &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;files&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt; files to organize.&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;filename&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;files&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;category&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;categorize_file&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;category&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Skipped &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt; (could not classify)&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;continue&lt;/span&gt;
        &lt;span class="n"&gt;category_path&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;TARGET_FOLDER&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;category&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;makedirs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;category_path&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;exist_ok&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;shutil&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;move&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;TARGET_FOLDER&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
                    &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;category_path&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Moved &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt; -&amp;gt; &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;category&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;/&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;Done! Your folder is organized.&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;__main__&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nf"&gt;organize_folder&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How I Built It
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Language:&lt;/strong&gt; Python&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Model:&lt;/strong&gt; Gemma (&lt;code&gt;gemma-4-31b-it&lt;/code&gt;) through Google's API, with &lt;code&gt;gemini-2.5-flash&lt;/code&gt; as a backup&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Flow:&lt;/strong&gt; read each filename, ask Gemma for one category, create the folder if it doesn't exist, move the file&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Slow and steady:&lt;/strong&gt; 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.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Does Open Innovation Matter?
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Lazy Payoff
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I Learned
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tech used:&lt;/strong&gt; Python, Google Gemma API&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Happy Hacktoberfest!&lt;/p&gt;

</description>
      <category>devchallenge</category>
      <category>hf26challenge</category>
    </item>
  </channel>
</rss>
