Upload tag_definition.ipynb
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "g4pG9wFdvyb5" }, "outputs": [], "source": [] }, { "cell_type": "markdown", "source": [ "# Tag definition" ], "metadata": { "id": "9lxGwaSaldYK" } }, { "cell_type": "code", "source": [ "# Install the datasets library (only needed once per runtime)\n", "!pip install -q datasets\n", "\n", "from datasets import load_dataset\n", "import random\n", "\n", "# Load the dataset\n", "print(\"Downloading dataset... (this may take a minute)\")\n", "ds = load_dataset(\"lylogummy/danbooru_wikis_2026\", split=\"train\")\n", "\n", "print(f\"Total rows loaded: {len(ds)}\")\n", "\n", "# Filter out deleted entries and entries without a title or body\n", "filtered = [\n", " item for item in ds\n", " if not item.get(\"is_deleted\", False)\n", " and item.get(\"title\")\n", " and item.get(\"body\")\n", " and str(item[\"body\"]).strip()\n", "]\n", "\n", "print(f\"Valid tag definitions after filtering: {len(filtered)}\")\n", "\n", "# Select 30 random items\n", "random_items = random.sample(filtered, 30)\n", "\n", "print(\"\\n\" + \"=\"*80)\n", "print(\"30 Random Tag Definitions\")\n", "print(\"=\"*80 + \"\\n\")\n", "\n", "for i, item in enumerate(random_items, 1):\n", " tag_name = item[\"title\"]\n", " definition = str(item[\"body\"]).strip()\n", "\n", " # Clean up the definition a bit (optional - removes excessive newlines)\n", " definition = \" \".join(definition.split())\n", "\n", " print(f\"{i}. The {tag_name} tag means this image has {definition}\")\n", " print(\"-\" * 80)" ], "metadata": { "id": "uefoU4mllfZA", "outputId": "5037ee4a-c498-4eb2-eb7c-d36637ed9266", "colab": { "base_uri": "https://localhost:8080/", "height": 1000, "referenced_widgets": [ "362c4d929042470c92f34b999fedff0b", "965e86e55a5a44c48f7c921d0d49eee3", "6b4ebcf1352f4f03beef840b3f84ce8a", "0d96d2d9d61243ba912d2ac952baa826", "887c9d26c88d494e8c4710acb9f66106", "ad2536e9e3d1406b92100696cd03d52c", "e3c071686d7a4855a8e39a893125fa92", "b3f0288f32e242d6b5f2157587b9b9d8", "888a0391913b45f696182701c3f4891a", "489e276524f5416fb24b70ce89e8e5f0", "9ea8a24645d94bd78bab8d87a71f262e", "0323c9bac21d435da1b62cf369ae2f63", "457dba8f7bcd438aa0ce168d8e57a439", "12f0337f75134f14a6032df2bb57464a", "e2adf5f23fe04d209723a7fe6b9135bb", "abafd0f258ad4d90b674e0350c06a8be", "f454375c38a44264bd29ee0f248593d0", "03673f2685e8434a92425747097886d4", "7472545a3310481e95f40cb32fd56ae1", "10724ecbca8c4a5194ac3489b67ed040", "55e103b16f0f46c38c213125783d614a", "223c9233e1184ab9a51e37431cb863d7", "0a2724b7b9e0465f90e771b6dedc977e", "02acd68608ff4a2d8c19b4f45fe33e9c", "8381c531af5c49139e862fb8fe6b0f31", "2c1701dde40840dfa97f87a29652cbaf", "91274fb464cb42568546aff07dcb9951", "d7c0aecfeabe4feab808bed43a775e56", "30cf87432d72440b8b14635e921cb071", "e4980900204e457286a1ff541096800a", "fb16a45e49c04b72b880ff4ced9914f7", "dcb36981e96a4dc99ed8fe14f6f02fc6", "a34c9b3c3cdd4e4e91a1d277e2b31320", "0b95605db36e42deb2d099c9838294d2", "59dc946e78ea4b569650ae6515d45d83", "20c550e3ebf54f0a8f0f1ffbfb42dbb3", "575d63e54017469bb5a8465dbe6bc65c", "962578f15ff642179d81a4040c15ed27", "a4047d030bc64c2987cb73c401598a09", "12e4aa121fd14db0998c8b5d41e57e7c", "d1d44bc2cf9646b8a3a27fc49e00d3ce", "23980c0908794a56b6a977958a7d6c5e", "14f174b423db43e2a0e720e1e6acf895", "daf1bb1e80e34e89bfba450bf14e0a82" ] } }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Downloading dataset... (this may take a minute)\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "README.md: 0%| | 0.00/462 [00:00<?, ?B/s]" ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "362c4d929042470c92f34b999fedff0b" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "wiki_pages_260310.parquet: reconstructing file: 0%| | 0.00B / 53.1MB " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "0323c9bac21d435da1b62cf369ae2f63" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "wiki_pages_260310.parquet: downloading bytes: | 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "0a2724b7b9e0465f90e771b6dedc977e" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "Generating train split: 0%| | 0/268908 [00:00<?, ? examples/s]" ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "0b95605db36e42deb2d099c9838294d2" } }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "Total rows loaded: 268908\n", "Valid tag definitions after filtering: 196684\n", "\n", "================================================================================\n", "30 Random Tag Definitions\n", "================================================================================\n", "\n", "1. The sakumareiji tag means this image has Artist. Homepage: http://breakinbakery.blog77.fc2.com/ Pixiv: http://www.pixiv.net/member.php?id=541279\n", "--------------------------------------------------------------------------------\n", "2. The red_ballad_(idolmaster) tag means this image has Unit in [[Idolmaster Cinderella Girls]] composed by [[Kirino Aya]], [[Takahashi Reiko]], [[Kurokawa Chiaki]], [[Aikawa Chinatsu]], and [[Togo Ai]]. Use this tag for works featuring the unit and/or their red dress.\n", "--------------------------------------------------------------------------------\n", "3. The diane tag means this image has Ambiguous tag. Do not use. h4. See also * [[diane (monster maker)|Diane]] ([[Monster Maker]]) * [[diane (nanatsu no taizai)|Diane]] ([[Nanatsu no Taizai]])\n", "--------------------------------------------------------------------------------\n", "4. The gamayun tag means this image has Gamayun is a prophetic bird of Russian folklore. It is a symbol of wisdom and knowledge and lives on an island in the mythical east, close to paradise. She is said to spread divine messages and prophecies, as she knows everything of all creation, gods, heroes, and man.\n", "--------------------------------------------------------------------------------\n", "5. The laughing tag means this image has An involuntary reaction to a humorous comment, story, joke or situation. It can involve producing sounds from the lungs while the face and body are contorted, and bearing a wide [[smile]] to express amusement or mirth. h4. Examples * !post #8319940 h4. See also * [[giggling]] * [[stifled laugh]]\n", "--------------------------------------------------------------------------------\n", "6. The sparring_dummy tag means this image has For the classic oriental sparring dummy with branches, see [[mu ren zhuang]]. For sparring mannequins see [[mannequin]]. For jousting dummies, see [[jousting dummy]].\n", "--------------------------------------------------------------------------------\n", "7. The ginka_sima tag means this image has h4. Works * [[Axel Syrios]] ([[Holostars English]]) * [[Fate (series)|]] ** [[David (fate)|]] ** [[Gilgamesh (Caster) (fate)|]] ** [[Mandricardo (fate)|]] ** [[Marie Antoinette (fate)|]] ** [[Nebuchadnezzar II (fate)|]]\n", "--------------------------------------------------------------------------------\n", "8. The js_kongou_(kancolle) tag means this image has Artworks where [[Kantai Collection|KanColle]]'s [[Kongou (kancolle)|]] is used to represent a [[personification]] of the JMSDF guided missile destroyer [[JS Kongou]].\n", "--------------------------------------------------------------------------------\n", "9. The yane_ura tag means this image has Artist. Japanese name: 屋根裏 h4. See also * Blog: http://yane-ura.blog.so-net.ne.jp/ * Pixiv account: http://www.pixiv.net/member.php?id=243718 * Drawr account: http://drawr.net/yane-ura * Stickam account: http://www.stickam.jp/profile/yane_ura * Twitter account: http://twitter.com/yaneura\n", "--------------------------------------------------------------------------------\n", "10. The xiao_weiying_(wolf) tag means this image has [[Xiao Weiying]]'s official [[animalization]] as a [[wolf]].\n", "--------------------------------------------------------------------------------\n", "11. The yatsuzuka_spina tag means this image has Artist. Likes [[tsukumogami]]. Japanese name: 八塚 すぴな (reading is \"given\":http://c10052816.circle.ms/oc/CircleProfile.aspx as Yatsuzuka Spina) Old name: すぴな (the artist uses this spelling: \"Spina\") Circle & site name: SPINALIEN Old site name: スピンえいりあん! (Spin Alien!) h4.See also * Home page: http://spinalien.net/ * Tumblr gallery: http://spiningalien.tumblr.com/ * Pixiv account: http://www.pixiv.net/member.php?id=590460 * Tinami account: http://www.tinami.com/creator/profile/17967 * Nijie account: http://nijie.info/members.php?id=2944 * Stickam account: http://www.stickam.jp/profile/u__spina * Twitter account: http://twitter.com/spinalien * Twitpic account: http://twitpic.com/photos/spinalien * Circle.ms: http://c10229899.circle.ms/oc/CircleProfile.aspx * Old blog (dead): http://blog.spinalien.net/\n", "--------------------------------------------------------------------------------\n", "12. The diabolik_lovers tag means this image has Otome franchise centering around multiple families of vampires and a human girl with the transplanted heart of the Sakamaki family's matriarch. Produced by [[Rejet]].\n", "--------------------------------------------------------------------------------\n", "13. The magic_pen_(twisted_wonderland) tag means this image has A tool in [[Twisted Wonderland]]. It's given to students of Night Raven College in order to help channel their magic and control their blot. It physically appears as a [[pen]] with a magestone (gem) in the color associated with their dorm. It can be used as both a wand and a writing instrument. The breast pockets on the jackets of the [[Night Raven college school uniform]] and [[Night Raven College gym uniform|gym uniform]]s are designed to hold the magic pen, making it appears like a brooch. A key-shaped sheath is worn around the waist in their [[Night Raven College ceremonial robes|ceremonial robes]], and a pocket on the shoulder for their [[Night Raven College gym uniform|gym uniform]]. Instead of a magic pen, [[Grim (twisted wonderland)|]] wears his gem on a collar around his neck. [[Silver Vanrouge]]'s magic pen is larger, making it more closely resemble a dagger. [[Idia Shroud]] and [[Ortho Shroud]] do not utilize them. Students at Royal Sword Academy are shown to also keep their magestones in their lapels, but it's unclear if they also function as pens. h4. See also * [[Overblot]] h4. External links * \"Magic - Twisted Wonderland Wiki (wiki.gg)\":https://twistedwonderland.wiki.gg/wiki/Magic\n", "--------------------------------------------------------------------------------\n", "14. The kamen_rider_ghost_(series) tag means this image has The 26th installment in the [[Kamen Rider]] series, as well as the 17th entry in the Heisei era.\n", "--------------------------------------------------------------------------------\n", "15. The penis_to_breast tag means this image has A [[penis]] poking or being rubbed against a [[nipples|nipple]] or [[breasts|breast]]. h4. See also * [[Penis to pectoral]] (male equivalent)\n", "--------------------------------------------------------------------------------\n", "16. The genos tag means this image has A superhero character from [[One-punch Man]]. The 16th rank S-class hero, aka \"Demon [[Cyborg]]\".\n", "--------------------------------------------------------------------------------\n", "17. The doujinshi tag means this image has The Japanese term for independently-published print works (the equivalent term in English would be fanbook or fanzine). Comics and art books are common. It can be [[original]] or fan art. This tag is deprecated. Use one of the tags below instead: * For comics, use [[comic]]. * For scans of print comics, use [[scan]]. * For doujin covers, use [[doujin cover]]. * For artbooks, see [[artbook]]. * For doujinshi being physically present in the post, see [[manga (object)]] or [[pornography]]. * For comics that are uploaded in their entirety, see \"the list of series pools\":/pools/gallery?commit=Search&search%5Bcategory%5D=series. You can also see a list of translated comics under {{translated comic}}.\n", "--------------------------------------------------------------------------------\n", "18. The asai_mayumi tag means this image has A female character from [[Doki Doki Pretty League]].\n", "--------------------------------------------------------------------------------\n", "19. The mordred_(memories_at_trifas)_(fate) tag means this image has [[Mordred (fate)|]] in her casual attire, first seen in [[Fate/Apocrypha]], then later released in [[Fate/Grand Order]] as a Spiritron Costume for her Saber variant. It's also seen in the [i]Heading Towards Trifas[/i] [[Craft Essence (fate)|]]. h4. Appearance * !post #1336069 * !post #3844613 * !post #3107186\n", "--------------------------------------------------------------------------------\n", "20. The storm_ruler_(dark_souls) tag means this image has A [[sword]] appears in multiple [[FromSoftware]] games, originating in [[Demon's Souls]].\n", "--------------------------------------------------------------------------------\n", "21. The tawara_touta_(fate)_(cosplay) tag means this image has [[Cosplay]] of [[Fate/Grand Order]]'s [[Tawara Touta (fate)|]].\n", "--------------------------------------------------------------------------------\n", "22. The madura_no_tsubasa tag means this image has \"The Wing of Madoola\" A platform game developed by [[SunSoft]] for the Nintendo Famicom in 1986. The game's plot greatly resembles that of [[Genmu Senki Leda]], which was released in 1985.\n", "--------------------------------------------------------------------------------\n", "23. The somunia tag means this image has [[Indie Virtual YouTuber|Indie]] [[Virtual Youtuber|Virtual Singer]]. Was briefly a part of Ficty (who had worked with KMNZ), from March 2019 to October 2021.\n", "--------------------------------------------------------------------------------\n", "24. The non_sequitur_(comic_strip) tag means this image has Non Sequitur is a [[comic]] strip created by Wiley Miller (usually credited as just Wiley) in 1992. http://en.wikipedia.org/wiki/Non_Sequitur_%28comic_strip%29\n", "--------------------------------------------------------------------------------\n", "25. The ooshiro_shin'ya tag means this image has Illustrator, guitarist. Japanese name: 大城 慎也 Other names: MRあきら, あきら, 秋月アキラ\n", "--------------------------------------------------------------------------------\n", "26. The ice_pack tag means this image has A bag containing [[ice]], used for reducing fever, swelling or pain. For the pack ice (Earth science term), see [[iceberg]]. h4. See also * [[Cold pack]]\n", "--------------------------------------------------------------------------------\n", "27. The kikurage-san tag means this image has Artist. Japanese name: きくらげさん (Kikurage-san) Circle name: 屋根裏猫 h4.See also * Pixiv account: http://www.pixiv.net/member.php?id=2016182\n", "--------------------------------------------------------------------------------\n", "28. The teppen!!!_(manga) tag means this image has Manga by [[mugi (iccomae)]]. An anime adaptation began airing in the Summer 2022 season.\n", "--------------------------------------------------------------------------------\n", "29. The natsume_ricca tag means this image has An [[Indie Virtual YouTuber|indie]] [[Virtual YouTuber]]. h4. External Links * \"YouTube channel\":https://www.youtube.com/RiccaNatsume * \"Twitter\":https://twitter.com/ricca_natsume\n", "--------------------------------------------------------------------------------\n", "30. The nipple_piercing tag means this image has A [[piercing]] through the nipple. The most common types of nipple piercings are [[nipple bar]]s or [[nipple rings]]. Illustrations without [[covered nipples]] should include [[nipples]] when visible. Objects that fit around the nipple instead of piercing them are [[nipple sleeves]]. h4. See also * [[Areola piercing]] * [[Nipple bar]] * [[Nipple rings]] * [[Nipple jewelry]] * [[Nipple chain]] * [[Nipple tag]] * [[Pasties]] * [[Piercing through clothes]] * [[Tag Group:Breasts Tags]] * [[Tag Group:Piercings]]\n", "--------------------------------------------------------------------------------\n" ] } ] }, { "cell_type": "code", "source": [ "# ==================== Standalone: Enrich captions.parquet with UNIQUE Danbooru wiki definitions ====================\n", "# Repo: https://huggingface.co/datasets/codeShare/sankaku_captioned_images\n", "# Prefers tags whose definitions have NOT been used yet. Only re-uses when no unused option exists.\n", "# Requires HF_TOKEN in Colab Secrets (with write access to the repo)\n", "\n", "import os\n", "import sys\n", "import random\n", "import re\n", "import tempfile\n", "import shutil\n", "import subprocess\n", "from pathlib import Path\n", "from collections import defaultdict\n", "\n", "# Install dependencies\n", "subprocess.check_call([\n", " sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-U\",\n", " \"datasets\", \"pandas\", \"pyarrow\", \"huggingface_hub\"\n", "])\n", "\n", "from datasets import load_dataset\n", "import pandas as pd\n", "from huggingface_hub import HfApi, hf_hub_download\n", "from google.colab import userdata\n", "\n", "# ---------------------------- Configuration ----------------------------\n", "REPO_ID = \"codeShare/sankaku_captioned_images\"\n", "PARQUET_REPO_PATH = \"preprocessed/captions.parquet\"\n", "TARGET_FIELD = \"thinking_response\" # change to \"written_response\" or \"addendum\" if desired\n", "LOCAL_DIR = Path(\"/content/sankaku_enrich\")\n", "LOCAL_DIR.mkdir(parents=True, exist_ok=True)\n", "LOCAL_PARQUET = LOCAL_DIR / \"captions.parquet\"\n", "\n", "HF_TOKEN = userdata.get(\"HF_TOKEN\")\n", "if not HF_TOKEN:\n", " raise ValueError(\"Add HF_TOKEN to Colab Secrets (needs write access to the repo).\")\n", "\n", "api = HfApi(token=HF_TOKEN)\n", "\n", "# ---------------------------- Helpers ----------------------------\n", "def clean_definition(text: str) -> str:\n", " \"\"\"Keep only A-Z a-z 0-9 and , . \\\" ' ! ? + spaces. Force start with lowercase.\"\"\"\n", " if not text:\n", " return \"\"\n", " cleaned = re.sub(r\"[^A-Za-z0-9,.\\\"'!? ]+\", \" \", str(text))\n", " cleaned = \" \".join(cleaned.split())\n", " if cleaned:\n", " cleaned = cleaned[0].lower() + cleaned[1:]\n", " return cleaned\n", "\n", "\n", "def get_preferred_definition(tags_str: str, wiki_lookup: dict, used_tags: set) -> tuple[str, str | None]:\n", " \"\"\"\n", " Return (formatted_string, chosen_tag) preferring tags that have NOT been used yet.\n", " Falls back to any matching tag only when no unused option exists.\n", " Returns (\"\", None) if no matching tags at all.\n", " \"\"\"\n", " if not tags_str or not isinstance(tags_str, str):\n", " return \"\", None\n", "\n", " tags = [t.strip().lower() for t in tags_str.split(\",\") if t.strip()]\n", " matches = [t for t in tags if t in wiki_lookup]\n", " if not matches:\n", " return \"\", None\n", "\n", " # Prefer unused tags\n", " unused_matches = [t for t in matches if t not in used_tags]\n", " if unused_matches:\n", " chosen = random.choice(unused_matches)\n", " else:\n", " # No unused options left for this row → allow re-use\n", " chosen = random.choice(matches)\n", "\n", " definition = wiki_lookup[chosen]\n", " formatted = f\"The {chosen} tag means this image has {definition}\"\n", " return formatted, chosen\n", "\n", "\n", "# ---------------------------- 1. Download current parquet ----------------------------\n", "print(f\"Downloading {PARQUET_REPO_PATH} from {REPO_ID} ...\")\n", "downloaded_path = hf_hub_download(\n", " repo_id=REPO_ID,\n", " repo_type=\"dataset\",\n", " filename=PARQUET_REPO_PATH,\n", " token=HF_TOKEN,\n", " force_download=True,\n", ")\n", "shutil.copy(downloaded_path, LOCAL_PARQUET)\n", "print(f\"Downloaded → {LOCAL_PARQUET}\")\n", "\n", "df = pd.read_parquet(LOCAL_PARQUET)\n", "print(f\"Loaded {len(df):,} rows. Columns: {list(df.columns)}\")\n", "\n", "if \"tags\" not in df.columns:\n", " raise ValueError(\"Parquet is missing the required 'tags' column.\")\n", "\n", "# Ensure target field exists\n", "if TARGET_FIELD not in df.columns:\n", " df[TARGET_FIELD] = \"\"\n", "df[TARGET_FIELD] = df[TARGET_FIELD].fillna(\"\").astype(str)\n", "\n", "# ---------------------------- 2. Load Danbooru wiki & build lookup ----------------------------\n", "print(\"\\nLoading Danbooru wiki dataset (lylogummy/danbooru_wikis_2026) ...\")\n", "wiki_ds = load_dataset(\"lylogummy/danbooru_wikis_2026\", split=\"train\")\n", "\n", "wiki_lookup = {}\n", "for item in wiki_ds:\n", " if item.get(\"is_deleted\"):\n", " continue\n", " title = (item.get(\"title\") or \"\").strip().lower()\n", " body = item.get(\"body\")\n", " if not title or not body:\n", " continue\n", " cleaned = clean_definition(body)\n", " if cleaned:\n", " wiki_lookup[title] = cleaned\n", "\n", "print(f\"Wiki lookup ready: {len(wiki_lookup):,} usable tags.\")\n", "\n", "# ---------------------------- 3. Enrich every row (prefer unique definitions) ----------------------------\n", "print(\"\\nEnriching rows (preferring previously unused tag definitions) ...\")\n", "\n", "used_tags = set() # tags whose definitions have already been assigned\n", "appended_count = 0\n", "reused_count = 0\n", "skipped_already_present = 0\n", "no_match_count = 0\n", "\n", "skipped_already = 0\n", "pan_present = 0\n", "\n", "# Optional: shuffle the order so early rows don't monopolize popular tags\n", "indices = list(df.index)\n", "random.shuffle(indices)\n", "\n", "for i, idx in enumerate(indices):\n", " if (i + 1) % 5000 == 0:\n", " print(f\" processed {i+1:,}/{len(df):,} | unique tags used so far: {len(used_tags):,}\")\n", "\n", " tags = df.at[idx, \"tags\"]\n", " extra, chosen_tag = get_preferred_definition(tags, wiki_lookup, used_tags)\n", "\n", " if not extra:\n", " no_match_count += 1\n", " continue\n", "\n", " current = str(df.at[idx, TARGET_FIELD] or \"\").strip()\n", "\n", " # Skip if this exact definition string is already present in the field\n", " if extra in current:\n", " skipped_already_present += 1\n", " # Still mark the tag as used so we don't prefer it later\n", " if chosen_tag:\n", " used_tags.add(chosen_tag)\n", " continue\n", "\n", " # Append\n", " if current:\n", " df.at[idx, TARGET_FIELD] = current + \"\\n\\n\" + extra\n", " else:\n", " df.at[idx, TARGET_FIELD] = extra\n", "\n", " appended_count += 1\n", " if chosen_tag in used_tags:\n", " reused_count += 1\n", " else:\n", " used_tags.add(chosen_tag)\n", "\n", "print(f\"\\nFinished enrichment:\")\n", "print(f\" • Newly appended : {appended_count:,}\")\n", "print(f\" • Of which were re-uses : {reused_count:,}\")\n", "print(f\" • Unique tags used : {len(used_tags):,}\")\n", "\n", "print(f\" • Already present (skipped): {skipped_already} {pan_present:,}\")\n", "\n", "print(f\" • Rows with no matching tag: {no_match_count:,}\")\n", "\n", "# ---------------------------- 4. Save locally (atomic) ----------------------------\n", "fd, tmp_name = tempfile.mkstemp(prefix=\"captions-\", suffix=\".parquet.tmp\", dir=str(LOCAL_DIR))\n", "os.close(fd)\n", "try:\n", " df.to_parquet(tmp_name, index=False)\n", " check = pd.read_parquet(tmp_name)\n", " if len(check) != len(df):\n", " raise IOError(\"Local Parquet verification failed\")\n", " os.replace(tmp_name, LOCAL_PARQUET)\n", "finally:\n", " if os.path.exists(tmp_name):\n", " os.remove(tmp_name)\n", "\n", "print(f\"Local enriched parquet ready: {LOCAL_PARQUET}\")\n", "\n", "# ---------------------------- 5. Upload back to the repo ----------------------------\n", "print(f\"\\nUploading updated {PARQUET_REPO_PATH} to {REPO_ID} ...\")\n", "api.upload_file(\n", " path_or_fileobj=str(LOCAL_PARQUET),\n", " path_in_repo=PARQUET_REPO_PATH,\n", " repo_id=REPO_ID,\n", " repo_type=\"dataset\",\n", " commit_message=\"Enrich thinking_response with unique Danbooru wiki definitions (prefer unused tags)\",\n", " token=HF_TOKEN,\n", ")\n", "\n", "print(\"\\n✅ Done! The parquet in the repo has been updated.\")\n", "print(f\" Repo : https://huggingface.co/datasets/{REPO_ID}\")\n", "print(f\" File : {PARQUET_REPO_PATH}\")\n", "print(f\" Field: {TARGET_FIELD}\")\n", "print(f\" Unique tag definitions used: {len(used_tags):,}\")" ], "metadata": { "id": "bgcVmb8jnAjc", "outputId": "d0182034-c759-496c-f043-2f137af3a571", "colab": { "base_uri": "https://localhost:8080/", "height": 643, "referenced_widgets": [ "9c1e29d8b3294b22af263e9dee90cfc0", "7bd74084d66c488eadfdbe75b48b7af3", "79c8015889a94a658be4af81cd88eb8a", "d8bc964103c849b195733d65dfc6a547", "ab0b4cf69a6d44ac987dbddad9b378c0", "aadde5c431584405a2c439209889c141", "a2c048bb7d444e43ab68ce984bfb9bff", "1d0325df296b4b7ab83220885446da2c", "3c0f44914f454418b4a6e8947645d969", "684157eeae004d4197eb40d6d1292820", "060572f0c5d14db98bdafae56811af27", "799cff7da8a74adcb478f9d1e4ee324e", "d35e7fee9c3847e99210fb39ed45f7d9", "af9ecd888c70418ea9a46b15139b3251", "eaa9c14684ba4994a073b1c5b07f2b05", "66b1f9c705ff4b769deee5d6ac5d882e", "086140f8576d46a8989819965d97ebce", "cb7960df26cb45ac9003d026359852db", "a0bc9656896b451397b360c28da9accd", "22250b08e36147d5bf1808cb5d306485", "ac2113eae19b483e995c385ef491e574", "59db03088c754d50b62d0b8bc10b168c", "40cdc4db27a24518af4c30961e033af5", "69ea5a361a824c9eaf573e20ae7e7dec", "84ff8d0f5575451d950510c5e99f1aca", "bfbea1957220436880dd883cab6f3600", "95cf3e4886174ca6832d461a828f261b", "ee90079dae5e434582a91c0531a64d2d", "b266849eda7e48738b78f08801dc7137", "47ff6f2afc8141f183456c52e5690cea", "c271299679574208af66e951b427e8e5", "8b74364328524d66a5dcaa26ba31051f", "58d48af80640450492bd1a60f2352f96", "508150f039454206ad91c64124a61e21", "71a5edf83c9d4b72826cb4aab3a641c3", "2c87e29f20614a8f8f92d67bc86b2e20", "104f9adccd754117ae1d06e3f1023212", "bdf95d8073be424482ff98c3514648a2", "5f5b19fd64094c9e91ff57d56739b9cc", "fe062391465f4b0da26e9ca6d013421f", "17bb14883efb4d59b71b3202fcd14319", "6b617c55060f4113bde9d6172bb62799", "83d5024b2f8843398dd9714469a69c5b", "550a64b0196e4ebfbbb4d86b3f052796", "851c544977b24431bc602e14d5706293", "c20ca40b003c408d9c68d872a9dbaf2b", "c8cae9f09592452aa9caeda5e843b522", "e8bb2d1e60554fb4be66eccaeee1a2b9", "9bf77cdea2934ad6a4f5cca62e46bf82", "3a9b42ff12c24892957d942f25080807", "336e94c181064efa83fb3e34ae25d39f", "f3871884fff0477ea0eeef0cb92768fd", "90cb374f53b34c0bb96c84c8b6914429", "c2db6c89d05e4aab82fcbfa1ad6b4914", "1b40aea8fd0b45c09c67036d0bce6a7a", "7307b79c85a7484eb9f5c171a917113a", "20962758005e41afa8979737ec5e24ea", "bb8654787fd84932a5882e827088832f", "e26e905526e24489aea9d5598b5816e6", "bf28b820dea94b70b723dcba042e35d0", "ed43671a59804a768351e6f30a7334f5", "3a8826dab59445e6a7ef49ec3dec8c0c", "2d268cb0f4854b8090db48b1a83768f7", "c2148118d12a460fb2ea3afaa885a1bd", "fd00f4d31f9e4228a8cfb916abac5d25", "c3f424c9037540a1a1418b7153ba29d2" ] } }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Downloading preprocessed/captions.parquet from codeShare/sankaku_captioned_images ...\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "preprocessed/captions.parquet: reconstructing file: 0%| | 0.00B / 10.3MB " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "9c1e29d8b3294b22af263e9dee90cfc0" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "preprocessed/captions.parquet: downloading bytes: | 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "799cff7da8a74adcb478f9d1e4ee324e" } }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "Downloaded → /content/sankaku_enrich/captions.parquet\n", "Loaded 7,768 rows. Columns: ['idx', 'prompt', 'tags', 'author', 'json_file', 'byte_offset', 'byte_length', 'instruction', 'thinking_response', 'written_response', 'addendum']\n", "\n", "Loading Danbooru wiki dataset (lylogummy/danbooru_wikis_2026) ...\n", "Wiki lookup ready: 196,635 usable tags.\n", "\n", "Enriching rows (preferring previously unused tag definitions) ...\n", " processed 5,000/7,768 | unique tags used so far: 3,454\n", "\n", "Finished enrichment:\n", " • Newly appended : 7,768\n", " • Of which were re-uses : 3,379\n", " • Unique tags used : 4,389\n", " • Already present (skipped): 0 0\n", " • Rows with no matching tag: 0\n", "Local enriched parquet ready: /content/sankaku_enrich/captions.parquet\n", "\n", "Uploading updated preprocessed/captions.parquet to codeShare/sankaku_captioned_images ...\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "Processing Files (0 / 0) : | | 0.00B / 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "40cdc4db27a24518af4c30961e033af5" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "New Data Upload : | | 0.00B / 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "508150f039454206ad91c64124a61e21" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ " ...u_enrich/captions.parquet: 36%|###5 | 4.41MB / 12.4MB " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "851c544977b24431bc602e14d5706293" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "Validating : | 0% " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "7307b79c85a7484eb9f5c171a917113a" } }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "\n", "✅ Done! The parquet in the repo has been updated.\n", " Repo : https://huggingface.co/datasets/codeShare/sankaku_captioned_images\n", " File : preprocessed/captions.parquet\n", " Field: thinking_response\n", " Unique tag definitions used: 4,389\n" ] } ] }, { "cell_type": "code", "source": [ "# ==================== Standalone: Truncate thinking_response after \"example\" / \"Example\" ====================\n", "# Repo: https://huggingface.co/datasets/codeShare/sankaku_captioned_images\n", "# Clears everything after the first occurrence of the word \"example\" or \"Example\"\n", "# Requires HF_TOKEN in Colab Secrets (with write access)\n", "\n", "import os\n", "import sys\n", "import re\n", "import tempfile\n", "import shutil\n", "import subprocess\n", "from pathlib import Path\n", "\n", "subprocess.check_call([\n", " sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-U\",\n", " \"pandas\", \"pyarrow\", \"huggingface_hub\"\n", "])\n", "\n", "import pandas as pd\n", "from huggingface_hub import HfApi, hf_hub_download\n", "from google.colab import userdata\n", "\n", "# ---------------------------- Configuration ----------------------------\n", "REPO_ID = \"codeShare/sankaku_captioned_images\"\n", "PARQUET_REPO_PATH = \"preprocessed/captions.parquet\"\n", "TARGET_FIELD = \"thinking_response\"\n", "LOCAL_DIR = Path(\"/content/sankaku_truncate\")\n", "LOCAL_DIR.mkdir(parents=True, exist_ok=True)\n", "LOCAL_PARQUET = LOCAL_DIR / \"captions.parquet\"\n", "\n", "HF_TOKEN = userdata.get(\"HF_TOKEN\")\n", "if not HF_TOKEN:\n", " raise ValueError(\"Add HF_TOKEN to Colab Secrets (needs write access to the repo).\")\n", "\n", "api = HfApi(token=HF_TOKEN)\n", "\n", "# Pattern: the whole word \"example\" or \"Example\" (case-sensitive as requested)\n", "# If you later want fully case-insensitive, change to re.IGNORECASE\n", "EXAMPLE_PATTERN = re.compile(r\"\\b(?:example|Example)\\b\")\n", "\n", "def truncate_after_example(text: str) -> str:\n", " \"\"\"Keep only the text up to (but not including) the first 'example'/'Example'.\"\"\"\n", " if not isinstance(text, str) or not text:\n", " return \"\"\n", " match = EXAMPLE_PATTERN.search(text)\n", " if match:\n", " # Keep everything before the matched word and strip trailing whitespace\n", " return text[:match.start()].rstrip()\n", " return text\n", "\n", "# ---------------------------- 1. Download current parquet ----------------------------\n", "print(f\"Downloading {PARQUET_REPO_PATH} from {REPO_ID} ...\")\n", "downloaded_path = hf_hub_download(\n", " repo_id=REPO_ID,\n", " repo_type=\"dataset\",\n", " filename=PARQUET_REPO_PATH,\n", " token=HF_TOKEN,\n", " force_download=True,\n", ")\n", "shutil.copy(downloaded_path, LOCAL_PARQUET)\n", "print(f\"Downloaded → {LOCAL_PARQUET}\")\n", "\n", "df = pd.read_parquet(LOCAL_PARQUET)\n", "print(f\"Loaded {len(df):,} rows.\")\n", "\n", "if TARGET_FIELD not in df.columns:\n", " raise ValueError(f\"Parquet is missing the required '{TARGET_FIELD}' column.\")\n", "\n", "df[TARGET_FIELD] = df[TARGET_FIELD].fillna(\"\").astype(str)\n", "\n", "# ---------------------------- 2. Process the column ----------------------------\n", "print(f\"\\nTruncating '{TARGET_FIELD}' after first occurrence of 'example' / 'Example' ...\")\n", "\n", "changed_count = 0\n", "for idx in df.index:\n", " original = df.at[idx, TARGET_FIELD]\n", " cleaned = truncate_after_example(original)\n", " if cleaned != original:\n", " df.at[idx, TARGET_FIELD] = cleaned\n", " changed_count += 1\n", "\n", "print(f\"Rows modified: {changed_count:,}\")\n", "\n", "# ---------------------------- 3. Save locally (atomic) ----------------------------\n", "fd, tmp_name = tempfile.mkstemp(prefix=\"captions-\", suffix=\".parquet.tmp\", dir=str(LOCAL_DIR))\n", "os.close(fd)\n", "try:\n", " df.to_parquet(tmp_name, index=False)\n", " check = pd.read_parquet(tmp_name)\n", " if len(check) != len(df):\n", " raise IOError(\"Local Parquet verification failed\")\n", " os.replace(tmp_name, LOCAL_PARQUET)\n", "finally:\n", " if os.path.exists(tmp_name):\n", " os.remove(tmp_name)\n", "\n", "print(f\"Local cleaned parquet ready: {LOCAL_PARQUET}\")\n", "\n", "# ---------------------------- 4. Upload back to the repo ----------------------------\n", "print(f\"\\nUploading updated {PARQUET_REPO_PATH} to {REPO_ID} ...\")\n", "api.upload_file(\n", " path_or_fileobj=str(LOCAL_PARQUET),\n", " path_in_repo=PARQUET_REPO_PATH,\n", " repo_id=REPO_ID,\n", " repo_type=\"dataset\",\n", " commit_message=\"Truncate thinking_response after first occurrence of 'example'/'Example'\",\n", " token=HF_TOKEN,\n", ")\n", "\n", "print(\"\\n✅ Done!\")\n", "print(f\" Repo : https://huggingface.co/datasets/{REPO_ID}\")\n", "print(f\" File : {PARQUET_REPO_PATH}\")\n", "print(f\" Modified rows: {changed_count:,}\")" ], "metadata": { "id": "Nwb1efQSn6we", "outputId": "3205f44c-78ec-4863-d21f-96204e652a96", "colab": { "base_uri": "https://localhost:8080/", "height": 452, "referenced_widgets": [ "0eaffdf43ac9422189a207085adcd648", "2435a2192fbf4b208851df2b006bbe06", "ceecf799c1524e8f8b675f063e7fc90f", "3082564a50314641beebf1bc341c7ac4", "5c5764aef67c45d9983ad5c39221bea1", "3fed6714b44447719b56e7316d8e1297", "d305c641fe514701963bcd37440d1cef", "e8550853b7e2453b8cc50eba92fd61b0", "ed4d5f8b352d40f693b50390d536c815", "a700da1e62da49968791e132008fad2a", "296ef64cf8f64b318c38b891664e0ef4", "145ed2b1e4a347eb93f0f26b98a856cb", "175bda8f009e4cff9ea4657dbd2bcaf5", "9916196b89974f879c3ea6d334231c66", "2b946a2a0256406f8381886ddb9df05f", "817ef1d7fadc46cdb94206d22eda306a", "7a3ed0ff1a8b4b3296029f2717107a2f", "2a53bbbabdb94e189f339530865119f4", "355905a5890b4c20841fe91140be3ced", "18523092d8da4bc8a5e79876bf18428f", "df5044ec76b44776b32de3aec330be0f", "b4b8b48f7daf4d46824d4b9c6af4b9c9", "9df57af1bffa4fe5975c24f53a56e470", "6ab5a188a4b1490f8f6856229396a263", "1b8dcc86391e418aae61b1b434c9cc6c", "a6e5ed0e220642dbb1d2c05e208622d4", "c2f83e258d15438a8d8d68c9d098e635", "038689169ea14e17a6f45ca80e628e37", "bacee620e1664f57a35fe23f95aa38f1", "784962bf707544c4b0a00171e94d9f96", "d878d9f7d6fa4b32ac03dd3edea804f3", "57099c35c5584b2d8da8b1bf442cf3b8", "1f23cb1df97148ec8f46ce893f45f6cd", "eefdc0696e1a4d3182e1ef92da474a13", "4a939ca5d7ce44109a4df804499ccdb0", "09671ffec691495abda41cc13fa2f2f2", "16100efeb7c9484b88c7cdd840210160", "14bdd721689e4dea9122793083114e2f", "d321958f4ba6422b89248076a0dfd03f", "15e9a823b2984b7d8baa778054035d37", "b3868e61c6804ee38474089f992b0dff", "03f92eb8d38a453c8b8ec36db5f49ef9", "feb2289b152b412ba40a61d064709cea", "190e5efae7784da4b58d87e333457d1b", "032a12ac2de74590abe7d69f9d21a400", "810db98cc6384b489d3fdf38cc2fc172", "e62449b444eb48a899edb68344ffe279", "c8be08d3ede54110b358559692ccf07e", "3eca9dd563224fc9acfe871008ab9057", "d5e8307621154090a1fad729442c1ced", "6902abd479184dafbdb43f9151adaf25", "f702cdedc0474b75b0571b08d9ff2185", "49ec06404082448288cfcbfcb0865a6d", "4213b42884f64618b2ba005c0fd4004a", "f3b738b9e0574ce09c651f32dbcff54d", "09f0162afa024ad5af2f200cf068941a", "ae21f73da46b4d9ba7a78fe3c09d12a9", "e7bd50ce702f44e3b4161eddbe121a05", "1b805d2fd43043b68c24cd6fc9f06851", "2182a96d647244ae84c655f9f5f6197d", "6f1910488cf84da195056cfec90116cc", "c7cdadeddeed429a90b4774155c314d3", "0c8bd296b2df4395bce3a248d89c4690", "692048b038d44697ad97a94be1a507b5", "69682374ece84e138f3b808c483a3894", "e04a7662248b4bb49e2fc65a0f4b87ec" ] } }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Downloading preprocessed/captions.parquet from codeShare/sankaku_captioned_images ...\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "preprocessed/captions.parquet: reconstructing file: 0%| | 0.00B / 12.4MB " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "0eaffdf43ac9422189a207085adcd648" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "preprocessed/captions.parquet: downloading bytes: | 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "145ed2b1e4a347eb93f0f26b98a856cb" } }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "Downloaded → /content/sankaku_truncate/captions.parquet\n", "Loaded 7,768 rows.\n", "\n", "Truncating 'thinking_response' after first occurrence of 'example' / 'Example' ...\n", "Rows modified: 136\n", "Local cleaned parquet ready: /content/sankaku_truncate/captions.parquet\n", "\n", "Uploading updated preprocessed/captions.parquet to codeShare/sankaku_captioned_images ...\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "Processing Files (0 / 0) : | | 0.00B / 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "9df57af1bffa4fe5975c24f53a56e470" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "New Data Upload : | | 0.00B / 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "eefdc0696e1a4d3182e1ef92da474a13" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ " ...truncate/captions.parquet: 81%|########1 | 10.0MB / 12.3MB " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "032a12ac2de74590abe7d69f9d21a400" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "Validating : | 0% " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "09f0162afa024ad5af2f200cf068941a" } }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "\n", "✅ Done!\n", " Repo : https://huggingface.co/datasets/codeShare/sankaku_captioned_images\n", " File : preprocessed/captions.parquet\n", " Modified rows: 136\n" ] } ] }, { "cell_type": "code", "source": [ "# ==================== Standalone: Truncate thinking_response after \"!post\" / \"see also\" / \"See also\" ====================\n", "# Repo: https://huggingface.co/datasets/codeShare/sankaku_captioned_images\n", "# Clears everything after the first occurrence of \"!post\", \"see also\", or \"See also\"\n", "# Requires HF_TOKEN in Colab Secrets (with write access)\n", "\n", "import os\n", "import sys\n", "import re\n", "import tempfile\n", "import shutil\n", "import subprocess\n", "from pathlib import Path\n", "\n", "subprocess.check_call([\n", " sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-U\",\n", " \"pandas\", \"pyarrow\", \"huggingface_hub\"\n", "])\n", "\n", "import pandas as pd\n", "from huggingface_hub import HfApi, hf_hub_download\n", "from google.colab import userdata\n", "\n", "# ---------------------------- Configuration ----------------------------\n", "REPO_ID = \"codeShare/sankaku_captioned_images\"\n", "PARQUET_REPO_PATH = \"preprocessed/captions.parquet\"\n", "TARGET_FIELD = \"thinking_response\"\n", "LOCAL_DIR = Path(\"/content/sankaku_truncate_post\")\n", "LOCAL_DIR.mkdir(parents=True, exist_ok=True)\n", "LOCAL_PARQUET = LOCAL_DIR / \"captions.parquet\"\n", "\n", "HF_TOKEN = userdata.get(\"HF_TOKEN\")\n", "if not HF_TOKEN:\n", " raise ValueError(\"Add HF_TOKEN to Colab Secrets (needs write access to the repo).\")\n", "\n", "api = HfApi(token=HF_TOKEN)\n", "\n", "# Match \"!post\" or \"see also\" / \"See also\" (case-insensitive for the latter)\n", "TRUNCATE_PATTERN = re.compile(\n", " r\"!post|\\bsee also\\b\",\n", " flags=re.IGNORECASE\n", ")\n", "\n", "def truncate_after_marker(text: str) -> str:\n", " \"\"\"Keep only the text up to (but not including) the first matching marker.\"\"\"\n", " if not isinstance(text, str) or not text:\n", " return \"\"\n", " match = TRUNCATE_PATTERN.search(text)\n", " if match:\n", " return text[:match.start()].rstrip()\n", " return text\n", "\n", "# ---------------------------- 1. Download current parquet ----------------------------\n", "print(f\"Downloading {PARQUET_REPO_PATH} from {REPO_ID} ...\")\n", "downloaded_path = hf_hub_download(\n", " repo_id=REPO_ID,\n", " repo_type=\"dataset\",\n", " filename=PARQUET_REPO_PATH,\n", " token=HF_TOKEN,\n", " force_download=True,\n", ")\n", "shutil.copy(downloaded_path, LOCAL_PARQUET)\n", "print(f\"Downloaded → {LOCAL_PARQUET}\")\n", "\n", "df = pd.read_parquet(LOCAL_PARQUET)\n", "print(f\"Loaded {len(df):,} rows.\")\n", "\n", "if TARGET_FIELD not in df.columns:\n", " raise ValueError(f\"Parquet is missing the required '{TARGET_FIELD}' column.\")\n", "\n", "df[TARGET_FIELD] = df[TARGET_FIELD].fillna(\"\").astype(str)\n", "\n", "# ---------------------------- 2. Process the column ----------------------------\n", "print(f\"\\nTruncating '{TARGET_FIELD}' after first occurrence of '!post' / 'see also' / 'See also' ...\")\n", "\n", "changed_count = 0\n", "for idx in df.index:\n", " original = df.at[idx, TARGET_FIELD]\n", " cleaned = truncate_after_marker(original)\n", " if cleaned != original:\n", " df.at[idx, TARGET_FIELD] = cleaned\n", " changed_count += 1\n", "\n", "print(f\"Rows modified: {changed_count:,}\")\n", "\n", "# ---------------------------- 3. Save locally (atomic) ----------------------------\n", "fd, tmp_name = tempfile.mkstemp(prefix=\"captions-\", suffix=\".parquet.tmp\", dir=str(LOCAL_DIR))\n", "os.close(fd)\n", "try:\n", " df.to_parquet(tmp_name, index=False)\n", " check = pd.read_parquet(tmp_name)\n", " if len(check) != len(df):\n", " raise IOError(\"Local Parquet verification failed\")\n", " os.replace(tmp_name, LOCAL_PARQUET)\n", "finally:\n", " if os.path.exists(tmp_name):\n", " os.remove(tmp_name)\n", "\n", "print(f\"Local cleaned parquet ready: {LOCAL_PARQUET}\")\n", "\n", "# ---------------------------- 4. Upload back to the repo ----------------------------\n", "print(f\"\\nUploading updated {PARQUET_REPO_PATH} to {REPO_ID} ...\")\n", "api.upload_file(\n", " path_or_fileobj=str(LOCAL_PARQUET),\n", " path_in_repo=PARQUET_REPO_PATH,\n", " repo_id=REPO_ID,\n", " repo_type=\"dataset\",\n", " commit_message=\"Truncate thinking_response after '!post' or 'see also'/'See also'\",\n", " token=HF_TOKEN,\n", ")\n", "\n", "print(\"\\n✅ Done!\")\n", "print(f\" Repo : https://huggingface.co/datasets/{REPO_ID}\")\n", "print(f\" File : {PARQUET_REPO_PATH}\")\n", "print(f\" Modified rows: {changed_count:,}\")" ], "metadata": { "id": "jWyMWGdep1gh", "outputId": "aafa6e51-b75b-447e-c51f-d13ae11f98e2", "colab": { "base_uri": "https://localhost:8080/", "height": 452, "referenced_widgets": [ "18360203552d48928fed22645c928a4e", "4e539936b4e0496e99777a58edb5f8a9", "754ee5f0cd3c4306b37c08f984840b26", "ee988ee5837144c6bf4b63fa2349dfb4", "31b59da31277478cbf40b5fc55f0fa1a", "c31af0946a7946778c3ee823171d4ce9", "b1f95fa1e22d4cb5a5e0a6a195ce961a", "0be3c8c6321c4c7b99cabf292311d90d", "7d3f33a1fb944813934d97a20fb5219f", "ce9e0d530a1448bb8db6c56654dd4d9d", "f75dd7624b46471ba2f03a0a7606d9da", "f9d08f2066f546138265bbf59863ab5e", "614e8ec476214da0a9ac68b964fcdac4", "e66a9d429d9b4eaf95ed886bff30cdf3", "32fb8b8c0a5f47eaa6ccf01db321034f", "22d4a18319ba46c1a6a2b01a590789bb", "ccacc481fba94049886c0d719213241d", "9890738429fb4379ae13a64b6391fcd0", "b519367d727e46dc85b3cc979bc6e42f", "5312e74ba32c402888b04ac284d4f819", "f10cae56156d41418e934fafb908f712", "2673d7e526f145169f9313e55c4bd265", "8af8ae200c1040829ce0a2deb4ddbb89", "8316b399ebc645889a31909feb72aabf", "3309021f0cc440c784c57b1f50d43a0d", "bb39d25b4bc4492a9e3327d18e81f368", "91889c5f45d34a179f4861c984c6f77d", "309522e19e2845a5be07baa37131fc3c", "10959c311a994469b3cd56caee187e78", "093265efcd1146dc9f80a5b14c1bed14", "3f3085d6a206463786c9508df6a956f6", "9cce0aeb50624903ba5325bbb8d50da7", "1d0a9711bb1d4331b3489d92c693975c", "5c154f423cad43c38edf481ef81c11ea", "cb9c92fc496649b685d4059e9ae93dee", "c4efe42000994e19aa61dfc2dbd1567e", "633ce66dd56b403f9b4dd53e6475c74a", "015631e2bb224db58c111c7328d37bc6", "c0c5b7232d4444629bee0a11a99fc2f8", "30c685e3467742388381417bde3b897e", "70b5a5a752b54a7c8bb6b3c56b3e6d7f", "88aa5d53b45f4fcd9b7bfdd190380244", "f5fbd8e9b1c547a494a547d9d71172cf", "066a9d767720465c960fb9b149f8e3e8", "8234f0a8df1f4ded894a9c49cb9c9c22", "fbcb92425bef4c3dae049fb968da0379", "350e817aafd74094844026408630d5f9", "5dc5f2ca0a714f04a1e62f9857ebd4f2", "587209035a9b4665a271f98b5c2e86bc", "7889baff5bff4744b053579414836f01", "26cd7e414fc346a4987b6c8281ab89c1", "bcfe648422ce43849da197d402a490dd", "26ef408d83bf45a9841c8ef28f297d49", "6f4a90ca6d764695b02ca14d26e707ad", "d549a89626f8440c850b043d763ce19a", "3ddcbf028dae4e75bb98889408cc56cf", "06defba033304e8fa442a2de214ae44c", "bffd74ee61944e1f95936135b9c3b0ba", "14b95a957ac4441586b970d6aa3f6ef6", "f9f7b613a3d748ffa4b43dd43fa4fe77", "6975b02cf58941678a9f2aeccdf58d09", "a2e3f5e65e26420ab087b69b4b689682", "b9f46c8e5e0d4b8a85ba595279941a4d", "3998aafed9de46cebb7b4ac2abb38710", "e03034dce65e43bb8dd21af6edc7bd2c", "9e2834537a53434d92a3fc9070c44af0" ] } }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Downloading preprocessed/captions.parquet from codeShare/sankaku_captioned_images ...\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "preprocessed/captions.parquet: reconstructing file: 0%| | 0.00B / 12.3MB " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "18360203552d48928fed22645c928a4e" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "preprocessed/captions.parquet: downloading bytes: | 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "f9d08f2066f546138265bbf59863ab5e" } }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "Downloaded → /content/sankaku_truncate_post/captions.parquet\n", "Loaded 7,768 rows.\n", "\n", "Truncating 'thinking_response' after first occurrence of '!post' / 'see also' / 'See also' ...\n", "Rows modified: 6,622\n", "Local cleaned parquet ready: /content/sankaku_truncate_post/captions.parquet\n", "\n", "Uploading updated preprocessed/captions.parquet to codeShare/sankaku_captioned_images ...\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "Processing Files (0 / 0) : | | 0.00B / 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "8af8ae200c1040829ce0a2deb4ddbb89" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "New Data Upload : | | 0.00B / 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "5c154f423cad43c38edf481ef81c11ea" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ " ...ate_post/captions.parquet: 89%|########9 | 10.1MB / 11.3MB " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "8234f0a8df1f4ded894a9c49cb9c9c22" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "Validating : | 0% " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "3ddcbf028dae4e75bb98889408cc56cf" } }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "\n", "✅ Done!\n", " Repo : https://huggingface.co/datasets/codeShare/sankaku_captioned_images\n", " File : preprocessed/captions.parquet\n", " Modified rows: 6,622\n" ] } ] }, { "cell_type": "code", "source": [ "# ==================== Standalone: Truncate thinking_response after \"h4\" ====================\n", "# Repo: https://huggingface.co/datasets/codeShare/sankaku_captioned_images\n", "# Clears everything after the first occurrence of \"h4\"\n", "# Requires HF_TOKEN in Colab Secrets (with write access)\n", "\n", "import os\n", "import sys\n", "import re\n", "import tempfile\n", "import shutil\n", "import subprocess\n", "from pathlib import Path\n", "\n", "subprocess.check_call([\n", " sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-U\",\n", " \"pandas\", \"pyarrow\", \"huggingface_hub\"\n", "])\n", "\n", "import pandas as pd\n", "from huggingface_hub import HfApi, hf_hub_download\n", "from google.colab import userdata\n", "\n", "# ---------------------------- Configuration ----------------------------\n", "REPO_ID = \"codeShare/sankaku_captioned_images\"\n", "PARQUET_REPO_PATH = \"preprocessed/captions.parquet\"\n", "TARGET_FIELD = \"thinking_response\"\n", "LOCAL_DIR = Path(\"/content/sankaku_truncate_h4\")\n", "LOCAL_DIR.mkdir(parents=True, exist_ok=True)\n", "LOCAL_PARQUET = LOCAL_DIR / \"captions.parquet\"\n", "\n", "HF_TOKEN = userdata.get(\"HF_TOKEN\")\n", "if not HF_TOKEN:\n", " raise ValueError(\"Add HF_TOKEN to Colab Secrets (needs write access to the repo).\")\n", "\n", "api = HfApi(token=HF_TOKEN)\n", "\n", "# Match \"h4\" as a whole word (case-sensitive). Change to re.IGNORECASE if you want case-insensitive.\n", "H4_PATTERN = re.compile(r\"\\bh4\\b\")\n", "\n", "def truncate_after_h4(text: str) -> str:\n", " \"\"\"Keep only the text up to (but not including) the first 'h4'.\"\"\"\n", " if not isinstance(text, str) or not text:\n", " return \"\"\n", " match = H4_PATTERN.search(text)\n", " if match:\n", " return text[:match.start()].rstrip()\n", " return text\n", "\n", "# ---------------------------- 1. Download current parquet ----------------------------\n", "print(f\"Downloading {PARQUET_REPO_PATH} from {REPO_ID} ...\")\n", "downloaded_path = hf_hub_download(\n", " repo_id=REPO_ID,\n", " repo_type=\"dataset\",\n", " filename=PARQUET_REPO_PATH,\n", " token=HF_TOKEN,\n", " force_download=True,\n", ")\n", "shutil.copy(downloaded_path, LOCAL_PARQUET)\n", "print(f\"Downloaded → {LOCAL_PARQUET}\")\n", "\n", "df = pd.read_parquet(LOCAL_PARQUET)\n", "print(f\"Loaded {len(df):,} rows.\")\n", "\n", "if TARGET_FIELD not in df.columns:\n", " raise ValueError(f\"Parquet is missing the required '{TARGET_FIELD}' column.\")\n", "\n", "df[TARGET_FIELD] = df[TARGET_FIELD].fillna(\"\").astype(str)\n", "\n", "# ---------------------------- 2. Process the column ----------------------------\n", "print(f\"\\nTruncating '{TARGET_FIELD}' after first occurrence of 'h4' ...\")\n", "\n", "changed_count = 0\n", "for idx in df.index:\n", " original = df.at[idx, TARGET_FIELD]\n", " cleaned = truncate_after_h4(original)\n", " if cleaned != original:\n", " df.at[idx, TARGET_FIELD] = cleaned\n", " changed_count += 1\n", "\n", "print(f\"Rows modified: {changed_count:,}\")\n", "\n", "# ---------------------------- 3. Save locally (atomic) ----------------------------\n", "fd, tmp_name = tempfile.mkstemp(prefix=\"captions-\", suffix=\".parquet.tmp\", dir=str(LOCAL_DIR))\n", "os.close(fd)\n", "try:\n", " df.to_parquet(tmp_name, index=False)\n", " check = pd.read_parquet(tmp_name)\n", " if len(check) != len(df):\n", " raise IOError(\"Local Parquet verification failed\")\n", " os.replace(tmp_name, LOCAL_PARQUET)\n", "finally:\n", " if os.path.exists(tmp_name):\n", " os.remove(tmp_name)\n", "\n", "print(f\"Local cleaned parquet ready: {LOCAL_PARQUET}\")\n", "\n", "# ---------------------------- 4. Upload back to the repo ----------------------------\n", "print(f\"\\nUploading updated {PARQUET_REPO_PATH} to {REPO_ID} ...\")\n", "api.upload_file(\n", " path_or_fileobj=str(LOCAL_PARQUET),\n", " path_in_repo=PARQUET_REPO_PATH,\n", " repo_id=REPO_ID,\n", " repo_type=\"dataset\",\n", " commit_message=\"Truncate thinking_response after first occurrence of 'h4'\",\n", " token=HF_TOKEN,\n", ")\n", "\n", "print(\"\\n✅ Done!\")\n", "print(f\" Repo : https://huggingface.co/datasets/{REPO_ID}\")\n", "print(f\" File : {PARQUET_REPO_PATH}\")\n", "print(f\" Modified rows: {changed_count:,}\")" ], "metadata": { "id": "PcWciG5_qVE_", "outputId": "029b6b23-4dcc-467e-aa92-34a7e39923c4", "colab": { "base_uri": "https://localhost:8080/", "height": 452, "referenced_widgets": [ "49908163917b48d1ab572d8e67c25126", "ad9d35b1bb3446d5a64100232581cd84", "d6b14ded462948799853b223daa143de", "f50ef84e89c94a68b4400a21a46183ed", "fa2db5325c814b0382792eb91fd23037", "43e046aac24f42239362013349cbf60c", "ad49a576b8904c0bb2966ffd2b916bdc", "24f4f5a644c44b3aa75f28c49dd19b85", "ef1dcfbb041d402aaedd1588ace89bfe", "22bbdbcfeae849c3932ad474e6aab3ec", "df406626590b4bbf890854073a536331", "286d14f297d44784892f461468d5d27b", "7b973d1fb48f415789bdb5dba5fa1b6e", "614ea41b8cad4517b382d95ddf41f8a1", "f319342c01314ffdb3de1c4a7a8876c7", "586e1cc4102e438e85a41f294cf5cd1a", "170e8ed27a4e4cbbbfe455a53e2d66ec", "a500ba35e5a24fc9b71ad1219591e230", "df519622820249f39d64cf73889a7c72", "6d280d1e38f34d6aa7fd930f3fc5961e", "bdbf95ad5ed847a695fff2072ac5e21d", "83c3e9d232ec4225b50d685791da0c91", "602b70dac4074ac2bb810edd42d1f69e", "3b138abe857c49e5946e8bbfa4fda016", "26a58e9c09a842bea9296121f36c08e2", "7a36e224ec4344d2b656acb2cba2b8ff", "9d496ad207554419b2aa6401fc4f4872", "de3e8d10592c4c179a61fd000e9d8857", "995ebfe7a18c47a5b2e71adffce3d7c6", "44d67a9a54324af7bc28d6b44fa0d1ab", "c79aa408669a476a93f6b7ea278bf1d0", "281d9b3f7a79443faf642c8c992b7396", "de434896279341789ef7214ec6ad7142", "eae4beaa4a614c98a73b03a90f2d733c", "da5767e1a7514e349e09982424c5f4ae", "95664123836d4613bbd77f6e73959b8d", "9035e8ee74f34675bf98efea2bb0bfef", "ad7ed55976a64c53aebccec393885a84", "482e49cba6374f92a3ff338f9025d3d6", "3912bde9372949b79da7be2232d9d422", "fbcac96384264c3da336453071a87ce6", "c63735b607f94327ae307987dba8f1f4", "2c44f8df9418401f9c1325b9239a79b1", "664eb7dceb8a449ab4e31a323fa4b65d", "ce371ea867fc40e588f24151cf55e9c6", "aa5e01b6f7db4bba93ba4f31b3476777", "bce60d76163a4726880c093c28cf8d57", "7d21ea1f695146368df1b059c26e4d9c", "f2b3bcd01a024cf898e2766df23b5b80", "2e5b3f22fe294da093c843d4c70b1c0b", "2e0f863179e04f688ca10e92c66e3713", "59ebd18b86bb49f2bf31c9b58bdf5cce", "68e63eff0c4a4262af368f474c9c77f1", "6520e3eaa0f541cdafc307edfab77f68", "4684c418a555482d88c5831bf705ae39", "f6b85c7311504f3d8c11a18512d94a69", "36ab7b6db3a64af8a8f9f0b07a86ccd0", "965a0b5bebae4d74964ad83f66b78cf6", "be6be726367f45bfa31b62811fc98e18", "95becb29c7b14ecf84cc06f41be5e95c", "ccbf7628252f4325a47e48202fb5def3", "a6dcd13066d64ffc8a8dedff3e32e498", "b0087f55015a4b95a40dcc18e91efa4c", "4817c292e8344a39905a12675ddb73f3", "0e27645cd0d9455da7b3c25243981f13", "322d8708f90746e09f023b5b274875c2" ] } }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Downloading preprocessed/captions.parquet from codeShare/sankaku_captioned_images ...\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "preprocessed/captions.parquet: reconstructing file: 0%| | 0.00B / 11.3MB " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "49908163917b48d1ab572d8e67c25126" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "preprocessed/captions.parquet: downloading bytes: | 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "286d14f297d44784892f461468d5d27b" } }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "Downloaded → /content/sankaku_truncate_h4/captions.parquet\n", "Loaded 7,768 rows.\n", "\n", "Truncating 'thinking_response' after first occurrence of 'h4' ...\n", "Rows modified: 6,710\n", "Local cleaned parquet ready: /content/sankaku_truncate_h4/captions.parquet\n", "\n", "Uploading updated preprocessed/captions.parquet to codeShare/sankaku_captioned_images ...\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "Processing Files (0 / 0) : | | 0.00B / 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "602b70dac4074ac2bb810edd42d1f69e" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "New Data Upload : | | 0.00B / 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "eae4beaa4a614c98a73b03a90f2d733c" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ " ...ncate_h4/captions.parquet: 90%|######### | 10.1MB / 11.2MB " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "ce371ea867fc40e588f24151cf55e9c6" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "Validating : | 0% " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "f6b85c7311504f3d8c11a18512d94a69" } }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "\n", "✅ Done!\n", " Repo : https://huggingface.co/datasets/codeShare/sankaku_captioned_images\n", " File : preprocessed/captions.parquet\n", " Modified rows: 6,710\n" ] } ] }, { "cell_type": "code", "source": [ "# ==================== Second-pass enrichment ====================\n", "# Only rows where thinking_response has < 30 words receive an additional\n", "# Danbooru wiki definition. Prefers tags that have never been used yet.\n", "# Extra filtering: cut everything after \"example\"/\"Example\", \"h4\", \"!post\",\n", "# \"See also\"/\"see also\".\n", "# Repo: https://huggingface.co/datasets/codeShare/sankaku_captioned_images\n", "\n", "import os\n", "import sys\n", "import random\n", "import re\n", "import tempfile\n", "import shutil\n", "import subprocess\n", "from pathlib import Path\n", "\n", "subprocess.check_call([\n", " sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-U\",\n", " \"datasets\", \"pandas\", \"pyarrow\", \"huggingface_hub\"\n", "])\n", "\n", "from datasets import load_dataset\n", "import pandas as pd\n", "from huggingface_hub import HfApi, hf_hub_download\n", "from google.colab import userdata\n", "\n", "# ---------------------------- Configuration ----------------------------\n", "REPO_ID = \"codeShare/sankaku_captioned_images\"\n", "PARQUET_REPO_PATH = \"preprocessed/captions.parquet\"\n", "TARGET_FIELD = \"thinking_response\"\n", "MIN_WORDS = 30\n", "LOCAL_DIR = Path(\"/content/sankaku_enrich_pass2\")\n", "LOCAL_DIR.mkdir(parents=True, exist_ok=True)\n", "LOCAL_PARQUET = LOCAL_DIR / \"captions.parquet\"\n", "\n", "HF_TOKEN = userdata.get(\"HF_TOKEN\")\n", "if not HF_TOKEN:\n", " raise ValueError(\"Add HF_TOKEN to Colab Secrets (write access required).\")\n", "\n", "api = HfApi(token=HF_TOKEN)\n", "\n", "# ---------------------------- Cleaning helpers ----------------------------\n", "def strip_after_markers(text: str) -> str:\n", " \"\"\"Remove everything from the first occurrence of the listed markers onward.\"\"\"\n", " if not text:\n", " return \"\"\n", " # Case-insensitive search for the earliest marker\n", " markers = [\n", " r\"\\bexample\\b\",\n", " r\"\\bh4\\b\",\n", " r\"!post\",\n", " r\"\\bsee also\\b\",\n", " ]\n", " pattern = re.compile(\"|\".join(markers), flags=re.IGNORECASE)\n", " match = pattern.search(text)\n", " if match:\n", " text = text[:match.start()]\n", " return text.strip()\n", "\n", "\n", "def clean_definition(text: str) -> str:\n", " \"\"\"\n", " 1. Cut everything after example / h4 / !post / see also\n", " 2. Keep only A-Z a-z 0-9 and , . \" ' ! ?\n", " 3. Force the result to start with a lowercase letter\n", " \"\"\"\n", " if not text:\n", " return \"\"\n", " text = strip_after_markers(str(text))\n", " cleaned = re.sub(r\"[^A-Za-z0-9,.\\\"'!? ]+\", \" \", text)\n", " cleaned = \" \".join(cleaned.split())\n", " if cleaned:\n", " cleaned = cleaned[0].lower() + cleaned[1:]\n", " return cleaned\n", "\n", "\n", "def word_count(text: str) -> int:\n", " return len(str(text).split())\n", "\n", "\n", "def get_preferred_definition(tags_str: str, wiki_lookup: dict, used_tags: set):\n", " \"\"\"Prefer a tag that has never been used. Fall back to any match if necessary.\"\"\"\n", " if not tags_str or not isinstance(tags_str, str):\n", " return \"\", None\n", "\n", " tags = [t.strip().lower() for t in tags_str.split(\",\") if t.strip()]\n", " matches = [t for t in tags if t in wiki_lookup]\n", " if not matches:\n", " return \"\", None\n", "\n", " unused = [t for t in matches if t not in used_tags]\n", " chosen = random.choice(unused) if unused else random.choice(matches)\n", "\n", " definition = wiki_lookup[chosen]\n", " formatted = f\"The {chosen} tag means this image has {definition}\"\n", " return formatted, chosen\n", "\n", "\n", "# ---------------------------- 1. Download current parquet ----------------------------\n", "print(f\"Downloading {PARQUET_REPO_PATH} from {REPO_ID} ...\")\n", "downloaded = hf_hub_download(\n", " repo_id=REPO_ID,\n", " repo_type=\"dataset\",\n", " filename=PARQUET_REPO_PATH,\n", " token=HF_TOKEN,\n", " force_download=True,\n", ")\n", "shutil.copy(downloaded, LOCAL_PARQUET)\n", "print(f\"Downloaded → {LOCAL_PARQUET}\")\n", "\n", "df = pd.read_parquet(LOCAL_PARQUET)\n", "print(f\"Loaded {len(df):,} rows.\")\n", "\n", "if \"tags\" not in df.columns:\n", " raise ValueError(\"Parquet is missing the 'tags' column.\")\n", "if TARGET_FIELD not in df.columns:\n", " df[TARGET_FIELD] = \"\"\n", "df[TARGET_FIELD] = df[TARGET_FIELD].fillna(\"\").astype(str)\n", "\n", "# ---------------------------- 2. Load wiki & build cleaned lookup ----------------------------\n", "print(\"\\nLoading Danbooru wiki dataset ...\")\n", "wiki_ds = load_dataset(\"lylogummy/danbooru_wikis_2026\", split=\"train\")\n", "\n", "wiki_lookup = {}\n", "for item in wiki_ds:\n", " if item.get(\"is_deleted\"):\n", " continue\n", " title = (item.get(\"title\") or \"\").strip().lower()\n", " body = item.get(\"body\")\n", " if not title or not body:\n", " continue\n", " cleaned = clean_definition(body)\n", " if cleaned:\n", " wiki_lookup[title] = cleaned\n", "\n", "print(f\"Wiki lookup ready: {len(wiki_lookup):,} usable tags.\")\n", "\n", "# ---------------------------- 3. Discover already-used tags ----------------------------\n", "# Scan the whole dataframe so we continue the \"prefer unique\" policy from the first pass\n", "print(\"\\nScanning existing thinking_response for already-used tags ...\")\n", "used_tags = set()\n", "tag_pattern = re.compile(r\"The ([a-z0-9_]+) tag means this image has \", re.IGNORECASE)\n", "\n", "for text in df[TARGET_FIELD]:\n", " for match in tag_pattern.finditer(str(text)):\n", " used_tags.add(match.group(1).lower())\n", "\n", "print(f\"Tags already used in the dataset: {len(used_tags):,}\")\n", "\n", "# ---------------------------- 4. Second-pass enrichment ----------------------------\n", "print(f\"\\nSecond pass: appending to rows with < {MIN_WORDS} words ...\")\n", "\n", "indices = list(df.index)\n", "random.shuffle(indices) # avoid bias toward early rows\n", "\n", "appended = 0\n", "reused = 0\n", "skipped_short_but_no_match = 0\n", "already_long = 0\n", "\n", "for i, idx in enumerate(indices):\n", " if (i + 1) % 5000 == 0:\n", " print(f\" processed {i+1:,}/{len(df):,} | unique tags used: {len(used_tags):,}\")\n", "\n", " current = str(df.at[idx, TARGET_FIELD] or \"\").strip()\n", " if word_count(current) >= MIN_WORDS:\n", " already_long += 1\n", " continue\n", "\n", " tags = df.at[idx, \"tags\"]\n", " extra, chosen = get_preferred_definition(tags, wiki_lookup, used_tags)\n", "\n", " if not extra:\n", " skipped_short_but_no_match += 1\n", " continue\n", "\n", " # Avoid exact duplicate string\n", " if extra in current:\n", " if chosen:\n", " used_tags.add(chosen)\n", " continue\n", "\n", " if current:\n", " df.at[idx, TARGET_FIELD] = current + \"\\n\\n\" + extra\n", " else:\n", " df.at[idx, TARGET_FIELD] = extra\n", "\n", " appended += 1\n", " if chosen in used_tags:\n", " reused += 1\n", " else:\n", " used_tags.add(chosen)\n", "\n", "print(f\"\\nSecond-pass results:\")\n", "print(f\" • Rows already ≥ {MIN_WORDS} words : {already_long:,}\")\n", "print(f\" • Newly appended : {appended:,}\")\n", "print(f\" • Of which were re-uses : {reused:,}\")\n", "print(f\" • Short rows with no matching tag : {skipped_short_but_no_match:,}\")\n", "print(f\" • Total unique tags used now : {len(used_tags):,}\")\n", "\n", "# ---------------------------- 5. Atomic local save ----------------------------\n", "fd, tmp_name = tempfile.mkstemp(prefix=\"captions-\", suffix=\".parquet.tmp\", dir=str(LOCAL_DIR))\n", "os.close(fd)\n", "try:\n", " df.to_parquet(tmp_name, index=False)\n", " check = pd.read_parquet(tmp_name)\n", " if len(check) != len(df):\n", " raise IOError(\"Local Parquet verification failed\")\n", " os.replace(tmp_name, LOCAL_PARQUET)\n", "finally:\n", " if os.path.exists(tmp_name):\n", " os.remove(tmp_name)\n", "\n", "print(f\"Local enriched parquet ready: {LOCAL_PARQUET}\")\n", "\n", "# ---------------------------- 6. Upload ----------------------------\n", "print(f\"\\nUploading updated {PARQUET_REPO_PATH} ...\")\n", "api.upload_file(\n", " path_or_fileobj=str(LOCAL_PARQUET),\n", " path_in_repo=PARQUET_REPO_PATH,\n", " repo_id=REPO_ID,\n", " repo_type=\"dataset\",\n", " commit_message=(\n", " f\"Second-pass: append extra wiki definition to thinking_response \"\n", " f\"when word count < {MIN_WORDS} (prefer unused tags, filtered definitions)\"\n", " ),\n", " token=HF_TOKEN,\n", ")\n", "\n", "print(\"\\n✅ Done!\")\n", "print(f\" Repo : https://huggingface.co/datasets/{REPO_ID}\")\n", "print(f\" File : {PARQUET_REPO_PATH}\")" ], "metadata": { "id": "qelTqHRKsjwv", "outputId": "92771370-1a28-408d-e95f-1ac5f56c2fb0", "colab": { "base_uri": "https://localhost:8080/", "height": 660, "referenced_widgets": [ "7a2c2e5a0e7d494eb887353925603b74", "87c2fe5336944334b1ee57dba426957e", "4eb386fb4e544daab7d111aee5f4773b", "7ceb2df36c644cb0baa8d3689a806e52", "7f71a85902f54c33b22436364825f9e6", "6f563e5f26f448418c80dde0b2972fc0", "1832eee72db74d98ac52d8bcbcda55ed", "83b68c2726de4b8dbdbf3c17656feb34", "9130bd931a514c7b907972b8a79271a1", "b4dadea5e04548d2869a2e54167d2c00", "cef4d791fa8b4a6c82fe4663b741dc96", "abe0bf510aa54619a67454f3e3e8d464", "93ffcc5552994f4bb6612622e4d61dbb", "71365afe521547e7aa4bb97441ee467a", "4fa95a7146e64822b4fc9315e0f62ef4", "1a6cdbaeeb604127a70e8ae3e8821e49", "b6541dcc037b44ed8ace345998b034aa", "de58f01b661d490d8502fbd6b62fa0fd", "22a7862deec74018b6a32dc109da4f57", "d97e0431bfa84449ae215a1cc0b6e2b4", "3b9d66e59ebb4a92a5dd920de420c8ca", "8a6b94a7aac04c418f99e2861c740f90", "7e5a9b43bacd4f229dc34dccbedc2ba7", "9f01a97dc2cb4440b7373b1b77b2dcc2", "7107de39aa054075ad92ececa545515e", "f5fe3b50a1864deb919ca8ed98d9df16", "4f034517b01043c8b8633820417bd4f6", "41082cf333954b95a29477e81055b9a1", "7cbe22af251140feae1a06e4f93bb28d", "48486712cc0a45e484ba5d0c51288331", "22b5a84440f645faa94302b65f524a4b", "e2bc2ecd21b246b8b199ff196d4b8bf0", "cb72b363c45b4ab5940887a140c01703", "b8ec658f1dd24fb39a8db2bd3354f1e7", "84d2e4d20107455e8f7119bfa430107b", "ed81b250a01a44e0b59aaa5539a95ff0", "0b4b1baafe9145509bf55681a8dbdc95", "40c864f01db644cb9f2f3fc024c6c24e", "a93e531e4d6a43c885e2b349b7518ccf", "cb1663910157427bba6f90e2c7eabae6", "df2381c12202445086eb397728b9ea20", "64116b5b9d814656acd5728bdd7b8013", "423336dcc580425fa038fa53759cbe32", "d4fb493d2e944dba8a4026a3b16034fd", "aac7ea2b89b34a71beb591627d01637b", "ea526cae4fe84932bafc104773eed143", "89fbf52a6f1b41618072fca0c738ec71", "f385f7d8a5114d0bbe096c7a7922b5c4", "527c32cb20c445dba3768df3c2fda080", "0781b94a83ee44c796078093a9de90e7", "11f63adfd3b7419a86ffb35efb3b71c5", "fab71e8074264a949bf6632cc98ca934", "dcc716277db346c1be333c191e9171d4", "59c39515757b4902a31771e8a88c2a17", "e56e9bdb56304636b42d25d0930d4bd3", "8e8c457526ca4dc1bd55e72455ccab74", "ce95e1727f154d299ef8b7b8df9ec7f8", "13172b1e5b3b49fbaeba8a35ed0b86dd", "41e9f573fc084259a272d485d31949c3", "ad9ca11ab88b4f4fae0aa2fdbc7b649a", "c1ac342424444547932fb97982d03033", "559df3788b16454cbca245b398519541", "00de9978fcc54c39b49080f147045f3e", "d4285ac7095c4fb29cf37e8add2297dc", "9421aa1d1e6548e6bf13b8fe4edc70be", "8e05e61139c746419cc88f5c254a4153" ] } }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Downloading preprocessed/captions.parquet from codeShare/sankaku_captioned_images ...\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "preprocessed/captions.parquet: reconstructing file: 0%| | 0.00B / 11.2MB " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "7a2c2e5a0e7d494eb887353925603b74" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "preprocessed/captions.parquet: downloading bytes: | 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "abe0bf510aa54619a67454f3e3e8d464" } }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "Downloaded → /content/sankaku_enrich_pass2/captions.parquet\n", "Loaded 7,768 rows.\n", "\n", "Loading Danbooru wiki dataset ...\n", "Wiki lookup ready: 195,141 usable tags.\n", "\n", "Scanning existing thinking_response for already-used tags ...\n", "Tags already used in the dataset: 3,816\n", "\n", "Second pass: appending to rows with < 30 words ...\n", " processed 5,000/7,768 | unique tags used: 4,294\n", "\n", "Second-pass results:\n", " • Rows already ≥ 30 words : 5,319\n", " • Newly appended : 2,346\n", " • Of which were re-uses : 1,742\n", " • Short rows with no matching tag : 0\n", " • Total unique tags used now : 4,468\n", "Local enriched parquet ready: /content/sankaku_enrich_pass2/captions.parquet\n", "\n", "Uploading updated preprocessed/captions.parquet ...\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "Processing Files (0 / 0) : | | 0.00B / 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "7e5a9b43bacd4f229dc34dccbedc2ba7" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "New Data Upload : | | 0.00B / 0.00B " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "b8ec658f1dd24fb39a8db2bd3354f1e7" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ " ...ch_pass2/captions.parquet: 85%|########5 | 10.0MB / 11.7MB " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "aac7ea2b89b34a71beb591627d01637b" } }, "metadata": {} }, { "output_type": "display_data", "data": { "text/plain": [ "Validating : | 0% " ], "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": "8e8c457526ca4dc1bd55e72455ccab74" } }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "\n", "✅ Done!\n", " Repo : https://huggingface.co/datasets/codeShare/sankaku_captioned_images\n", " File : preprocessed/captions.parquet\n" ] } ] } ]}qwen35_training/tag_definition.ipynbAdded+2075