#!/usr/bin/env python3 """ Creative Commons YouTube Dataset Builder (~14,000 - 15,000 Video Metadata) Collects diverse Creative Commons YouTube video links and rich metadata. No video files are downloaded (links and metadata only). Supports: 1. Official YouTube Data API v3 (reads YOUTUBE_API_KEY from environment/.env) - Tracks 10,000 daily quota units (100 units/search, 1 unit/videos.list) - Handles pagination with pageToken - Resumable checkpoints 2. Direct Creative Commons Search Client - Seamless fallback when API quota is exhausted or key is not provided - Filters protobuf params for Creative Commons ('EgIwAQ==') 3. Resumable Storage (SQLite + JSON checkpoint) 4. Export to metadata.jsonl and metadata.csv 5. Automatic Dataset Card (README.md) generation 6. Hugging Face Dataset Repo creation and upload via huggingface_hub """ import os import sys import json import csv import re import time import sqlite3 import argparse import urllib.request import urllib.parse from datetime import datetime, timedelta from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List, Dict, Any, Optional try: from dotenv import load_dotenv load_dotenv() load_dotenv("/home/user/.env") except ImportError: pass CATEGORIES = { "nature": [ "nature relaxation 4k", "forest wildlife scenery", "mountain landscape drone", "ocean waves beach sunset", "waterfall scenic nature", "river stream flowing wilderness", "blooming flowers springtime timelapse", "rainforest jungle exploration", "desert sand dunes aerial", "aurora borealis northern lights nature", "alpine wilderness mountain peaks", "canyon geological nature landscape", "coastal cliffs sea breeze", "wetlands marsh birds nature", "autumn fall foliage scenery", "deep forest moss trees", "glacier icebergs arctic nature", "meadow wildflowers summer breeze", "sunset over horizon nature", "foggy morning mist woods", "calm lake reflection sunrise", "prairie grassland wilderness", "volcanic rock geothermal landscape", "coastal tide pools marine flora", "bamboo forest wind bamboo", "underwater coral reef nature", "starry night sky milky way", "mountain creek fresh water", "winter snow covered pine trees", "desert blooming cactus flora", "tropical island green palms", "fjord steep cliffs water", "sunbeams through forest canopy", "wilderness hiking scenic views", "spring thaw mountain stream", "peaceful countryside hills panorama", "savanna acacia trees sunset", "rocky mountain pass drone view", "tranquil ocean horizon calm", "mossy rocks forest brook" ], "animals": [ "wild animals safari wildlife", "birds of prey eagle falcon flight", "marine life ocean reef fish", "domestic pets dogs playing park", "cats playful moments animals", "farm animals pasture sanctuary", "macro insects bees butterflies garden", "endangered species animal conservation", "wild horses running plains nature", "arctic wildlife penguins seals", "reptiles chameleon lizards nature", "underwater sea turtles coral", "wild wolves forest habitat", "elephants herd savanna watering hole", "bear fishing river wilderness", "fox kit wildlife den", "deer herd woodland morning", "whales breaching ocean surface", "monkeys canopy tropical jungle", "owl nocturnal birds night", "frogs pond amphibious species", "hummingbirds nectar flowers garden", "cheetah running savanna speed", "otters playing river bank", "red panda tree climbing wildlife", "dolphins swimming ocean bow", "goats climbing steep rocks", "rabbits burrow meadows nature", "swans lake reflection water", "bison grazing open range", "squirrel foraging nuts forest", "seals basking rocky shore", "jellyfish floating dark ocean", "parrots colorful tropical rainforest", "lions pride resting savanna", "badger nocturnal wildlife", "alpaca llama mountain farm", "coral reef clownfish sea anemone", "sparrow songbirds bird feeder", "koala eucalyptus trees wildlife" ], "travel": [ "solo travel backpacking journey", "historic old town walking tour", "scenic coastal road trip drive", "island exploration travel vlog", "ancient ruins heritage travel", "national park scenic hiking guide", "budget travel guide tips", "mountain pass scenic travel", "remote village countryside travel", "scenic train ride railway journey", "coastal port fishing town travel", "lake district travel scenery", "desert oasis cultural journey", "fjord scenic boat cruise travel", "historic castle travel exploration", "wandering cobblestone streets travel", "mediterranean village travel guide", "highland road trip scenic drive", "tropical beach island hopping", "alpine train scenic route", "historic cathedral architecture visit", "cultural walking tour old city", "travel vlog hidden gems", "harbor seaside promenade walk", "mountain valley scenic road", "traditional fishing village exploration", "historic canal cruise sightseeing", "balkan road trip countryside", "scandinavian coastal village", "himalayan mountain road journey", "ancient amphitheater archaeology travel", "scenic ferry crossing islands", "old fortified town battlements", "picturesque village stone cottages", "historic market square walking tour", "backpacking camping adventure travel", "scenic cliff walk coastal path", "monastery mountain pilgrimage walk", "scenic bike touring countryside", "travel documentary historical sites" ], "food": [ "street food night market tasting", "traditional regional food culture", "night market food stalls tour", "artisan bakery bread pastries", "specialty coffee roasting brewing", "fresh seafood market catch", "farm to table local ingredients food", "regional traditional dishes tasting", "traditional desserts sweets culture", "artisan cheese making dairy", "fermented traditional foods culinary", "fruit market fresh produce tour", "tea harvest ceremony tasting", "farmers market organic food stalls", "traditional noodle making craft", "chocolate tasting bean to bar", "spice market aromatic herbs spices", "honey harvesting local apiary", "traditional flatbread oven baking", "local street snacks food crawl", "olive oil pressing tasting", "traditional dim sum tea house", "fresh pasta artisan workshop", "gelato ice cream making tasting", "smoked fish market traditional", "rural village market fresh produce", "street food vendor cooking stalls", "traditional sweet bakery confectionery", "pickled vegetables artisan jars", "cider orchard pressing fresh apples", "charcuterie cured meats artisan", "fresh sushi market preparation", "tapas crawl local food walk", "local food culture tasting tour", "street food satay skewered meat", "matcha green tea ceremony preparation", "fresh coconut water market street", "traditional pretzel bakery hand twisted", "roasted chestnuts street food", "crepe making french street food" ], "cooking": [ "home cooking simple delicious recipe", "traditional pasta dough from scratch", "campfire outdoor cooking nature", "sourdough bread baking technique", "authentic curry cooking spices recipe", "wok stir fry cooking technique", "wood fired pizza baking homemade", "barbecue smoking grilling techniques", "vegan plant based cooking recipe", "homemade soup stew winter recipe", "pastry dough baking tutorial", "chef knife cutting technique culinary", "fermentation cooking kimchi sourdough", "traditional dessert baking recipe", "sauce making culinary tutorial", "roasting vegetables cast iron skillet", "traditional risotto creamy arborio", "fresh sourdough focaccia herbs", "homemade dumplings wrapping folding", "rustic bread dutch oven baking", "slow cooked braised beef pot", "making fresh gnocchi potato dough", "cast iron skillet searing steak", "baking homemade fruit pie crust", "traditional noodle soup broth simmer", "creamy soup from scratch blender", "grilling fresh fish outdoor barbecue", "homemade sourdough cinnamon rolls", "vegetable curry rich coconut milk", "pan frying crispy tofu garlic", "making homemade mayonnaise emulsion", "artisan sourdough loaf scoring ear", "cooking grains pilaf aromatics", "steaming buns homemade dough filling", "traditional apple pie spices baking", "making homemade pesto mortar pestle", "homemade jam fruit pectin canning", "simmering tomato marinara fresh basil", "searing scallops brown butter pan", "baking sourdough baguettes shaping" ], "sports": [ "skateboarding street tricks skatepark", "rock climbing bouldering outdoors", "ocean surfing waves riding", "street basketball drills tournament", "cycling road bike mountain trail", "trail running marathon trail workout", "martial arts judo karate training", "calisthenics bodyweight workout park", "snowboarding powder mountain slope", "kayaking river paddling rapids", "table tennis ping pong rally drills", "athletics track field sprinting jumps", "badminton competitive rally training", "archery traditional bow practice", "rowing crew lake training session", "swimming freestyle technique drills", "freestyle bmx bike stunts park", "downhill mountain biking forest trail", "windsurfing coastal ocean breeze", "parkour free running city obstacles", "boxing sparring footwork training", "gymnastics floor routine practice", "weightlifting clean and jerk technique", "volleyball beach jump serve spikes", "fencing sword foil training practice", "tennis baseline rally cross court", "longboarding downhill speed cruise", "scuba diving open water buoyancy", "stand up paddleboarding calm bay", "ice skating figure spirals jumps", "climbing lead wall belaying indoor", "taekwondo kicking forms sparring", "sprint hurdles track athletics", "rugby passing drills tackle training", "cricket batting bowling practice net", "field hockey stick handling skills", "trail ultramarathon scenic running", "disc golf driving putting technique", "inline skating rollerblading street", "canoeing wilderness lake expedition" ], "music": [ "acoustic fingerstyle guitar performance", "classical piano solo recital", "ambient synthesizer generative music", "lofi hip hop beat production session", "drum solo groove percussion technique", "violin cello duet harmony acoustic", "modular synth electronic live patch", "traditional folk acoustic instruments", "electric bass groove slap line", "orchestral chamber strings rehearsal", "jazz saxophone improvisation session", "kalimba thumb piano calming melody", "harp acoustic instrumental performance", "flute instrumental soothing meditation", "handpan percussion melodic rhythm", "classical acoustic nylon guitar solo", "analog synthesizer sequence drone", "upright double bass jazz pizzicato", "tabla rhythm classical percussion solo", "banjo clawhammer traditional folk tune", "mandolin acoustic bluegrass picking", "trumpet jazz solo improvisation mute", "marimba wooden mallet percussion", "accordion traditional folk melodic playing", "slide blues guitar acoustic resonator", "pipe organ cathedral acoustics prelude", "dulcimer hammer acoustic folk tune", "clarinet woodwind classical solo", "djembe west african drumming groove", "cello suite classical performance", "fingerpicking acoustic blues rhythm", "chilled guitar chords pedalboard loop", "ambient piano tape loop reverberation", "vibraphone jazz harmony four mallets", "didgeridoo circular breathing drone", "bouzouki greek acoustic folk instrument", "oud middle eastern traditional lute", "recorder baroque woodwind melody", "pedal steel guitar country swells", "hang drum sound bath meditation" ], "dance": [ "contemporary lyrical dance choreography", "street hip hop breakdance routine", "classical ballet rehearsal barre studio", "traditional cultural folk dance performance", "salsa bachata latin social dance", "irish step dance tap rhythmic", "flamenco spanish guitar dance", "urban freestyle dance studio battle", "swing lindy hop social dance", "argentine tango partner dance", "popping locking funk dance", "indian classical kathak bharatanatyam", "modern jazz dance combination", "tap dance rhythmic footwork", "ballroom waltz standard dance", "belly dance middle eastern classical", "afrobeats dance choreography routine", "house dance footwork club style", "k-pop dance practice cover studio", "capoeira martial dance flow rodas", "ballet pointe work variation studio", "traditional scottish highland dancing", "polynesian hula cultural dance", "contemporary floorwork expressive release", "krump dance session freestyle energy", "cha cha cha ballroom latin rhythm", "vogue ballroom dance hands performance", "georgian folk dance athletic jumps", "flamenco zapateado footwork rhythm", "street dance locking fundamentals studio", "cuban rumba traditional afro dance", "contact improvisation dance workshop", "broadway musical theater jazz dance", "mexican folklorico traditional dress dance", "ballet allegro jumps center combination", "breakdance headspins windmilling power", "flamenco bulerias fiesta clapping", "urban choreography smooth musicality", "traditional native circle dance gathering", "baroque court historical dance recreations" ], "technology": [ "open source linux operating system", "electronics soldering circuit board repair", "3d printing timelapse functional print", "robotics arduino microcontroller project", "mechanical keyboard custom assembly build", "home server homelab network setup", "smart home automation sensors iot", "microcontroller esp32 hardware build", "computer pc hardware component build", "embedded systems hardware engineering", "vintage retro computing restoration", "diy solar battery generator build", "raspberry pi home automation projects", "fpga hardware programming tutorial", "electronics oscilloscope signal testing", "custom water cooling loop pc", "diy mechanical macro keypad build", "breadboard prototyping digital logic", "diy cnc router milling aluminum", "quadcopter drone frame building solder", "audio amplifier discrete transistors build", "network rack cable management switch", "linux desktop custom configuration dotfiles", "vintage cassette deck repair belts", "diy e-ink display clock weather", "laser engraver cutting plywood craft", "surface mount smd soldering hot air", "diy midi controller arcade buttons", "home lab virtualization server setup", "reverse engineering circuit board trace", "vintage crt monitor repair testing", "diy audio synthesizer analog oscillators", "robot arm kinematics servo motor code", "custom mechanical switches lubrication", "bench power supply calibration test", "diy spectrometer light sensor project", "amateur ham radio antenna build", "3d printer linear rails upgrade calibration", "custom nas storage server zfs build", "stepper motor driver tuning test" ], "education": [ "mathematics calculus visual geometry", "world history ancient civilizations documentary", "physics mechanics optics experiments", "linguistics language origins etymology", "philosophy ethics thought experiments", "geography cartography map projection", "astronomy planetary science universe", "microbiology cells microscope study", "economics fundamentals markets trade", "archaeology historical artifacts discovery", "environmental conservation ecosystems", "organic chemistry molecular structure", "meteorology weather systems atmosphere", "anthropology human cultural evolution", "neuroscience cognitive brain function", "linear algebra vectors matrices intuitive", "ancient mesopotamia cuneiform tablets", "thermodynamics entropy heat engine", "phonetics international phonetic alphabet", "stoicism ancient philosophical wisdom", "geology plate tectonics continental drift", "astrophysics black holes gravitational waves", "genetics dna replication transcription", "macroeconomics inflation fiscal policy", "roman empire legions engineering roads", "ecology predator prey population dynamics", "quantum mechanics schrodinger wave function", "ancient greek philosophy socrates plato", "computational complexity algorithm analysis", "marine ecology coral bleaching science", "sociology social structures networks", "paleoclimatology ice cores ancient climate", "evolutionary biology natural selection", "cognitive psychology memory perception", "medieval castle architecture siegecraft", "calculus derivatives integrals visual proof", "ancient egyptian hieroglyphs translation", "atomic structure quantum orbital shells", "comparative mythology archetypes lore", "economic history industrial revolution impact" ], "science": [ "chemical reactions color laboratory", "astrophotography deep space nebula", "fluid dynamics laminar flow vortex", "botany plant growth timelapse science", "geology rocks minerals crystallography", "neuroscience neuron synaptic signals", "optics lasers refraction experiment", "quantum physics wave particle duality", "marine biology plankton ocean study", "paleontology dinosaur fossil excavation", "atmospheric science storms lightning", "materials science metallurgy crystallization", "cellular biology mitosis microscope", "spectroscopy light spectrum analysis", "volcanology volcanic lava geology", "electrochemistry battery anode cathode", "astronomy telescope solar flare observing", "surface tension fluid droplets meniscus", "seed germination roots timelapse botany", "crystal growth under polarized microscope", "brain eeg neural oscillations waves", "interference pattern double slit laser", "superconductivity meissner effect magnet", "deep sea bioluminescence organisms", "fossil preparation clearing limestone matrix", "cloud formation convection lapse rates", "shape memory alloys nitinol phase change", "bacterial cultures agar plate streaking", "emission spectra gas discharge tubes", "igneous rock thin section microscopy", "polymer crosslinking gel synthesis", "planetary cratering impact experiments", "non newtonian fluid shear thickening cornstarch", "photosynthesis chloroplasts light reaction", "mineral fluorescence ultraviolet light minerals", "sound waves chladni plate patterns", "piezoelectric effect spark generation crystals", "magnetic levitation pyrolytic graphite", "tardigrades water bears under microscope", "stellar nucleosynthesis heavy elements cosmos" ], "diy_crafts": [ "woodworking traditional hand tools joinery", "pottery ceramics wheel throwing clay", "leathercraft handmade leather wallet", "knitting crochet yarn craft pattern", "origami geometric paper folding", "resin wood art coaster epoxy crafting", "blacksmithing forging steel iron craft", "stained glass copper foil art", "bookbinding handmade journal binding", "weaving loom handmade textile fabric", "macrame plant hanger decorative knotting", "wood carving whittling figurine handmade", "soap making cold process craft", "candle making beeswax artisanal", "mosaic tile handmade art craft", "dovetail joint sawing hand chisel", "trimming ceramic bowl pottery wheel", "hand stitching saddle stitch leather belt", "knitting cable sweater circular needles", "modular origami geometric polyhedra", "resin casting crystal silicone molds", "forging damascus steel billet anvil", "cutting colored glass lead came panel", "coptic stitch open spine bookbinding", "tabletop rigid heddle weaving scarf", "macrame wall hanging feather fringe", "carving wooden spoon gouge sloyd knife", "botanical soap swirling natural clays", "hand dipping beeswax tapers wick", "mosaic stepping stone outdoor garden", "japanese kumiko lattice woodworking", "sgraffito carving ceramic vase pottery", "burnishing leather edges beeswax tokonole", "crochet granny square blanket border", "paper quilling filigree flower art", "live edge river table resin pour", "forging hand axe hammer tongs", "glass etching stencil cream craft", "leather passport cover saddle stitched", "hand spun wool drop spindle yarn" ], "vehicles": [ "vintage classic car restoration garage", "motorcycle cafe racer custom build", "electric bicycle ebike conversion", "train locomotive driver cab view", "aviation cockpit takeoff flight instruments", "wooden sailboat coastal sailing voyage", "offroad 4x4 overland trail adventure", "small engine carburetor rebuild repair", "steam locomotive heritage railroad", "vintage scooter vespa restoration", "cargo ship container vessel maritime", "antique tractor agricultural machinery", "electric vehicle powertrain conversion", "bicycle overhaul maintenance repair", "helicopter aerial flight maneuvers", "air cooled engine rebuild vintage vw", "motorcycle carburetor tuning sync gauges", "custom ebike hub motor battery install", "high speed train rail cab ride", "glider soaring thermal wave flight", "sailboat rigging sails tacking wind", "rock crawling jeep suspension articulation", "two stroke chainsaw engine tune repair", "narrowboat canal navigation lock gates", "restoring vintage moped two stroke", "tugboat maneuvering harbor docking ship", "vintage bulldozer diesel crawler engine", "disc brake caliper overhaul bleed fluid", "truing bicycle wheel spoke wrench", "gyrocopter autogyro flight cockpit", "classic pickup truck bodywork sanding", "motorcycle fork seals fluid replacement", "recumbent touring bicycle road trip", "subway train operating cab viewpoint", "floatplane landing backcountry lake water", "sailing catamaran ocean passage trade winds", "vintage dirt bike trail ride forest", "lawn mower governor spring throttle carb", "paddle steamer paddlewheel riverboat", "vintage flathead v8 engine assembly" ], "city_life": [ "tokyo rainy night pedestrian street walk", "london rain city street atmosphere", "new york city morning street commute", "paris boulevard architecture outdoor cafe", "amsterdam canals bicycle morning commute", "berlin neighborhood street atmosphere tram", "seoul night market bustling street food", "singapore urban garden architecture walk", "melbourne laneways street art coffee", "istanbul historic street bazaar tram", "metro subway commuter transit platform", "evening sunset city skyline rooftop", "prague historic old town square walk", "chicago architectural riverfront walk", "vancouver waterfront urban streetscape", "kyoto traditional wooden street walk", "edinburgh old town rain cobblestone", "san francisco cable car street hill", "vienna historic ringstrasse tram ride", "copenhagen harbor bicycle commuter bridge", "hong kong double decker tram view", "barcelona gothic quarter alleyways stroll", "stockholm gamla stan stone streets", "toronto downtown streetcar transit morning", "montreal plateau historic spiral stairs", "lisbon yellow tram 28 hills ride", "dublin temple bar street buskers", "budapest historic tram along danube", "rome piazza fountains evening passeggiata", "seattle pike place market morning flowers", "milan galleria historic arcade walk", "taipei night market neon alleys", "osaka dotonbori canal signs stroll", "munich marienplatz glockenspiel square", "boston historic beacon hill brick streets", "taipei scooter morning commute rush", "helsinki seaside tram quiet morning", "brussels grand place gilded facades", "mexico city reforma boulevard cycling", "zurich limmat river bridge old town" ], "festivals_culture": [ "traditional lantern festival night celebration", "cultural street carnival festive costumes", "spring harvest flower festival celebration", "indigenous tribal cultural heritage ceremony", "dragon boat festival drums racing", "mid autumn moon festival traditions", "folk costume historical cultural pageant", "solstice bonfire celebration tradition", "winter ice snow sculpture festival", "cultural music percussion festival crowd", "temple festival fair cultural rituals", "traditional mask dance ancient ritual", "cherry blossom hanami spring celebration", "carnival parade masquerade dancers", "traditional pottery fair artisan festival", "floating water lanterns river ceremony", "street puppet parade giant marionettes", "autumn grape harvest crushing festival", "cultural traditional drumming ensemble gathering", "traditional boat regatta historical banners", "full moon night cultural temple dances", "medieval renaissance fair costumes archery", "midsummer pole floral wreath festival", "ice lantern illuminated winter wonderland", "brass band street procession festival", "folk dance circle accordion festivity", "cultural heritage craft market bazaar", "traditional paper lantern release sky", "harvest festival wheat sheaf ceremony", "ancestral ceremonial chanting rituals", "spring equinox outdoor nature ritual", "cultural dance competition tribal regalia", "historic boat blessing sea ceremony", "flower carpet street processional festival", "traditional kite flying wind festival", "candlelight cathedral choral celebration", "cultural festival street food tents", "traditional bell ringing village feast", "sacred grove nature pilgrimage gathering", "sun dance indigenous cultural traditions" ], "fashion": [ "sustainable slow fashion vintage wardrobe", "textile handloom weaving traditional fabric", "couture garment pattern sewing crafting", "traditional ethnic attire cultural clothing", "bespoke leather shoe shoemaking cordwainer", "runway street style outfit aesthetic", "hand knit wool sweater craftsmanship", "natural botanical indigo fabric dyeing", "vintage thrift clothing haul styling", "historical period costume tailoring", "millinery handmade wool felt hat", "embroidery hand needlework stitching", "leather bag handmade artisan leathercraft", "silk screen printing textile garment", "sustainable upcycled fashion design", "capsule wardrobe styling mix match", "backstrap loom ethnic weaving textile", "draping dress form muslin garment pattern", "traditional kimono dressing silk obi", "hand welted leather shoe stitching", "autumn layers thrifted outfits lookbook", "hand spinning wool roving wheel yarn", "shibori tie dye folding indigo vat", "styling vintage tweed wool coats", "corset making boning historical sewing", "blocking wool felt hat crown brim", "goldwork embroidery bullion metal threads", "stitching leather tote bag copper rivets", "block printing botanical motifs fabric", "reworking denim jeans upcycle jacket", "minimalist wardrobe aesthetic styling tips", "hand woven tartan wool loom shuttle", "sewing tailored wool blazer lapel canvas", "traditional hanbok silk ribbons attire", "wooden lasts bespoke shoemaking rasps", "monochrome minimalist outfit lookbook", "fair isle stranded colorwork knitting", "natural plant dyeing onion skin madder", "restoring vintage leather boots polish", "victorian dress historical sewing replica" ], "art": [ "oil painting landscape alla prima timelapse", "watercolor painting wet on wet landscape", "clay sculpture modeling studio bust", "charcoal portrait drawing studio sketch", "linocut printmaking block carving ink", "calligraphy brush pen lettering script", "street art mural aerosol spray paint", "botanical illustration gouache painting", "pottery glazing ceramic kiln firing", "pastel plein air landscape sketch", "intaglio copper etching printmaking", "sketchbook tour pen ink illustrations", "acrylic fluid pouring abstract art", "woodblock carving traditional printmaking", "mosaic glass ceramic tile installation", "palette knife oil painting impasto thick", "watercolor painting mountain mist layering", "sculpting figurative anatomy armature clay", "graphite pencil realistic eye shading", "reduction linocut printing multiple layers", "broad edge calligraphy copperplate italic", "trompe loeil perspective wall mural", "gouache painting landscape color harmony", "raku pottery outdoor smoking firing", "soft pastel atmospheric landscape blending", "drypoint etching printing intaglio press", "urban sketching pen wash buildings", "acrylic painting abstract geometric shapes", "japanese woodblock moku hanga printing", "glass fusing kiln glass art jewelry", "alla prima still life fruit oil painting", "watercolor skies clouds wet on wet", "stone carving chisel mallet sculpture", "pen and ink cross hatching drawing", "screen printing art print poster ink", "gothic calligraphy illuminated manuscript gilt", "plein air outdoor oil painting easel", "gouache color mixing landscape studies", "ceramic stoneware pottery wheel trimming", "conte crayon gesture figure drawing quick" ], "gaming": [ "indie adventure game exploration showcase", "retro 16 bit game speedrun walkthrough", "sandbox simulation creative building timelapse", "realistic flight simulator instrument approach", "chess strategic endgame puzzle analysis", "virtual reality vr interactive gameplay", "isometric strategy game base construction", "tabletop miniature board game strategy", "pixel art indie game devlog mechanics", "space flight simulator planetary orbital", "physics puzzle mechanics walkthrough", "racing simulator cockpit steering wheel", "city builder simulation management", "turn based strategy tactical gameplay", "rpg role playing indie game quests", "point and click adventure puzzle solution", "classic arcade game high score playthrough", "voxel sandbox terraforming world building", "glider sailplane soaring simulator flight", "classical chess grandmaster game commentary", "vr room scale physics interaction demo", "factory automation logistics game build", "miniature painting tabletop wargame terrain", "2d metroidvania platformer mechanics demo", "space station orbital docking simulator", "bridge building engineering puzzle sim", "rally racing simulator gravel drift turns", "medieval town colony survival builder", "tactical deckbuilding card game synergies", "cooperative puzzle solving mechanics indie", "text parser retro adventure gameplay", "bullet hell shmup dodging patterns", "isometric tycoon theme park ride building", "instrument flight ifr bad weather simulator", "chess opening preparation deep theory", "vr bow and arrow archery target mechanic", "transport tycoon railway logistics route", "board game rule explanation playthrough", "pixel art roguelike dungeon crawl run", "submariner naval simulator sonar navigation" ], "everyday_scenes": [ "gentle rain against window cozy room", "morning coffee brewing pour over ritual", "quiet library bookshelves study ambience", "autumn leaves falling quiet park walkway", "neighborhood morning farmers market stalls", "countryside garden tending vegetable patch", "baking sourdough kitchen quiet afternoon", "train window view passing countryside hills", "quiet evening dinner cooking routine", "wooden front porch summer evening breeze", "lakeside wooden dock morning mist quiet", "cat resting sunny windowsill quiet room", "wood burning fireplace warm winter hearth", "morning sunrise quiet street awakening", "potting plants greenhouse quiet gardening", "quiet bookstore browsing shelves afternoon", "walking countryside gravel lane hedgerows", "snow gently falling quiet courtyard night", "cup of herbal tea steaming reading book", "ironing crisp linen shirt morning routine", "wooden boat moored calm harbor morning", "winding country road cyclist morning mist", "sunlight streaming through sheer curtains room", "tending backyard compost soil planting", "quiet workshop sharpening chisels whetstone", "morning birds singing green garden dawn", "hanging fresh laundry outside gentle wind", "rain puddles quiet alleyway reflection", "quiet riverbank willow trees afternoon rest", "reading paperback armchair natural light", "watering windowsill herbs morning sunshine", "picking ripe tomatoes vegetable garden vine", "crackle of wood fire outdoor campfire night", "folding warm blankets freshly laundered", "quiet pottery studio morning dust motes", "walking dog along quiet country path", "watching distant rain clouds over fields", "quiet evening lighting candles living room", "morning bakery sweeping storefront pavement", "quiet canal path bicycling morning air" ], "nepal_content": [ "nepali culture traditions customs heritage", "annapurna circuit mountain pass trek nepal", "everest base camp trekking trail himalayas", "kathmandu durbar square ancient temples", "pokhara phewa lake sunrise himalayas view", "nepali rural village mountain farming hills", "dashain tihar festival celebration nepal", "nepali dal bhat traditional food cooking", "upper mustang trans himalayan kingdom nepal", "bhaktapur pottery square traditional crafts", "langtang valley trek himalayan landscape", "newari traditional festivals guthi heritage", "himalayan suspension footbridge mountain trail", "ason bazar local spices market kathmandu", "tharu village culture terai nepal traditions", "patan durbar square historic architecture", "rara lake remote wilderness trekking nepal", "sherpa village life solukhumbu mountains", "nepali folk sarangi madal acoustic music", "manaslu circuit trek remote himalayan route", "gorkha historic palace mountain ridge nepal", "chitwan national park rhino elephant conservation", "bandipur preserved hilltop town traditional architecture", "tadapani sunrise view annapurna south nepal", "tamang heritage trail mountain culture homestay", "nepali sel roti traditional bread festival", "kapan monastery tibetan buddhist prayer flags", "muktinath temple sacred pilgrimage sacred springs", "khumjung village himalayan sherpa valley", "namche bazaar sherpa mountain capital trek", "nepali lokta handmade paper making artisan", "panauti ancient heritage town newari architecture", "mardi himal trek ridgeline trail view", "illam tea garden green hills east nepal", "boudhanath stupa prayer wheels kora kathmandu", "swayambhunath monkey temple stupa sunrise", "mustang ancient cave dwellings cliff walls", "gokyo lakes turquoise glacial waters himalayas", "nepali dhindo traditional meal preparation village", "helambu apple orchards mountain trekking route" ] } def parse_duration_str(dur_str: str) -> int: """Parses mm:ss, hh:mm:ss, or ISO 8601 PT#M#S to seconds.""" if not dur_str: return 0 dur_str = dur_str.strip() if dur_str.startswith("PT") or dur_str.startswith("P"): m_h = re.search(r'(\d+)H', dur_str) m_m = re.search(r'(\d+)M', dur_str) m_s = re.search(r'(\d+)S', dur_str) h = int(m_h.group(1)) if m_h else 0 m = int(m_m.group(1)) if m_m else 0 s = int(m_s.group(1)) if m_s else 0 return h * 3600 + m * 60 + s parts = dur_str.split(':') try: if len(parts) == 3: return int(parts[0]) * 3600 + int(parts[1]) * 60 + int(parts[2]) elif len(parts) == 2: return int(parts[0]) * 60 + int(parts[1]) elif len(parts) == 1: return int(parts[0]) except Exception: return 0 return 0 def parse_view_count(view_str: str) -> int: """Extracts integer view count from string (e.g., '12,500 views', '1.4M views').""" if not view_str: return 0 text = str(view_str).lower().replace(',', '').split('view')[0].strip() match = re.search(r'([\d\.]+)\s*([kmb])?', text) if not match: return 0 val, mult = match.groups() try: num = float(val) if mult == 'k': num *= 1_000 elif mult == 'm': num *= 1_000_000 elif mult == 'b': num *= 1_000_000_000 return int(num) except Exception: return 0 def parse_upload_date(date_str: str) -> str: """Parses ISO string or relative time ('2 years ago') into YYYY-MM-DD.""" if not date_str: return "2024-01-01" date_str = str(date_str).strip() iso_match = re.search(r'(\d{4}-\d{2}-\d{2})', date_str) if iso_match: return iso_match.group(1) now = datetime(2026, 10, 11) rel_match = re.search(r'(\d+)\s+(year|month|week|day|hour|minute)s?\s+ago', date_str.lower()) if rel_match: qty = int(rel_match.group(1)) unit = rel_match.group(2) if unit == 'year': dt = now.replace(year=max(2006, now.year - qty)) elif unit == 'month': total_months = now.year * 12 + now.month - qty y = total_months // 12 m = total_months % 12 or 12 dt = now.replace(year=y, month=m, day=min(now.day, 28)) elif unit == 'week': dt = now - timedelta(days=qty * 7) elif unit == 'day': dt = now - timedelta(days=qty) else: dt = now return dt.strftime("%Y-%m-%d") return "2024-06-01" def detect_language(title: str, description: str, category: str) -> str: """Infers language code (e.g. 'ne', 'en', 'es', 'ja').""" full_text = f"{title} {description}" if re.search(r'[\u0900-\u097F]', full_text) or category == "nepal_content": if re.search(r'[\u0900-\u097F]', full_text) or any(w in full_text.lower() for w in ["nepal", "nepali", "kathmandu", "pokhara", "himalaya"]): return "ne" if re.search(r'[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff]', full_text): return "ja" if re.search(r'[\uac00-\ud7af]', full_text): return "ko" if re.search(r'[\u0400-\u04FF]', full_text): return "ru" return "en" class ResumableStorage: """Manages SQLite storage for resume capability.""" def __init__(self, db_path: str = "dataset.db"): self.db_path = db_path self._init_db() def _init_db(self): with sqlite3.connect(self.db_path) as conn: conn.execute(""" CREATE TABLE IF NOT EXISTS videos ( video_id TEXT PRIMARY KEY, url TEXT, title TEXT, description TEXT, channel_name TEXT, channel_id TEXT, category TEXT, duration_seconds INTEGER, language TEXT, upload_date TEXT, view_count INTEGER, license TEXT, tags TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) conn.execute(""" CREATE TABLE IF NOT EXISTS quota_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT UNIQUE, units_used INTEGER, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) conn.commit() def has_video(self, video_id: str) -> bool: with sqlite3.connect(self.db_path) as conn: cursor = conn.cursor() cursor.execute("SELECT 1 FROM videos WHERE video_id = ?", (video_id,)) return cursor.fetchone() is not None def save_batch(self, videos: List[Dict[str, Any]]) -> int: if not videos: return 0 inserted = 0 with sqlite3.connect(self.db_path) as conn: for v in videos: tags_str = json.dumps(v.get("tags", [])) if isinstance(v.get("tags"), list) else str(v.get("tags", "")) desc_500 = str(v.get("description", ""))[:500] try: conn.execute(""" INSERT OR IGNORE INTO videos ( video_id, url, title, description, channel_name, channel_id, category, duration_seconds, language, upload_date, view_count, license, tags ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( v["video_id"], v["url"], v["title"], desc_500, v["channel_name"], v["channel_id"], v["category"], int(v["duration_seconds"]), v["language"], v["upload_date"], int(v["view_count"]), v["license"], tags_str )) inserted += 1 except Exception: pass conn.commit() return inserted def count_by_category(self) -> Dict[str, int]: with sqlite3.connect(self.db_path) as conn: cursor = conn.cursor() cursor.execute("SELECT category, COUNT(*) FROM videos GROUP BY category") return dict(cursor.fetchall()) def total_count(self) -> int: with sqlite3.connect(self.db_path) as conn: cursor = conn.cursor() cursor.execute("SELECT COUNT(*) FROM videos") return cursor.fetchone()[0] def fetch_all(self) -> List[Dict[str, Any]]: with sqlite3.connect(self.db_path) as conn: conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute(""" SELECT video_id, url, title, description, channel_name, channel_id, category, duration_seconds, language, upload_date, view_count, license, tags FROM videos ORDER BY category, upload_date DESC """) rows = cursor.fetchall() results = [] for r in rows: item = dict(r) try: item["tags"] = json.loads(item["tags"]) except Exception: item["tags"] = [t.strip() for t in item["tags"].split(",") if t.strip()] results.append(item) return results class CreativeCommonsDirectClient: """Direct Creative Commons YouTube client using YouTube's CC filter ('EgIwAQ==').""" def __init__(self): self.url = "https://www.youtube.com/youtubei/v1/search?prettyPrint=false" self.headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36", "Content-Type": "application/json", "Accept-Language": "en-US,en;q=0.9" } def search_query(self, query: str, max_pages: int = 3) -> List[Dict[str, Any]]: videos = [] continuation_token = None for page in range(max_pages): if continuation_token: payload = { "context": {"client": {"clientName": "WEB", "clientVersion": "2.20240201.00.00"}}, "continuation": continuation_token } else: payload = { "context": {"client": {"clientName": "WEB", "clientVersion": "2.20240201.00.00"}}, "query": query, "params": "EgIwAQ==" } try: req = urllib.request.Request(self.url, data=json.dumps(payload).encode("utf-8"), headers=self.headers) with urllib.request.urlopen(req, timeout=10) as resp: res = json.loads(resp.read().decode("utf-8")) except Exception: break continuation_token = None if page == 0: section_list = res.get("contents", {}).get("twoColumnSearchResultsRenderer", {}).get("primaryContents", {}).get("sectionListRenderer", {}).get("contents", []) for section in section_list: items = section.get("itemSectionRenderer", {}).get("contents", []) for item in items: if "videoRenderer" in item: parsed = self._extract(item["videoRenderer"]) if parsed: videos.append(parsed) if "continuationItemRenderer" in section: continuation_token = section["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"] else: commands = res.get("onResponseReceivedCommands", []) for cmd in commands: actions = cmd.get("appendContinuationItemsAction", {}).get("continuationItems", []) for action in actions: if "itemSectionRenderer" in action: for it in action["itemSectionRenderer"].get("contents", []): if "videoRenderer" in it: parsed = self._extract(it["videoRenderer"]) if parsed: videos.append(parsed) elif "videoRenderer" in action: parsed = self._extract(action["videoRenderer"]) if parsed: videos.append(parsed) elif "continuationItemRenderer" in action: continuation_token = action["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"] if not continuation_token: break return videos def _extract(self, vr: Dict[str, Any]) -> Optional[Dict[str, Any]]: vid_id = vr.get("videoId") if not vid_id: return None title_runs = vr.get("title", {}).get("runs", []) title = "".join([r.get("text", "") for r in title_runs]).strip() if not title: return None dur_str = vr.get("lengthText", {}).get("simpleText", "") duration_seconds = parse_duration_str(dur_str) # Filters: 5s to 20m (1200s) if duration_seconds < 5 or duration_seconds > 1200: return None owner_runs = vr.get("ownerText", {}).get("runs", []) channel_name = "".join([r.get("text", "") for r in owner_runs]).strip() or "YouTube Creator" channel_endpoint = owner_runs[0].get("navigationEndpoint", {}).get("browseEndpoint", {}) if owner_runs else {} channel_id = channel_endpoint.get("browseId", f"UC_{vid_id[:8]}") desc = "" snippets = vr.get("detailedMetadataSnippets", []) if snippets: desc_runs = snippets[0].get("snippetText", {}).get("runs", []) desc = "".join([r.get("text", "") for r in desc_runs]).strip() if not desc: desc_runs = vr.get("descriptionSnippet", {}).get("runs", []) desc = "".join([r.get("text", "") for r in desc_runs]).strip() views_str = vr.get("viewCountText", {}).get("simpleText", "") if not views_str and "shortViewCountText" in vr: views_str = vr["shortViewCountText"].get("simpleText", "") view_count = parse_view_count(views_str) published_text = vr.get("publishedTimeText", {}).get("simpleText", "") upload_date = parse_upload_date(published_text) return { "video_id": vid_id, "url": f"https://www.youtube.com/watch?v={vid_id}", "title": title, "description": desc[:500], "channel_name": channel_name, "channel_id": channel_id, "duration_seconds": duration_seconds, "upload_date": upload_date, "view_count": view_count, "license": "Creative Commons (CC-BY)" } class YouTubeDataAPIClient: """Official YouTube Data API v3 client with quota tracking.""" def __init__(self, api_key: str, storage: ResumableStorage): self.api_key = api_key self.storage = storage self.base_url = "https://www.googleapis.com/youtube/v3" def search_creative_commons(self, query: str, max_results: int = 50, page_token: Optional[str] = None) -> Dict[str, Any]: params = { "part": "snippet", "q": query, "type": "video", "videoLicense": "creativeCommon", "maxResults": min(max_results, 50), "key": self.api_key } if page_token: params["pageToken"] = page_token url = f"{self.base_url}/search?{urllib.parse.urlencode(params)}" req = urllib.request.Request(url, headers={"User-Agent": "YouTubeDataCollector/1.0"}) try: with urllib.request.urlopen(req, timeout=15) as resp: return json.loads(resp.read().decode("utf-8")) except Exception as e: return {"items": [], "error": str(e)} def get_video_details(self, video_ids: List[str]) -> List[Dict[str, Any]]: if not video_ids: return [] results = [] for i in range(0, len(video_ids), 50): batch = video_ids[i:i + 50] params = { "part": "snippet,contentDetails,statistics,status", "id": ",".join(batch), "key": self.api_key } url = f"{self.base_url}/videos?{urllib.parse.urlencode(params)}" req = urllib.request.Request(url, headers={"User-Agent": "YouTubeDataCollector/1.0"}) try: with urllib.request.urlopen(req, timeout=15) as resp: data = json.loads(resp.read().decode("utf-8")) results.extend(data.get("items", [])) except Exception: pass return results class DatasetBuilder: """Master orchestrator.""" def __init__(self, target_per_category: int = 730, output_dir: str = "."): self.target_per_category = target_per_category self.output_dir = output_dir self.storage = ResumableStorage(os.path.join(output_dir, "dataset.db")) self.api_key = os.environ.get("YOUTUBE_API_KEY") self.api_client = YouTubeDataAPIClient(self.api_key, self.storage) if self.api_key else None self.direct_client = CreativeCommonsDirectClient() def run(self): print("=" * 65) print("šŸŽ„ Creative Commons YouTube Dataset Builder (~14k-15k Videos)") print(f"šŸŽÆ Target per Category: {self.target_per_category} (Total: {self.target_per_category * 20:,})") print(f"šŸ”‘ YouTube API Key: {'Active (Data API v3)' if self.api_key else 'Not set (using Direct CC Engine)'}") print(f"šŸ’¾ Storage Database: {self.storage.db_path}") print("=" * 65) # Check existing count counts = self.storage.count_by_category() total_now = self.storage.total_count() print(f"šŸ“Š Starting with {total_now:,} videos in database.") # Build list of work items: (category, query) work_items = [] for category, queries in CATEGORIES.items(): have = counts.get(category, 0) if have < self.target_per_category: for q in queries: work_items.append((category, q)) print(f"⚔ Executing {len(work_items)} query pipelines across categories concurrently...") # Run with ThreadPoolExecutor with ThreadPoolExecutor(max_workers=16) as executor: future_to_item = { executor.submit(self._fetch_query, category, query): (category, query) for category, query in work_items } completed = 0 for future in as_completed(future_to_item): cat, q = future_to_item[future] completed += 1 try: candidates = future.result() if candidates: # Process and save to_save = [] for v in candidates: v["category"] = cat v["language"] = detect_language(v["title"], v["description"], cat) v["tags"] = [word.lower() for word in re.findall(r'\b[a-zA-Z]{3,}\b', v["title"])[:8]] to_save.append(v) self.storage.save_batch(to_save) except Exception as e: pass if completed % 50 == 0 or completed == len(work_items): cur_tot = self.storage.total_count() print(f" [{completed}/{len(work_items)} queries processed] Total unique videos: {cur_tot:,}") # Summary and Exporters self.print_summary() self.export_metadata_files() self.generate_readme() def _fetch_query(self, category: str, query: str) -> List[Dict[str, Any]]: # Check if category already reached target cur_count = self.storage.count_by_category().get(category, 0) if cur_count >= self.target_per_category: return [] return self.direct_client.search_query(query, max_pages=3) def print_summary(self): counts = self.storage.count_by_category() total = self.storage.total_count() print("\n" + "=" * 65) print("šŸ“ˆ FINAL DATASET SUMMARY BY CATEGORY") print("=" * 65) print(f"{'Category':<25} | {'Count':<10} | {'Percentage':<10}") print("-" * 65) for cat in sorted(CATEGORIES.keys()): cnt = counts.get(cat, 0) pct = (cnt / total * 100) if total > 0 else 0 print(f"{cat:<25} | {cnt:<10} | {pct:>6.2f}%") print("-" * 65) print(f"{'TOTAL UNIQUE VIDEOS':<25} | {total:<10} | 100.00%") print("=" * 65) def export_metadata_files(self): all_videos = self.storage.fetch_all() print(f"\nšŸ’¾ Exporting {len(all_videos):,} records to metadata.jsonl and metadata.csv...") jsonl_path = os.path.join(self.output_dir, "metadata.jsonl") csv_path = os.path.join(self.output_dir, "metadata.csv") # 1. JSONL Export with open(jsonl_path, "w", encoding="utf-8") as f_jsonl: for item in all_videos: f_jsonl.write(json.dumps(item, ensure_ascii=False) + "\n") print(f"āœ“ Saved JSONL: {jsonl_path} ({os.path.getsize(jsonl_path) / (1024*1024):.2f} MB)") # 2. CSV Export fieldnames = [ "video_id", "url", "title", "description", "channel_name", "channel_id", "category", "duration_seconds", "language", "upload_date", "view_count", "license", "tags" ] with open(csv_path, "w", encoding="utf-8", newline="") as f_csv: writer = csv.DictWriter(f_csv, fieldnames=fieldnames) writer.writeheader() for item in all_videos: row = dict(item) if isinstance(row.get("tags"), list): row["tags"] = ", ".join(row["tags"]) writer.writerow(row) print(f"āœ“ Saved CSV: {csv_path} ({os.path.getsize(csv_path) / (1024*1024):.2f} MB)") def generate_readme(self): readme_path = os.path.join(self.output_dir, "README.md") counts = self.storage.count_by_category() total = self.storage.total_count() rows_table = "" for cat in sorted(CATEGORIES.keys()): cnt = counts.get(cat, 0) rows_table += f"| `{cat}` | {cnt:,} |\n" readme_content = f"""--- license: cc-by-4.0 task_categories: - video-classification - feature-extraction - text-to-video language: - en - ne tags: - youtube - creative-commons - video-links - multimodal - metadata size_categories: - 10K āš ļø **Important Legal & Attribution Notice:** > **Links and metadata only, no video files included. Each video keeps its original Creative Commons license; credit the creators.** --- ## šŸ“Œ Dataset Overview * **Total Unique Videos:** `{total:,}` * **License:** Creative Commons (CC-BY) * **Categories:** 20 balanced categories * **Formats Provided:** `metadata.jsonl` and `metadata.csv` * **Duration Constraints:** Filtered between 5 seconds and 20 minutes (no ultra-short clips, no long streams) * **Deduplication:** 100% deduplicated by unique `video_id` --- ## šŸ—‚ļø Categories & Distribution | Category | Video Count | |:---|---:| {rows_table}| **Total** | **{total:,}** | --- ## šŸ·ļø Field Explanations Each record in `metadata.jsonl` and `metadata.csv` provides the following 13 metadata fields: | Field Name | Type | Description | |:---|:---|:---| | `video_id` | `string` | Unique 11-character YouTube video identifier | | `url` | `string` | Canonical watch URL (`https://www.youtube.com/watch?v=...`) | | `title` | `string` | Full video title | | `description` | `string` | Video description (first 500 characters) | | `channel_name` | `string` | Name of the YouTube channel/creator | | `channel_id` | `string` | Unique YouTube channel identifier | | `category` | `string` | Assigned content category (e.g. `nature`, `nepal_content`, `science`) | | `duration_seconds` | `integer` | Video length in seconds (5s to 1200s) | | `language` | `string` | Inferred language tag (`en`, `ne`, etc.) | | `upload_date` | `string` | Upload date in ISO format (`YYYY-MM-DD`) | | `view_count` | `integer` | Recorded view count | | `license` | `string` | `Creative Commons (CC-BY)` | | `tags` | `list / string` | Topical keywords associated with the video | --- ## šŸ’» Quickstart: Load Dataset via Hugging Face `datasets` ```python from datasets import load_dataset # Load from Hugging Face dataset = load_dataset("sushan98/youtube-creative-commons-15k", split="train") print(f"Loaded {{len(dataset):,}} video metadata records!") sample = dataset[0] print("Sample video:", sample["title"], "->", sample["url"]) ``` --- ## ā¬‡ļø How to Download Videos with `yt-dlp` You can download videos or extract audio using [`yt-dlp`](https://github.com/yt-dlp/yt-dlp). ### 1. Download a Single Video (720p/1080p MP4): ```bash yt-dlp -f "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best" "https://www.youtube.com/watch?v=VIDEO_ID" ``` ### 2. Download from `metadata.jsonl` using Python: ```python import json import subprocess with open("metadata.jsonl", "r", encoding="utf-8") as f: for line in f: item = json.loads(line) url = item["url"] category = item["category"] print(f"Downloading CC video [{{category}}]: {{item['title']}}") # Download at max 720p to save space subprocess.run([ "yt-dlp", "-f", "bestvideo[height<=720]+bestaudio/best[height<=720]", "-o", f"downloads/{{category}}/%(id)s.%(ext)s", "--max-filesize", "100M", url ]) break # Remove to download more ``` --- ## šŸ›”ļø License and Usage Links and metadata only, no video files included. Each video keeps its original Creative Commons license; credit the creators. """ with open(readme_path, "w", encoding="utf-8") as f: f.write(readme_content) print(f"āœ“ Saved Dataset Card: {readme_path}") def upload_to_huggingface(repo_id: str, local_dir: str): """Uploads dataset files to Hugging Face dataset repository.""" token = os.environ.get("HF_TOKEN") if not token: print("[Upload Warning] HF_TOKEN not found in environment or .env. Skipping upload.") return None try: from huggingface_hub import HfApi api = HfApi(token=token) print(f"\nšŸš€ Creating/verifying public Hugging Face dataset repository: {repo_id}...") api.create_repo(repo_id=repo_id, repo_type="dataset", private=False, exist_ok=True) files_to_upload = ["metadata.jsonl", "metadata.csv", "README.md", "collector.py"] for fname in files_to_upload: fpath = os.path.join(local_dir, fname) if os.path.exists(fpath): print(f" ā¬†ļø Uploading {fname} ({os.path.getsize(fpath) / (1024*1024):.2f} MB)...") api.upload_file( path_or_fileobj=fpath, path_in_repo=fname, repo_id=repo_id, repo_type="dataset", commit_message=f"Upload {fname} for {repo_id}" ) dataset_url = f"https://huggingface.co/datasets/{repo_id}" print(f"\nšŸŽ‰ Successfully uploaded dataset to Hugging Face!") print(f"šŸ”— Dataset URL: {dataset_url}") return dataset_url except Exception as e: print(f"[Upload Error] {e}") return None if __name__ == "__main__": parser = argparse.ArgumentParser(description="Creative Commons YouTube Dataset Builder") parser.add_argument("--target", type=int, default=730, help="Target videos per category (default: 730 = ~14,600 total)") parser.add_argument("--repo-id", type=str, default="sushan98/youtube-creative-commons-15k", help="Hugging Face repo ID") parser.add_argument("--no-upload", action="store_true", help="Skip Hugging Face upload") args = parser.parse_args() builder = DatasetBuilder(target_per_category=args.target, output_dir=os.path.dirname(os.path.abspath(__file__))) builder.run() if not args.no_upload: upload_to_huggingface(args.repo_id, os.path.dirname(os.path.abspath(__file__)))