hf_api.py 490 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450
  1. # coding=utf-8
  2. # Copyright 2019-present, the HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import annotations
  16. import base64
  17. import inspect
  18. import json
  19. import re
  20. import struct
  21. import time
  22. import warnings
  23. from collections import defaultdict
  24. from concurrent.futures import Future, ThreadPoolExecutor
  25. from dataclasses import asdict, dataclass, field
  26. from datetime import datetime
  27. from functools import wraps
  28. from itertools import islice
  29. from pathlib import Path
  30. from typing import (
  31. TYPE_CHECKING,
  32. Any,
  33. BinaryIO,
  34. Callable,
  35. Iterable,
  36. Iterator,
  37. Literal,
  38. Optional,
  39. Type,
  40. TypeVar,
  41. Union,
  42. overload,
  43. )
  44. from urllib.parse import quote
  45. import httpcore
  46. import httpx
  47. from tqdm.auto import tqdm as base_tqdm
  48. from tqdm.contrib.concurrent import thread_map
  49. from . import constants
  50. from ._commit_api import (
  51. CommitOperation,
  52. CommitOperationAdd,
  53. CommitOperationCopy,
  54. CommitOperationDelete,
  55. _fetch_files_to_copy,
  56. _fetch_upload_modes,
  57. _prepare_commit_payload,
  58. _upload_files,
  59. _warn_on_overwriting_operations,
  60. )
  61. from ._inference_endpoints import InferenceEndpoint, InferenceEndpointScalingMetric, InferenceEndpointType
  62. from ._jobs_api import JobHardware, JobInfo, JobSpec, ScheduledJobInfo, _create_job_spec
  63. from ._space_api import SpaceHardware, SpaceRuntime, SpaceStorage, SpaceVariable
  64. from ._upload_large_folder import upload_large_folder_internal
  65. from .community import (
  66. Discussion,
  67. DiscussionComment,
  68. DiscussionStatusChange,
  69. DiscussionTitleChange,
  70. DiscussionWithDetails,
  71. deserialize_event,
  72. )
  73. from .errors import (
  74. BadRequestError,
  75. GatedRepoError,
  76. HfHubHTTPError,
  77. LocalTokenNotFoundError,
  78. RemoteEntryNotFoundError,
  79. RepositoryNotFoundError,
  80. RevisionNotFoundError,
  81. )
  82. from .file_download import DryRunFileInfo, HfFileMetadata, get_hf_file_metadata, hf_hub_url
  83. from .repocard_data import DatasetCardData, ModelCardData, SpaceCardData
  84. from .utils import (
  85. DEFAULT_IGNORE_PATTERNS,
  86. NotASafetensorsRepoError,
  87. SafetensorsFileMetadata,
  88. SafetensorsParsingError,
  89. SafetensorsRepoMetadata,
  90. TensorInfo,
  91. build_hf_headers,
  92. chunk_iterable,
  93. experimental,
  94. filter_repo_objects,
  95. fix_hf_endpoint_in_url,
  96. get_session,
  97. get_token,
  98. hf_raise_for_status,
  99. logging,
  100. paginate,
  101. parse_datetime,
  102. validate_hf_hub_args,
  103. )
  104. from .utils import tqdm as hf_tqdm
  105. from .utils._auth import _get_token_from_environment, _get_token_from_file, _get_token_from_google_colab
  106. from .utils._deprecation import _deprecate_arguments
  107. from .utils._typing import CallableT
  108. from .utils._verification import collect_local_files, resolve_local_root, verify_maps
  109. from .utils.endpoint_helpers import _is_emission_within_threshold
  110. if TYPE_CHECKING:
  111. from .inference._providers import PROVIDER_T
  112. from .utils._verification import FolderVerification
  113. R = TypeVar("R") # Return type
  114. CollectionItemType_T = Literal["model", "dataset", "space", "paper", "collection"]
  115. ExpandModelProperty_T = Literal[
  116. "author",
  117. "baseModels",
  118. "cardData",
  119. "childrenModelCount",
  120. "config",
  121. "createdAt",
  122. "disabled",
  123. "downloads",
  124. "downloadsAllTime",
  125. "gated",
  126. "gguf",
  127. "inference",
  128. "inferenceProviderMapping",
  129. "lastModified",
  130. "library_name",
  131. "likes",
  132. "mask_token",
  133. "model-index",
  134. "pipeline_tag",
  135. "private",
  136. "resourceGroup",
  137. "safetensors",
  138. "sha",
  139. "siblings",
  140. "spaces",
  141. "tags",
  142. "transformersInfo",
  143. "trendingScore",
  144. "usedStorage",
  145. "widgetData",
  146. ]
  147. ExpandDatasetProperty_T = Literal[
  148. "author",
  149. "cardData",
  150. "citation",
  151. "createdAt",
  152. "description",
  153. "disabled",
  154. "downloads",
  155. "downloadsAllTime",
  156. "gated",
  157. "lastModified",
  158. "likes",
  159. "paperswithcode_id",
  160. "private",
  161. "resourceGroup",
  162. "sha",
  163. "siblings",
  164. "tags",
  165. "trendingScore",
  166. "usedStorage",
  167. ]
  168. ExpandSpaceProperty_T = Literal[
  169. "author",
  170. "cardData",
  171. "createdAt",
  172. "datasets",
  173. "disabled",
  174. "lastModified",
  175. "likes",
  176. "models",
  177. "private",
  178. "resourceGroup",
  179. "runtime",
  180. "sdk",
  181. "sha",
  182. "siblings",
  183. "subdomain",
  184. "tags",
  185. "trendingScore",
  186. "usedStorage",
  187. ]
  188. ModelSort_T = Literal["created_at", "downloads", "last_modified", "likes", "trending_score"]
  189. DatasetSort_T = Literal["created_at", "downloads", "last_modified", "likes", "trending_score"]
  190. SpaceSort_T = Literal["created_at", "last_modified", "likes", "trending_score"]
  191. USERNAME_PLACEHOLDER = "hf_user"
  192. _REGEX_DISCUSSION_URL = re.compile(r".*/discussions/(\d+)$")
  193. _REGEX_HTTP_PROTOCOL = re.compile(r"https?://")
  194. _CREATE_COMMIT_NO_REPO_ERROR_MESSAGE = (
  195. "\nNote: Creating a commit assumes that the repo already exists on the"
  196. " Huggingface Hub. Please use `create_repo` if it's not the case."
  197. )
  198. _AUTH_CHECK_NO_REPO_ERROR_MESSAGE = (
  199. "\nNote: The repository either does not exist or you do not have access rights."
  200. " Please check the repository ID and your access permissions."
  201. " If this is a private repository, ensure that your token is correct."
  202. )
  203. logger = logging.get_logger(__name__)
  204. def repo_type_and_id_from_hf_id(hf_id: str, hub_url: Optional[str] = None) -> tuple[Optional[str], Optional[str], str]:
  205. """
  206. Returns the repo type and ID from a huggingface.co URL linking to a
  207. repository
  208. Args:
  209. hf_id (`str`):
  210. An URL or ID of a repository on the HF hub. Accepted values are:
  211. - https://huggingface.co/<repo_type>/<namespace>/<repo_id>
  212. - https://huggingface.co/<namespace>/<repo_id>
  213. - hf://<repo_type>/<namespace>/<repo_id>
  214. - hf://<namespace>/<repo_id>
  215. - <repo_type>/<namespace>/<repo_id>
  216. - <namespace>/<repo_id>
  217. - <repo_id>
  218. hub_url (`str`, *optional*):
  219. The URL of the HuggingFace Hub, defaults to https://huggingface.co
  220. Returns:
  221. A tuple with three items: repo_type (`str` or `None`), namespace (`str` or
  222. `None`) and repo_id (`str`).
  223. Raises:
  224. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  225. If URL cannot be parsed.
  226. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  227. If `repo_type` is unknown.
  228. """
  229. input_hf_id = hf_id
  230. # Get the hub_url (with or without protocol)
  231. full_hub_url = hub_url if hub_url is not None else constants.ENDPOINT
  232. hub_url_without_protocol = _REGEX_HTTP_PROTOCOL.sub("", full_hub_url)
  233. # Check if hf_id is a URL containing the hub_url (check both with and without protocol)
  234. hf_id_without_protocol = _REGEX_HTTP_PROTOCOL.sub("", hf_id)
  235. is_hf_url = hub_url_without_protocol in hf_id_without_protocol and "@" not in hf_id
  236. HFFS_PREFIX = "hf://"
  237. if hf_id.startswith(HFFS_PREFIX): # Remove "hf://" prefix if exists
  238. hf_id = hf_id[len(HFFS_PREFIX) :]
  239. # If it's a URL, strip the endpoint prefix to get the path
  240. if is_hf_url:
  241. # Remove protocol if present
  242. hf_id_normalized = _REGEX_HTTP_PROTOCOL.sub("", hf_id)
  243. # Remove the hub_url prefix to get the relative path
  244. if hf_id_normalized.startswith(hub_url_without_protocol):
  245. # Strip the hub URL and any leading slashes
  246. hf_id = hf_id_normalized[len(hub_url_without_protocol) :].lstrip("/")
  247. url_segments = hf_id.split("/")
  248. is_hf_id = len(url_segments) <= 3
  249. namespace: Optional[str]
  250. if is_hf_url:
  251. # For URLs, we need to extract repo_type, namespace, repo_id
  252. # Expected format after stripping endpoint: [repo_type]/namespace/repo_id or namespace/repo_id
  253. if len(url_segments) >= 3:
  254. # Check if first segment is a repo type
  255. if url_segments[0] in constants.REPO_TYPES_MAPPING:
  256. repo_type = constants.REPO_TYPES_MAPPING[url_segments[0]]
  257. namespace = url_segments[1]
  258. repo_id = url_segments[2]
  259. else:
  260. # First segment is namespace
  261. namespace = url_segments[0]
  262. repo_id = url_segments[1]
  263. repo_type = None
  264. elif len(url_segments) == 2:
  265. namespace = url_segments[0]
  266. repo_id = url_segments[1]
  267. # Check if namespace is actually a repo type mapping
  268. if namespace in constants.REPO_TYPES_MAPPING:
  269. # Mean canonical dataset or model
  270. repo_type = constants.REPO_TYPES_MAPPING[namespace]
  271. namespace = None
  272. else:
  273. repo_type = None
  274. else:
  275. # Single segment
  276. repo_id = url_segments[0]
  277. namespace = None
  278. repo_type = None
  279. elif is_hf_id:
  280. if len(url_segments) == 3:
  281. # Passed <repo_type>/<user>/<model_id> or <repo_type>/<org>/<model_id>
  282. repo_type, namespace, repo_id = url_segments[-3:]
  283. elif len(url_segments) == 2:
  284. if url_segments[0] in constants.REPO_TYPES_MAPPING:
  285. # Passed '<model_id>' or 'datasets/<dataset_id>' for a canonical model or dataset
  286. repo_type = constants.REPO_TYPES_MAPPING[url_segments[0]]
  287. namespace = None
  288. repo_id = hf_id.split("/")[-1]
  289. else:
  290. # Passed <user>/<model_id> or <org>/<model_id>
  291. namespace, repo_id = hf_id.split("/")[-2:]
  292. repo_type = None
  293. else:
  294. # Passed <model_id>
  295. repo_id = url_segments[0]
  296. namespace, repo_type = None, None
  297. else:
  298. raise ValueError(f"Unable to retrieve user and repo ID from the passed HF ID: {hf_id}")
  299. # Check if repo type is known (mapping "spaces" => "space" + empty value => `None`)
  300. if repo_type in constants.REPO_TYPES_MAPPING:
  301. repo_type = constants.REPO_TYPES_MAPPING[repo_type]
  302. if repo_type == "":
  303. repo_type = None
  304. if repo_type not in constants.REPO_TYPES:
  305. raise ValueError(f"Unknown `repo_type`: '{repo_type}' ('{input_hf_id}')")
  306. return repo_type, namespace, repo_id
  307. @dataclass
  308. class LastCommitInfo(dict):
  309. oid: str
  310. title: str
  311. date: datetime
  312. def __post_init__(self): # hack to make LastCommitInfo backward compatible
  313. self.update(asdict(self))
  314. @dataclass
  315. class BlobLfsInfo(dict):
  316. size: int
  317. sha256: str
  318. pointer_size: int
  319. def __post_init__(self): # hack to make BlobLfsInfo backward compatible
  320. self.update(asdict(self))
  321. @dataclass
  322. class BlobSecurityInfo(dict):
  323. safe: bool # duplicate information with "status" field, keeping it for backward compatibility
  324. status: str
  325. av_scan: Optional[dict]
  326. pickle_import_scan: Optional[dict]
  327. def __post_init__(self): # hack to make BlogSecurityInfo backward compatible
  328. self.update(asdict(self))
  329. @dataclass
  330. class TransformersInfo(dict):
  331. auto_model: str
  332. custom_class: Optional[str] = None
  333. # possible `pipeline_tag` values: https://github.com/huggingface/huggingface.js/blob/3ee32554b8620644a6287e786b2a83bf5caf559c/packages/tasks/src/pipelines.ts#L72
  334. pipeline_tag: Optional[str] = None
  335. processor: Optional[str] = None
  336. def __post_init__(self): # hack to make TransformersInfo backward compatible
  337. self.update(asdict(self))
  338. @dataclass
  339. class SafeTensorsInfo(dict):
  340. parameters: dict[str, int]
  341. total: int
  342. def __post_init__(self): # hack to make SafeTensorsInfo backward compatible
  343. self.update(asdict(self))
  344. @dataclass
  345. class CommitInfo(str):
  346. """Data structure containing information about a newly created commit.
  347. Returned by any method that creates a commit on the Hub: [`create_commit`], [`upload_file`], [`upload_folder`],
  348. [`delete_file`], [`delete_folder`]. It inherits from `str` for backward compatibility but using methods specific
  349. to `str` is deprecated.
  350. Attributes:
  351. commit_url (`str`):
  352. Url where to find the commit.
  353. commit_message (`str`):
  354. The summary (first line) of the commit that has been created.
  355. commit_description (`str`):
  356. Description of the commit that has been created. Can be empty.
  357. oid (`str`):
  358. Commit hash id. Example: `"91c54ad1727ee830252e457677f467be0bfd8a57"`.
  359. pr_url (`str`, *optional*):
  360. Url to the PR that has been created, if any. Populated when `create_pr=True`
  361. is passed.
  362. pr_revision (`str`, *optional*):
  363. Revision of the PR that has been created, if any. Populated when
  364. `create_pr=True` is passed. Example: `"refs/pr/1"`.
  365. pr_num (`int`, *optional*):
  366. Number of the PR discussion that has been created, if any. Populated when
  367. `create_pr=True` is passed. Can be passed as `discussion_num` in
  368. [`get_discussion_details`]. Example: `1`.
  369. repo_url (`RepoUrl`):
  370. Repo URL of the commit containing info like repo_id, repo_type, etc.
  371. """
  372. commit_url: str
  373. commit_message: str
  374. commit_description: str
  375. oid: str
  376. _endpoint: Optional[str] = field(repr=False)
  377. pr_url: Optional[str] = None
  378. # Computed from `commit_url` in `__post_init__`
  379. repo_url: RepoUrl = field(init=False)
  380. # Computed from `pr_url` in `__post_init__`
  381. pr_revision: Optional[str] = field(init=False)
  382. pr_num: Optional[int] = field(init=False)
  383. def __new__(cls, *args, commit_url: str, **kwargs):
  384. return str.__new__(cls, commit_url)
  385. def __post_init__(self):
  386. """Populate pr-related fields after initialization.
  387. See https://docs.python.org/3.10/library/dataclasses.html#post-init-processing.
  388. """
  389. # Repo info
  390. self.repo_url = RepoUrl(self.commit_url.split("/commit/")[0], endpoint=self._endpoint)
  391. # PR info
  392. if self.pr_url is not None:
  393. self.pr_revision = _parse_revision_from_pr_url(self.pr_url)
  394. self.pr_num = int(self.pr_revision.split("/")[-1])
  395. else:
  396. self.pr_revision = None
  397. self.pr_num = None
  398. @dataclass
  399. class AccessRequest:
  400. """Data structure containing information about a user access request.
  401. Attributes:
  402. username (`str`):
  403. Username of the user who requested access.
  404. fullname (`str`):
  405. Fullname of the user who requested access.
  406. email (`Optional[str]`):
  407. Email of the user who requested access.
  408. Can only be `None` in the /accepted list if the user was granted access manually.
  409. timestamp (`datetime`):
  410. Timestamp of the request.
  411. status (`Literal["pending", "accepted", "rejected"]`):
  412. Status of the request. Can be one of `["pending", "accepted", "rejected"]`.
  413. fields (`dict[str, Any]`, *optional*):
  414. Additional fields filled by the user in the gate form.
  415. """
  416. username: str
  417. fullname: str
  418. email: Optional[str]
  419. timestamp: datetime
  420. status: Literal["pending", "accepted", "rejected"]
  421. # Additional fields filled by the user in the gate form
  422. fields: Optional[dict[str, Any]] = None
  423. @dataclass
  424. class WebhookWatchedItem:
  425. """Data structure containing information about the items watched by a webhook.
  426. Attributes:
  427. type (`Literal["dataset", "model", "org", "space", "user"]`):
  428. Type of the item to be watched. Can be one of `["dataset", "model", "org", "space", "user"]`.
  429. name (`str`):
  430. Name of the item to be watched. Can be the username, organization name, model name, dataset name or space name.
  431. """
  432. type: Literal["dataset", "model", "org", "space", "user"]
  433. name: str
  434. @dataclass
  435. class WebhookInfo:
  436. """Data structure containing information about a webhook.
  437. One of `url` or `job` is specified, but not both.
  438. Attributes:
  439. id (`str`):
  440. ID of the webhook.
  441. url (`str`, *optional*):
  442. URL of the webhook.
  443. job (`JobSpec`, *optional*):
  444. Specifications of the Job to trigger.
  445. watched (`list[WebhookWatchedItem]`):
  446. List of items watched by the webhook, see [`WebhookWatchedItem`].
  447. domains (`list[WEBHOOK_DOMAIN_T]`):
  448. List of domains the webhook is watching. Can be one of `["repo", "discussions"]`.
  449. secret (`str`, *optional*):
  450. Secret of the webhook.
  451. disabled (`bool`):
  452. Whether the webhook is disabled or not.
  453. """
  454. id: str
  455. url: Optional[str]
  456. job: Optional[JobSpec]
  457. watched: list[WebhookWatchedItem]
  458. domains: list[constants.WEBHOOK_DOMAIN_T]
  459. secret: Optional[str]
  460. disabled: bool
  461. class RepoUrl(str):
  462. """Subclass of `str` describing a repo URL on the Hub.
  463. `RepoUrl` is returned by `HfApi.create_repo`. It inherits from `str` for backward
  464. compatibility. At initialization, the URL is parsed to populate properties:
  465. - endpoint (`str`)
  466. - namespace (`Optional[str]`)
  467. - repo_name (`str`)
  468. - repo_id (`str`)
  469. - repo_type (`Literal["model", "dataset", "space"]`)
  470. - url (`str`)
  471. Args:
  472. url (`Any`):
  473. String value of the repo url.
  474. endpoint (`str`, *optional*):
  475. Endpoint of the Hub. Defaults to <https://huggingface.co>.
  476. Example:
  477. ```py
  478. >>> RepoUrl('https://huggingface.co/gpt2')
  479. RepoUrl('https://huggingface.co/gpt2', endpoint='https://huggingface.co', repo_type='model', repo_id='gpt2')
  480. >>> RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co')
  481. RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co', repo_type='dataset', repo_id='dummy_user/dummy_dataset')
  482. >>> RepoUrl('hf://datasets/my-user/my-dataset')
  483. RepoUrl('hf://datasets/my-user/my-dataset', endpoint='https://huggingface.co', repo_type='dataset', repo_id='user/dataset')
  484. >>> HfApi.create_repo("dummy_model")
  485. RepoUrl('https://huggingface.co/Wauplin/dummy_model', endpoint='https://huggingface.co', repo_type='model', repo_id='Wauplin/dummy_model')
  486. ```
  487. Raises:
  488. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  489. If URL cannot be parsed.
  490. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  491. If `repo_type` is unknown.
  492. """
  493. def __new__(cls, url: Any, endpoint: Optional[str] = None):
  494. url = fix_hf_endpoint_in_url(url, endpoint=endpoint)
  495. return super(RepoUrl, cls).__new__(cls, url)
  496. def __init__(self, url: Any, endpoint: Optional[str] = None) -> None:
  497. super().__init__()
  498. # Parse URL
  499. self.endpoint = endpoint or constants.ENDPOINT
  500. repo_type, namespace, repo_name = repo_type_and_id_from_hf_id(self, hub_url=self.endpoint)
  501. # Populate fields
  502. self.namespace = namespace
  503. self.repo_name = repo_name
  504. self.repo_id = repo_name if namespace is None else f"{namespace}/{repo_name}"
  505. self.repo_type = repo_type or constants.REPO_TYPE_MODEL
  506. self.url = str(self) # just in case it's needed
  507. def __repr__(self) -> str:
  508. return f"RepoUrl('{self}', endpoint='{self.endpoint}', repo_type='{self.repo_type}', repo_id='{self.repo_id}')"
  509. @dataclass
  510. class RepoSibling:
  511. """
  512. Contains basic information about a repo file inside a repo on the Hub.
  513. > [!TIP]
  514. > All attributes of this class are optional except `rfilename`. This is because only the file names are returned when
  515. > listing repositories on the Hub (with [`list_models`], [`list_datasets`] or [`list_spaces`]). If you need more
  516. > information like file size, blob id or lfs details, you must request them specifically from one repo at a time
  517. > (using [`model_info`], [`dataset_info`] or [`space_info`]) as it adds more constraints on the backend server to
  518. > retrieve these.
  519. Attributes:
  520. rfilename (str):
  521. file name, relative to the repo root.
  522. size (`int`, *optional*):
  523. The file's size, in bytes. This attribute is defined when `files_metadata` argument of [`repo_info`] is set
  524. to `True`. It's `None` otherwise.
  525. blob_id (`str`, *optional*):
  526. The file's git OID. This attribute is defined when `files_metadata` argument of [`repo_info`] is set to
  527. `True`. It's `None` otherwise.
  528. lfs (`BlobLfsInfo`, *optional*):
  529. The file's LFS metadata. This attribute is defined when`files_metadata` argument of [`repo_info`] is set to
  530. `True` and the file is stored with Git LFS. It's `None` otherwise.
  531. """
  532. rfilename: str
  533. size: Optional[int] = None
  534. blob_id: Optional[str] = None
  535. lfs: Optional[BlobLfsInfo] = None
  536. @dataclass
  537. class RepoFile:
  538. """
  539. Contains information about a file on the Hub.
  540. Attributes:
  541. path (str):
  542. file path relative to the repo root.
  543. size (`int`):
  544. The file's size, in bytes.
  545. blob_id (`str`):
  546. The file's git OID.
  547. lfs (`BlobLfsInfo`, *optional*):
  548. The file's LFS metadata.
  549. last_commit (`LastCommitInfo`, *optional*):
  550. The file's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
  551. are called with `expand=True`.
  552. security (`BlobSecurityInfo`, *optional*):
  553. The file's security scan metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
  554. are called with `expand=True`.
  555. """
  556. path: str
  557. size: int
  558. blob_id: str
  559. lfs: Optional[BlobLfsInfo] = None
  560. last_commit: Optional[LastCommitInfo] = None
  561. security: Optional[BlobSecurityInfo] = None
  562. def __init__(self, **kwargs):
  563. self.path = kwargs.pop("path")
  564. self.size = kwargs.pop("size")
  565. self.blob_id = kwargs.pop("oid")
  566. lfs = kwargs.pop("lfs", None)
  567. if lfs is not None:
  568. lfs = BlobLfsInfo(size=lfs["size"], sha256=lfs["oid"], pointer_size=lfs["pointerSize"])
  569. self.lfs = lfs
  570. last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None)
  571. if last_commit is not None:
  572. last_commit = LastCommitInfo(
  573. oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"])
  574. )
  575. self.last_commit = last_commit
  576. security = kwargs.pop("securityFileStatus", None)
  577. if security is not None:
  578. safe = security["status"] == "safe"
  579. security = BlobSecurityInfo(
  580. safe=safe,
  581. status=security["status"],
  582. av_scan=security["avScan"],
  583. pickle_import_scan=security["pickleImportScan"],
  584. )
  585. self.security = security
  586. # backwards compatibility
  587. self.rfilename = self.path
  588. self.lastCommit = self.last_commit
  589. @dataclass
  590. class RepoFolder:
  591. """
  592. Contains information about a folder on the Hub.
  593. Attributes:
  594. path (str):
  595. folder path relative to the repo root.
  596. tree_id (`str`):
  597. The folder's git OID.
  598. last_commit (`LastCommitInfo`, *optional*):
  599. The folder's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
  600. are called with `expand=True`.
  601. """
  602. path: str
  603. tree_id: str
  604. last_commit: Optional[LastCommitInfo] = None
  605. def __init__(self, **kwargs):
  606. self.path = kwargs.pop("path")
  607. self.tree_id = kwargs.pop("oid")
  608. last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None)
  609. if last_commit is not None:
  610. last_commit = LastCommitInfo(
  611. oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"])
  612. )
  613. self.last_commit = last_commit
  614. @dataclass
  615. class InferenceProviderMapping:
  616. provider: "PROVIDER_T" # Provider name
  617. hf_model_id: str # ID of the model on the Hugging Face Hub
  618. provider_id: str # ID of the model on the provider's side
  619. status: Literal["error", "live", "staging"]
  620. task: str
  621. adapter: Optional[str] = None
  622. adapter_weights_path: Optional[str] = None
  623. type: Optional[Literal["single-model", "tag-filter"]] = None
  624. def __init__(self, **kwargs):
  625. self.provider = kwargs.pop("provider")
  626. self.hf_model_id = kwargs.pop("hf_model_id")
  627. self.provider_id = kwargs.pop("providerId")
  628. self.status = kwargs.pop("status")
  629. self.task = kwargs.pop("task")
  630. self.adapter = kwargs.pop("adapter", None)
  631. self.adapter_weights_path = kwargs.pop("adapterWeightsPath", None)
  632. self.type = kwargs.pop("type", None)
  633. self.__dict__.update(**kwargs)
  634. @dataclass
  635. class ModelInfo:
  636. """
  637. Contains information about a model on the Hub. This object is returned by [`model_info`] and [`list_models`].
  638. > [!TIP]
  639. > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
  640. > In general, the more specific the query, the more information is returned. On the contrary, when listing models
  641. > using [`list_models`] only a subset of the attributes are returned.
  642. Attributes:
  643. id (`str`):
  644. ID of model.
  645. author (`str`, *optional*):
  646. Author of the model.
  647. sha (`str`, *optional*):
  648. Repo SHA at this particular revision.
  649. created_at (`datetime`, *optional*):
  650. Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
  651. corresponding to the date when we began to store creation dates.
  652. last_modified (`datetime`, *optional*):
  653. Date of last commit to the repo.
  654. private (`bool`):
  655. Is the repo private.
  656. disabled (`bool`, *optional*):
  657. Is the repo disabled.
  658. downloads (`int`):
  659. Number of downloads of the model over the last 30 days.
  660. downloads_all_time (`int`):
  661. Cumulated number of downloads of the model since its creation.
  662. gated (`Literal["auto", "manual", False]`, *optional*):
  663. Is the repo gated.
  664. If so, whether there is manual or automatic approval.
  665. gguf (`dict`, *optional*):
  666. GGUF information of the model.
  667. inference (`Literal["warm"]`, *optional*):
  668. Status of the model on Inference Providers. Warm if the model is served by at least one provider.
  669. inference_provider_mapping (`list[InferenceProviderMapping]`, *optional*):
  670. A list of [`InferenceProviderMapping`] ordered after the user's provider order.
  671. likes (`int`):
  672. Number of likes of the model.
  673. library_name (`str`, *optional*):
  674. Library associated with the model.
  675. tags (`list[str]`):
  676. List of tags of the model. Compared to `card_data.tags`, contains extra tags computed by the Hub
  677. (e.g. supported libraries, model's arXiv).
  678. pipeline_tag (`str`, *optional*):
  679. Pipeline tag associated with the model.
  680. mask_token (`str`, *optional*):
  681. Mask token used by the model.
  682. widget_data (`Any`, *optional*):
  683. Widget data associated with the model.
  684. model_index (`dict`, *optional*):
  685. Model index for evaluation.
  686. config (`dict`, *optional*):
  687. Model configuration.
  688. transformers_info (`TransformersInfo`, *optional*):
  689. Transformers-specific info (auto class, processor, etc.) associated with the model.
  690. trending_score (`int`, *optional*):
  691. Trending score of the model.
  692. card_data (`ModelCardData`, *optional*):
  693. Model Card Metadata as a [`huggingface_hub.repocard_data.ModelCardData`] object.
  694. siblings (`list[RepoSibling]`):
  695. List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the model.
  696. spaces (`list[str]`, *optional*):
  697. List of spaces using the model.
  698. safetensors (`SafeTensorsInfo`, *optional*):
  699. Model's safetensors information.
  700. security_repo_status (`dict`, *optional*):
  701. Model's security scan status.
  702. """
  703. id: str
  704. author: Optional[str]
  705. sha: Optional[str]
  706. created_at: Optional[datetime]
  707. last_modified: Optional[datetime]
  708. private: Optional[bool]
  709. disabled: Optional[bool]
  710. downloads: Optional[int]
  711. downloads_all_time: Optional[int]
  712. gated: Optional[Literal["auto", "manual", False]]
  713. gguf: Optional[dict]
  714. inference: Optional[Literal["warm"]]
  715. inference_provider_mapping: Optional[list[InferenceProviderMapping]]
  716. likes: Optional[int]
  717. library_name: Optional[str]
  718. tags: Optional[list[str]]
  719. pipeline_tag: Optional[str]
  720. mask_token: Optional[str]
  721. card_data: Optional[ModelCardData]
  722. widget_data: Optional[Any]
  723. model_index: Optional[dict]
  724. config: Optional[dict]
  725. transformers_info: Optional[TransformersInfo]
  726. trending_score: Optional[int]
  727. siblings: Optional[list[RepoSibling]]
  728. spaces: Optional[list[str]]
  729. safetensors: Optional[SafeTensorsInfo]
  730. security_repo_status: Optional[dict]
  731. def __init__(self, **kwargs):
  732. self.id = kwargs.pop("id")
  733. self.author = kwargs.pop("author", None)
  734. self.sha = kwargs.pop("sha", None)
  735. last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
  736. self.last_modified = parse_datetime(last_modified) if last_modified else None
  737. created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
  738. self.created_at = parse_datetime(created_at) if created_at else None
  739. self.private = kwargs.pop("private", None)
  740. self.gated = kwargs.pop("gated", None)
  741. self.disabled = kwargs.pop("disabled", None)
  742. self.downloads = kwargs.pop("downloads", None)
  743. self.downloads_all_time = kwargs.pop("downloadsAllTime", None)
  744. self.likes = kwargs.pop("likes", None)
  745. self.library_name = kwargs.pop("library_name", None)
  746. self.gguf = kwargs.pop("gguf", None)
  747. self.inference = kwargs.pop("inference", None)
  748. # little hack to simplify Inference Providers logic and make it backward and forward compatible
  749. # right now, API returns a dict on model_info and a list on list_models. Let's harmonize to list.
  750. mapping = kwargs.pop("inferenceProviderMapping", None)
  751. if isinstance(mapping, list):
  752. self.inference_provider_mapping = [
  753. InferenceProviderMapping(**{**value, "hf_model_id": self.id}) for value in mapping
  754. ]
  755. elif isinstance(mapping, dict):
  756. self.inference_provider_mapping = [
  757. InferenceProviderMapping(**{**value, "hf_model_id": self.id, "provider": provider})
  758. for provider, value in mapping.items()
  759. ]
  760. elif mapping is None:
  761. self.inference_provider_mapping = None
  762. else:
  763. raise ValueError(
  764. f"Unexpected type for `inferenceProviderMapping`. Expecting `dict` or `list`. Got {mapping}."
  765. )
  766. self.tags = kwargs.pop("tags", None)
  767. self.pipeline_tag = kwargs.pop("pipeline_tag", None)
  768. self.mask_token = kwargs.pop("mask_token", None)
  769. self.trending_score = kwargs.pop("trendingScore", None)
  770. card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
  771. self.card_data = (
  772. ModelCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
  773. )
  774. self.widget_data = kwargs.pop("widgetData", None)
  775. self.model_index = kwargs.pop("model-index", None) or kwargs.pop("model_index", None)
  776. self.config = kwargs.pop("config", None)
  777. transformers_info = kwargs.pop("transformersInfo", None) or kwargs.pop("transformers_info", None)
  778. self.transformers_info = TransformersInfo(**transformers_info) if transformers_info else None
  779. siblings = kwargs.pop("siblings", None)
  780. self.siblings = (
  781. [
  782. RepoSibling(
  783. rfilename=sibling["rfilename"],
  784. size=sibling.get("size"),
  785. blob_id=sibling.get("blobId"),
  786. lfs=(
  787. BlobLfsInfo(
  788. size=sibling["lfs"]["size"],
  789. sha256=sibling["lfs"]["sha256"],
  790. pointer_size=sibling["lfs"]["pointerSize"],
  791. )
  792. if sibling.get("lfs")
  793. else None
  794. ),
  795. )
  796. for sibling in siblings
  797. ]
  798. if siblings is not None
  799. else None
  800. )
  801. self.spaces = kwargs.pop("spaces", None)
  802. safetensors = kwargs.pop("safetensors", None)
  803. self.safetensors = (
  804. SafeTensorsInfo(
  805. parameters=safetensors["parameters"],
  806. total=safetensors["total"],
  807. )
  808. if safetensors
  809. else None
  810. )
  811. self.security_repo_status = kwargs.pop("securityRepoStatus", None)
  812. # backwards compatibility
  813. self.lastModified = self.last_modified
  814. self.cardData = self.card_data
  815. self.transformersInfo = self.transformers_info
  816. self.__dict__.update(**kwargs)
  817. @dataclass
  818. class DatasetInfo:
  819. """
  820. Contains information about a dataset on the Hub. This object is returned by [`dataset_info`] and [`list_datasets`].
  821. > [!TIP]
  822. > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
  823. > In general, the more specific the query, the more information is returned. On the contrary, when listing datasets
  824. > using [`list_datasets`] only a subset of the attributes are returned.
  825. Attributes:
  826. id (`str`):
  827. ID of dataset.
  828. author (`str`):
  829. Author of the dataset.
  830. sha (`str`):
  831. Repo SHA at this particular revision.
  832. created_at (`datetime`, *optional*):
  833. Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
  834. corresponding to the date when we began to store creation dates.
  835. last_modified (`datetime`, *optional*):
  836. Date of last commit to the repo.
  837. private (`bool`):
  838. Is the repo private.
  839. disabled (`bool`, *optional*):
  840. Is the repo disabled.
  841. gated (`Literal["auto", "manual", False]`, *optional*):
  842. Is the repo gated.
  843. If so, whether there is manual or automatic approval.
  844. downloads (`int`):
  845. Number of downloads of the dataset over the last 30 days.
  846. downloads_all_time (`int`):
  847. Cumulated number of downloads of the model since its creation.
  848. likes (`int`):
  849. Number of likes of the dataset.
  850. tags (`list[str]`):
  851. List of tags of the dataset.
  852. card_data (`DatasetCardData`, *optional*):
  853. Model Card Metadata as a [`huggingface_hub.repocard_data.DatasetCardData`] object.
  854. siblings (`list[RepoSibling]`):
  855. List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the dataset.
  856. paperswithcode_id (`str`, *optional*):
  857. Papers with code ID of the dataset.
  858. trending_score (`int`, *optional*):
  859. Trending score of the dataset.
  860. """
  861. id: str
  862. author: Optional[str]
  863. sha: Optional[str]
  864. created_at: Optional[datetime]
  865. last_modified: Optional[datetime]
  866. private: Optional[bool]
  867. gated: Optional[Literal["auto", "manual", False]]
  868. disabled: Optional[bool]
  869. downloads: Optional[int]
  870. downloads_all_time: Optional[int]
  871. likes: Optional[int]
  872. paperswithcode_id: Optional[str]
  873. tags: Optional[list[str]]
  874. trending_score: Optional[int]
  875. card_data: Optional[DatasetCardData]
  876. siblings: Optional[list[RepoSibling]]
  877. def __init__(self, **kwargs):
  878. self.id = kwargs.pop("id")
  879. self.author = kwargs.pop("author", None)
  880. self.sha = kwargs.pop("sha", None)
  881. created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
  882. self.created_at = parse_datetime(created_at) if created_at else None
  883. last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
  884. self.last_modified = parse_datetime(last_modified) if last_modified else None
  885. self.private = kwargs.pop("private", None)
  886. self.gated = kwargs.pop("gated", None)
  887. self.disabled = kwargs.pop("disabled", None)
  888. self.downloads = kwargs.pop("downloads", None)
  889. self.downloads_all_time = kwargs.pop("downloadsAllTime", None)
  890. self.likes = kwargs.pop("likes", None)
  891. self.paperswithcode_id = kwargs.pop("paperswithcode_id", None)
  892. self.tags = kwargs.pop("tags", None)
  893. self.trending_score = kwargs.pop("trendingScore", None)
  894. card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
  895. self.card_data = (
  896. DatasetCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
  897. )
  898. siblings = kwargs.pop("siblings", None)
  899. self.siblings = (
  900. [
  901. RepoSibling(
  902. rfilename=sibling["rfilename"],
  903. size=sibling.get("size"),
  904. blob_id=sibling.get("blobId"),
  905. lfs=(
  906. BlobLfsInfo(
  907. size=sibling["lfs"]["size"],
  908. sha256=sibling["lfs"]["sha256"],
  909. pointer_size=sibling["lfs"]["pointerSize"],
  910. )
  911. if sibling.get("lfs")
  912. else None
  913. ),
  914. )
  915. for sibling in siblings
  916. ]
  917. if siblings is not None
  918. else None
  919. )
  920. # backwards compatibility
  921. self.lastModified = self.last_modified
  922. self.cardData = self.card_data
  923. self.__dict__.update(**kwargs)
  924. @dataclass
  925. class SpaceInfo:
  926. """
  927. Contains information about a Space on the Hub. This object is returned by [`space_info`] and [`list_spaces`].
  928. > [!TIP]
  929. > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
  930. > In general, the more specific the query, the more information is returned. On the contrary, when listing spaces
  931. > using [`list_spaces`] only a subset of the attributes are returned.
  932. Attributes:
  933. id (`str`):
  934. ID of the Space.
  935. author (`str`, *optional*):
  936. Author of the Space.
  937. sha (`str`, *optional*):
  938. Repo SHA at this particular revision.
  939. created_at (`datetime`, *optional*):
  940. Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
  941. corresponding to the date when we began to store creation dates.
  942. last_modified (`datetime`, *optional*):
  943. Date of last commit to the repo.
  944. private (`bool`):
  945. Is the repo private.
  946. gated (`Literal["auto", "manual", False]`, *optional*):
  947. Is the repo gated.
  948. If so, whether there is manual or automatic approval.
  949. disabled (`bool`, *optional*):
  950. Is the Space disabled.
  951. host (`str`, *optional*):
  952. Host URL of the Space.
  953. subdomain (`str`, *optional*):
  954. Subdomain of the Space.
  955. likes (`int`):
  956. Number of likes of the Space.
  957. tags (`list[str]`):
  958. List of tags of the Space.
  959. siblings (`list[RepoSibling]`):
  960. List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the Space.
  961. card_data (`SpaceCardData`, *optional*):
  962. Space Card Metadata as a [`huggingface_hub.repocard_data.SpaceCardData`] object.
  963. runtime (`SpaceRuntime`, *optional*):
  964. Space runtime information as a [`huggingface_hub.hf_api.SpaceRuntime`] object.
  965. sdk (`str`, *optional*):
  966. SDK used by the Space.
  967. models (`list[str]`, *optional*):
  968. List of models used by the Space.
  969. datasets (`list[str]`, *optional*):
  970. List of datasets used by the Space.
  971. trending_score (`int`, *optional*):
  972. Trending score of the Space.
  973. """
  974. id: str
  975. author: Optional[str]
  976. sha: Optional[str]
  977. created_at: Optional[datetime]
  978. last_modified: Optional[datetime]
  979. private: Optional[bool]
  980. gated: Optional[Literal["auto", "manual", False]]
  981. disabled: Optional[bool]
  982. host: Optional[str]
  983. subdomain: Optional[str]
  984. likes: Optional[int]
  985. sdk: Optional[str]
  986. tags: Optional[list[str]]
  987. siblings: Optional[list[RepoSibling]]
  988. trending_score: Optional[int]
  989. card_data: Optional[SpaceCardData]
  990. runtime: Optional[SpaceRuntime]
  991. models: Optional[list[str]]
  992. datasets: Optional[list[str]]
  993. def __init__(self, **kwargs):
  994. self.id = kwargs.pop("id")
  995. self.author = kwargs.pop("author", None)
  996. self.sha = kwargs.pop("sha", None)
  997. created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
  998. self.created_at = parse_datetime(created_at) if created_at else None
  999. last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
  1000. self.last_modified = parse_datetime(last_modified) if last_modified else None
  1001. self.private = kwargs.pop("private", None)
  1002. self.gated = kwargs.pop("gated", None)
  1003. self.disabled = kwargs.pop("disabled", None)
  1004. self.host = kwargs.pop("host", None)
  1005. self.subdomain = kwargs.pop("subdomain", None)
  1006. self.likes = kwargs.pop("likes", None)
  1007. self.sdk = kwargs.pop("sdk", None)
  1008. self.tags = kwargs.pop("tags", None)
  1009. self.trending_score = kwargs.pop("trendingScore", None)
  1010. card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
  1011. self.card_data = (
  1012. SpaceCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
  1013. )
  1014. siblings = kwargs.pop("siblings", None)
  1015. self.siblings = (
  1016. [
  1017. RepoSibling(
  1018. rfilename=sibling["rfilename"],
  1019. size=sibling.get("size"),
  1020. blob_id=sibling.get("blobId"),
  1021. lfs=(
  1022. BlobLfsInfo(
  1023. size=sibling["lfs"]["size"],
  1024. sha256=sibling["lfs"]["sha256"],
  1025. pointer_size=sibling["lfs"]["pointerSize"],
  1026. )
  1027. if sibling.get("lfs")
  1028. else None
  1029. ),
  1030. )
  1031. for sibling in siblings
  1032. ]
  1033. if siblings is not None
  1034. else None
  1035. )
  1036. runtime = kwargs.pop("runtime", None)
  1037. self.runtime = SpaceRuntime(runtime) if runtime else None
  1038. self.models = kwargs.pop("models", None)
  1039. self.datasets = kwargs.pop("datasets", None)
  1040. # backwards compatibility
  1041. self.lastModified = self.last_modified
  1042. self.cardData = self.card_data
  1043. self.__dict__.update(**kwargs)
  1044. @dataclass
  1045. class CollectionItem:
  1046. """
  1047. Contains information about an item of a Collection (model, dataset, Space, paper or collection).
  1048. Attributes:
  1049. item_object_id (`str`):
  1050. Unique ID of the item in the collection.
  1051. item_id (`str`):
  1052. ID of the underlying object on the Hub. Can be either a repo_id, a paper id or a collection slug.
  1053. e.g. `"jbilcke-hf/ai-comic-factory"`, `"2307.09288"`, `"celinah/cerebras-function-calling-682607169c35fbfa98b30b9a"`.
  1054. item_type (`str`):
  1055. Type of the underlying object. Can be one of `"model"`, `"dataset"`, `"space"`, `"paper"` or `"collection"`.
  1056. position (`int`):
  1057. Position of the item in the collection.
  1058. note (`str`, *optional*):
  1059. Note associated with the item, as plain text.
  1060. """
  1061. item_object_id: str # id in database
  1062. item_id: str # repo_id or paper id
  1063. item_type: str
  1064. position: int
  1065. note: Optional[str] = None
  1066. def __init__(
  1067. self,
  1068. _id: str,
  1069. id: str,
  1070. type: CollectionItemType_T,
  1071. position: int,
  1072. note: Optional[dict] = None,
  1073. **kwargs,
  1074. ) -> None:
  1075. self.item_object_id: str = _id # id in database
  1076. self.item_id: str = id # repo_id or paper id
  1077. # if the item is a collection, override item_id with the slug
  1078. slug = kwargs.get("slug")
  1079. if slug is not None:
  1080. self.item_id = slug # collection slug
  1081. self.item_type: CollectionItemType_T = type
  1082. self.position: int = position
  1083. self.note: str = note["text"] if note is not None else None
  1084. @dataclass
  1085. class Collection:
  1086. """
  1087. Contains information about a Collection on the Hub.
  1088. Attributes:
  1089. slug (`str`):
  1090. Slug of the collection. E.g. `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  1091. title (`str`):
  1092. Title of the collection. E.g. `"Recent models"`.
  1093. owner (`str`):
  1094. Owner of the collection. E.g. `"TheBloke"`.
  1095. items (`list[CollectionItem]`):
  1096. List of items in the collection.
  1097. last_updated (`datetime`):
  1098. Date of the last update of the collection.
  1099. position (`int`):
  1100. Position of the collection in the list of collections of the owner.
  1101. private (`bool`):
  1102. Whether the collection is private or not.
  1103. theme (`str`):
  1104. Theme of the collection. E.g. `"green"`.
  1105. upvotes (`int`):
  1106. Number of upvotes of the collection.
  1107. description (`str`, *optional*):
  1108. Description of the collection, as plain text.
  1109. url (`str`):
  1110. (property) URL of the collection on the Hub.
  1111. """
  1112. slug: str
  1113. title: str
  1114. owner: str
  1115. items: list[CollectionItem]
  1116. last_updated: datetime
  1117. position: int
  1118. private: bool
  1119. theme: str
  1120. upvotes: int
  1121. description: Optional[str] = None
  1122. def __init__(self, **kwargs) -> None:
  1123. self.slug = kwargs.pop("slug")
  1124. self.title = kwargs.pop("title")
  1125. self.owner = kwargs.pop("owner")
  1126. self.items = [CollectionItem(**item) for item in kwargs.pop("items")]
  1127. self.last_updated = parse_datetime(kwargs.pop("lastUpdated"))
  1128. self.position = kwargs.pop("position")
  1129. self.private = kwargs.pop("private")
  1130. self.theme = kwargs.pop("theme")
  1131. self.upvotes = kwargs.pop("upvotes")
  1132. self.description = kwargs.pop("description", None)
  1133. endpoint = kwargs.pop("endpoint", None)
  1134. if endpoint is None:
  1135. endpoint = constants.ENDPOINT
  1136. self._url = f"{endpoint}/collections/{self.slug}"
  1137. @property
  1138. def url(self) -> str:
  1139. """Returns the URL of the collection on the Hub."""
  1140. return self._url
  1141. @dataclass
  1142. class GitRefInfo:
  1143. """
  1144. Contains information about a git reference for a repo on the Hub.
  1145. Attributes:
  1146. name (`str`):
  1147. Name of the reference (e.g. tag name or branch name).
  1148. ref (`str`):
  1149. Full git ref on the Hub (e.g. `"refs/heads/main"` or `"refs/tags/v1.0"`).
  1150. target_commit (`str`):
  1151. OID of the target commit for the ref (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`)
  1152. """
  1153. name: str
  1154. ref: str
  1155. target_commit: str
  1156. @dataclass
  1157. class GitRefs:
  1158. """
  1159. Contains information about all git references for a repo on the Hub.
  1160. Object is returned by [`list_repo_refs`].
  1161. Attributes:
  1162. branches (`list[GitRefInfo]`):
  1163. A list of [`GitRefInfo`] containing information about branches on the repo.
  1164. converts (`list[GitRefInfo]`):
  1165. A list of [`GitRefInfo`] containing information about "convert" refs on the repo.
  1166. Converts are refs used (internally) to push preprocessed data in Dataset repos.
  1167. tags (`list[GitRefInfo]`):
  1168. A list of [`GitRefInfo`] containing information about tags on the repo.
  1169. pull_requests (`list[GitRefInfo]`, *optional*):
  1170. A list of [`GitRefInfo`] containing information about pull requests on the repo.
  1171. Only returned if `include_prs=True` is set.
  1172. """
  1173. branches: list[GitRefInfo]
  1174. converts: list[GitRefInfo]
  1175. tags: list[GitRefInfo]
  1176. pull_requests: Optional[list[GitRefInfo]] = None
  1177. @dataclass
  1178. class GitCommitInfo:
  1179. """
  1180. Contains information about a git commit for a repo on the Hub. Check out [`list_repo_commits`] for more details.
  1181. Attributes:
  1182. commit_id (`str`):
  1183. OID of the commit (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`)
  1184. authors (`list[str]`):
  1185. List of authors of the commit.
  1186. created_at (`datetime`):
  1187. Datetime when the commit was created.
  1188. title (`str`):
  1189. Title of the commit. This is a free-text value entered by the authors.
  1190. message (`str`):
  1191. Description of the commit. This is a free-text value entered by the authors.
  1192. formatted_title (`str`):
  1193. Title of the commit formatted as HTML. Only returned if `formatted=True` is set.
  1194. formatted_message (`str`):
  1195. Description of the commit formatted as HTML. Only returned if `formatted=True` is set.
  1196. """
  1197. commit_id: str
  1198. authors: list[str]
  1199. created_at: datetime
  1200. title: str
  1201. message: str
  1202. formatted_title: Optional[str]
  1203. formatted_message: Optional[str]
  1204. @dataclass
  1205. class UserLikes:
  1206. """
  1207. Contains information about a user likes on the Hub.
  1208. Attributes:
  1209. user (`str`):
  1210. Name of the user for which we fetched the likes.
  1211. total (`int`):
  1212. Total number of likes.
  1213. datasets (`list[str]`):
  1214. List of datasets liked by the user (as repo_ids).
  1215. models (`list[str]`):
  1216. List of models liked by the user (as repo_ids).
  1217. spaces (`list[str]`):
  1218. List of spaces liked by the user (as repo_ids).
  1219. """
  1220. # Metadata
  1221. user: str
  1222. total: int
  1223. # User likes
  1224. datasets: list[str]
  1225. models: list[str]
  1226. spaces: list[str]
  1227. @dataclass
  1228. class Organization:
  1229. """
  1230. Contains information about an organization on the Hub.
  1231. Attributes:
  1232. avatar_url (`str`):
  1233. URL of the organization's avatar.
  1234. name (`str`):
  1235. Name of the organization on the Hub (unique).
  1236. fullname (`str`):
  1237. Organization's full name.
  1238. details (`str`, *optional*):
  1239. Organization's description.
  1240. is_verified (`bool`, *optional*):
  1241. Whether the organization is verified.
  1242. is_following (`bool`, *optional*):
  1243. Whether the authenticated user follows this organization.
  1244. num_users (`int`, *optional*):
  1245. Number of members in the organization.
  1246. num_models (`int`, *optional*):
  1247. Number of models owned by the organization.
  1248. num_spaces (`int`, *optional*):
  1249. Number of Spaces owned by the organization.
  1250. num_datasets (`int`, *optional*):
  1251. Number of datasets owned by the organization.
  1252. num_followers (`int`, *optional*):
  1253. Number of followers of the organization.
  1254. num_papers (`int`, *optional*):
  1255. Number of papers authored by the organization.
  1256. """
  1257. avatar_url: str
  1258. name: str
  1259. fullname: str
  1260. details: Optional[str] = None
  1261. is_verified: Optional[bool] = None
  1262. is_following: Optional[bool] = None
  1263. num_users: Optional[int] = None
  1264. num_models: Optional[int] = None
  1265. num_spaces: Optional[int] = None
  1266. num_datasets: Optional[int] = None
  1267. num_followers: Optional[int] = None
  1268. num_papers: Optional[int] = None
  1269. def __init__(self, **kwargs) -> None:
  1270. self.avatar_url = kwargs.pop("avatarUrl", "")
  1271. self.name = kwargs.pop("name", "")
  1272. self.fullname = kwargs.pop("fullname", "")
  1273. self.details = kwargs.pop("details", None)
  1274. self.is_verified = kwargs.pop("isVerified", None)
  1275. self.is_following = kwargs.pop("isFollowing", None)
  1276. self.num_users = kwargs.pop("numUsers", None)
  1277. self.num_models = kwargs.pop("numModels", None)
  1278. self.num_spaces = kwargs.pop("numSpaces", None)
  1279. self.num_datasets = kwargs.pop("numDatasets", None)
  1280. self.num_followers = kwargs.pop("numFollowers", None)
  1281. self.num_papers = kwargs.pop("numPapers", None)
  1282. # forward compatibility
  1283. self.__dict__.update(**kwargs)
  1284. @dataclass
  1285. class User:
  1286. """
  1287. Contains information about a user on the Hub.
  1288. Attributes:
  1289. username (`str`):
  1290. Name of the user on the Hub (unique).
  1291. fullname (`str`):
  1292. User's full name.
  1293. avatar_url (`str`):
  1294. URL of the user's avatar.
  1295. details (`str`, *optional*):
  1296. User's details.
  1297. is_following (`bool`, *optional*):
  1298. Whether the authenticated user is following this user.
  1299. is_pro (`bool`, *optional*):
  1300. Whether the user is a pro user.
  1301. num_models (`int`, *optional*):
  1302. Number of models created by the user.
  1303. num_datasets (`int`, *optional*):
  1304. Number of datasets created by the user.
  1305. num_spaces (`int`, *optional*):
  1306. Number of spaces created by the user.
  1307. num_discussions (`int`, *optional*):
  1308. Number of discussions initiated by the user.
  1309. num_papers (`int`, *optional*):
  1310. Number of papers authored by the user.
  1311. num_upvotes (`int`, *optional*):
  1312. Number of upvotes received by the user.
  1313. num_likes (`int`, *optional*):
  1314. Number of likes given by the user.
  1315. num_following (`int`, *optional*):
  1316. Number of users this user is following.
  1317. num_followers (`int`, *optional*):
  1318. Number of users following this user.
  1319. orgs (list of [`Organization`]):
  1320. List of organizations the user is part of.
  1321. """
  1322. # Metadata
  1323. username: str
  1324. fullname: str
  1325. avatar_url: str
  1326. details: Optional[str] = None
  1327. is_following: Optional[bool] = None
  1328. is_pro: Optional[bool] = None
  1329. num_models: Optional[int] = None
  1330. num_datasets: Optional[int] = None
  1331. num_spaces: Optional[int] = None
  1332. num_discussions: Optional[int] = None
  1333. num_papers: Optional[int] = None
  1334. num_upvotes: Optional[int] = None
  1335. num_likes: Optional[int] = None
  1336. num_following: Optional[int] = None
  1337. num_followers: Optional[int] = None
  1338. orgs: list[Organization] = field(default_factory=list)
  1339. def __init__(self, **kwargs) -> None:
  1340. self.username = kwargs.pop("user", "")
  1341. self.fullname = kwargs.pop("fullname", "")
  1342. self.avatar_url = kwargs.pop("avatarUrl", "")
  1343. self.is_following = kwargs.pop("isFollowing", None)
  1344. self.is_pro = kwargs.pop("isPro", None)
  1345. self.details = kwargs.pop("details", None)
  1346. self.num_models = kwargs.pop("numModels", None)
  1347. self.num_datasets = kwargs.pop("numDatasets", None)
  1348. self.num_spaces = kwargs.pop("numSpaces", None)
  1349. self.num_discussions = kwargs.pop("numDiscussions", None)
  1350. self.num_papers = kwargs.pop("numPapers", None)
  1351. self.num_upvotes = kwargs.pop("numUpvotes", None)
  1352. self.num_likes = kwargs.pop("numLikes", None)
  1353. self.num_following = kwargs.pop("numFollowing", None)
  1354. self.num_followers = kwargs.pop("numFollowers", None)
  1355. self.user_type = kwargs.pop("type", None)
  1356. self.orgs = [Organization(**org) for org in kwargs.pop("orgs", [])]
  1357. # forward compatibility
  1358. self.__dict__.update(**kwargs)
  1359. @dataclass
  1360. class PaperAuthor:
  1361. """
  1362. Contains information about a paper author on the Hub.
  1363. Attributes:
  1364. name (`str`):
  1365. Name of the author.
  1366. user (`User`, *optional*):
  1367. Information about the author as a [`User`] object.
  1368. status (`str`, *optional*):
  1369. Status of the author on the Hub.
  1370. status_last_changed_at (`datetime`, *optional*):
  1371. Date when the status of the author changed.
  1372. hidden (`bool`, *optional*):
  1373. Whether the author is hidden on the Hub.
  1374. """
  1375. name: str
  1376. user: Optional[User]
  1377. status: Optional[str]
  1378. status_last_changed_at: Optional[datetime]
  1379. hidden: Optional[bool]
  1380. def __init__(self, **kwargs) -> None:
  1381. self.name = kwargs.pop("name", "")
  1382. user = kwargs.pop("user", None)
  1383. self.user = User(**user) if user else None
  1384. self.status = kwargs.pop("status", None)
  1385. status_last_changed_at = kwargs.pop("statusLastChangedAt", None)
  1386. self.status_last_changed_at = parse_datetime(status_last_changed_at) if status_last_changed_at else None
  1387. self.hidden = kwargs.pop("hidden", None)
  1388. self.__dict__.update(**kwargs)
  1389. @dataclass
  1390. class PaperInfo:
  1391. """
  1392. Contains information about a paper on the Hub.
  1393. Attributes:
  1394. id (`str`):
  1395. arXiv paper ID.
  1396. authors (`list[PaperAuthor]`, *optional*):
  1397. Authors of the paper.
  1398. published_at (`datetime`, *optional*):
  1399. Date paper published.
  1400. title (`str`, *optional*):
  1401. Title of the paper.
  1402. summary (`str`, *optional*):
  1403. Summary of the paper.
  1404. upvotes (`int`, *optional*):
  1405. Number of upvotes for the paper on the Hub.
  1406. discussion_id (`str`, *optional*):
  1407. Discussion ID for the paper on the Hub.
  1408. source (`str`, *optional*):
  1409. Source of the paper.
  1410. comments (`int`, *optional*):
  1411. Number of comments for the paper on the Hub.
  1412. submitted_at (`datetime`, *optional*):
  1413. Date paper appeared in daily papers on the Hub.
  1414. submitted_by (`User`, *optional*):
  1415. Information about who submitted the daily paper.
  1416. ai_summary (`str`, *optional*):
  1417. AI summary of the paper.
  1418. ai_keywords (`list[str]`, *optional*):
  1419. AI keywords of the paper.
  1420. organization (`Organization`, *optional*):
  1421. Information about the organization associated with the paper.
  1422. project_page (`str`, *optional*):
  1423. URL of the project page for the paper.
  1424. github_repo (`str`, *optional*):
  1425. URL of the GitHub repository for the paper.
  1426. github_stars (`int`, *optional*):
  1427. Number of stars of the GitHub repository for the paper.
  1428. """
  1429. id: str
  1430. authors: Optional[list[PaperAuthor]]
  1431. published_at: Optional[datetime]
  1432. title: Optional[str]
  1433. summary: Optional[str]
  1434. upvotes: Optional[int]
  1435. discussion_id: Optional[str]
  1436. source: Optional[str]
  1437. comments: Optional[int]
  1438. submitted_at: Optional[datetime]
  1439. submitted_by: Optional[User]
  1440. ai_summary: Optional[str]
  1441. ai_keywords: Optional[list[str]]
  1442. organization: Optional[Organization]
  1443. project_page: Optional[str]
  1444. github_repo: Optional[str]
  1445. github_stars: Optional[int]
  1446. def __init__(self, **kwargs) -> None:
  1447. paper = kwargs.pop("paper", {})
  1448. self.id = kwargs.pop("id", None) or paper.pop("id", None)
  1449. authors = paper.pop("authors", None) or kwargs.pop("authors", None)
  1450. self.authors = [PaperAuthor(**author) for author in authors] if authors else None
  1451. published_at = paper.pop("publishedAt", None) or kwargs.pop("publishedAt", None)
  1452. self.published_at = parse_datetime(published_at) if published_at else None
  1453. self.title = kwargs.pop("title", None)
  1454. self.source = kwargs.pop("source", None)
  1455. self.summary = paper.pop("summary", None) or kwargs.pop("summary", None)
  1456. self.upvotes = paper.pop("upvotes", None) or kwargs.pop("upvotes", None)
  1457. self.discussion_id = paper.pop("discussionId", None) or kwargs.pop("discussionId", None)
  1458. self.comments = kwargs.pop("numComments", 0)
  1459. submitted_at = kwargs.pop("publishedAt", None) or kwargs.pop("submittedOnDailyAt", None)
  1460. self.submitted_at = parse_datetime(submitted_at) if submitted_at else None
  1461. submitted_by = kwargs.pop("submittedBy", None) or kwargs.pop("submittedOnDailyBy", None)
  1462. self.submitted_by = User(**submitted_by) if submitted_by else None
  1463. self.ai_summary = kwargs.pop("ai_summary", None)
  1464. self.ai_keywords = kwargs.pop("ai_keywords", None)
  1465. organization = kwargs.pop("organization", None)
  1466. self.organization = Organization(**organization) if organization else None
  1467. self.project_page = kwargs.pop("projectPage", None)
  1468. self.github_repo = kwargs.pop("githubRepo", None)
  1469. self.github_stars = kwargs.pop("githubStars", None)
  1470. # forward compatibility
  1471. self.__dict__.update(**kwargs)
  1472. @dataclass
  1473. class LFSFileInfo:
  1474. """
  1475. Contains information about a file stored as LFS on a repo on the Hub.
  1476. Used in the context of listing and permanently deleting LFS files from a repo to free-up space.
  1477. See [`list_lfs_files`] and [`permanently_delete_lfs_files`] for more details.
  1478. Git LFS files are tracked using SHA-256 object IDs, rather than file paths, to optimize performance
  1479. This approach is necessary because a single object can be referenced by multiple paths across different commits,
  1480. making it impractical to search and resolve these connections. Check out [our documentation](https://huggingface.co/docs/hub/storage-limits#advanced-track-lfs-file-references)
  1481. to learn how to know which filename(s) is(are) associated with each SHA.
  1482. Attributes:
  1483. file_oid (`str`):
  1484. SHA-256 object ID of the file. This is the identifier to pass when permanently deleting the file.
  1485. filename (`str`):
  1486. Possible filename for the LFS object. See the note above for more information.
  1487. oid (`str`):
  1488. OID of the LFS object.
  1489. pushed_at (`datetime`):
  1490. Date the LFS object was pushed to the repo.
  1491. ref (`str`, *optional*):
  1492. Ref where the LFS object has been pushed (if any).
  1493. size (`int`):
  1494. Size of the LFS object.
  1495. Example:
  1496. ```py
  1497. >>> from huggingface_hub import HfApi
  1498. >>> api = HfApi()
  1499. >>> lfs_files = api.list_lfs_files("username/my-cool-repo")
  1500. # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
  1501. # e.g. select only LFS files in the "checkpoints" folder
  1502. >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
  1503. # Permanently delete LFS files
  1504. >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
  1505. ```
  1506. """
  1507. file_oid: str
  1508. filename: str
  1509. oid: str
  1510. pushed_at: datetime
  1511. ref: Optional[str]
  1512. size: int
  1513. def __init__(self, **kwargs) -> None:
  1514. self.file_oid = kwargs.pop("fileOid")
  1515. self.filename = kwargs.pop("filename")
  1516. self.oid = kwargs.pop("oid")
  1517. self.pushed_at = parse_datetime(kwargs.pop("pushedAt"))
  1518. self.ref = kwargs.pop("ref", None)
  1519. self.size = kwargs.pop("size")
  1520. # forward compatibility
  1521. self.__dict__.update(**kwargs)
  1522. def future_compatible(fn: CallableT) -> CallableT:
  1523. """Wrap a method of `HfApi` to handle `run_as_future=True`.
  1524. A method flagged as "future_compatible" will be called in a thread if `run_as_future=True` and return a
  1525. `concurrent.futures.Future` instance. Otherwise, it will be called normally and return the result.
  1526. """
  1527. sig = inspect.signature(fn)
  1528. args_params = list(sig.parameters)[1:] # remove "self" from list
  1529. @wraps(fn)
  1530. def _inner(self, *args, **kwargs):
  1531. # Get `run_as_future` value if provided (default to False)
  1532. if "run_as_future" in kwargs:
  1533. run_as_future = kwargs["run_as_future"]
  1534. kwargs["run_as_future"] = False # avoid recursion error
  1535. else:
  1536. run_as_future = False
  1537. for param, value in zip(args_params, args):
  1538. if param == "run_as_future":
  1539. run_as_future = value
  1540. break
  1541. # Call the function in a thread if `run_as_future=True`
  1542. if run_as_future:
  1543. return self.run_as_future(fn, self, *args, **kwargs)
  1544. # Otherwise, call the function normally
  1545. return fn(self, *args, **kwargs)
  1546. _inner.is_future_compatible = True # type: ignore
  1547. return _inner # type: ignore
  1548. def _get_safetensors_metadata_size(size_bytes: bytes, filename: str, context_msg: str) -> int:
  1549. """
  1550. Parse and validate safetensors metadata size from the first 8 bytes.
  1551. This is a shared helper function used by both remote and local safetensors parsing.
  1552. Args:
  1553. size_bytes: First 8 bytes of the safetensors file.
  1554. filename: Filename for error messages.
  1555. context_msg: Additional context for error messages.
  1556. Returns:
  1557. The metadata size as an integer.
  1558. Raises:
  1559. SafetensorsParsingError: If size_bytes is too short or metadata size exceeds limit.
  1560. """
  1561. if len(size_bytes) < 8:
  1562. raise SafetensorsParsingError(
  1563. f"Failed to parse safetensors header for '{filename}' ({context_msg}): file is too small to be a valid "
  1564. "safetensors file."
  1565. )
  1566. metadata_size = struct.unpack("<Q", size_bytes[:8])[0]
  1567. if metadata_size > constants.SAFETENSORS_MAX_HEADER_LENGTH:
  1568. raise SafetensorsParsingError(
  1569. f"Failed to parse safetensors header for '{filename}' ({context_msg}): safetensors header is too big. "
  1570. f"Maximum supported size is {constants.SAFETENSORS_MAX_HEADER_LENGTH} bytes (got {metadata_size})."
  1571. )
  1572. return metadata_size
  1573. def _parse_safetensors_header(metadata_as_bytes: bytes, filename: str, context_msg: str) -> SafetensorsFileMetadata:
  1574. """
  1575. Parse safetensors metadata from raw header bytes.
  1576. This is a shared helper function used by both remote and local safetensors parsing.
  1577. Args:
  1578. metadata_as_bytes: Raw bytes of the JSON metadata header (without the 8-byte size prefix).
  1579. filename: Filename for error messages.
  1580. context_msg: Additional context for error messages (e.g., repo info or local path).
  1581. Returns:
  1582. SafetensorsFileMetadata object.
  1583. Raises:
  1584. SafetensorsParsingError: If the header cannot be parsed.
  1585. """
  1586. # Parse json header
  1587. try:
  1588. metadata_as_dict = json.loads(metadata_as_bytes.decode(errors="ignore"))
  1589. except json.JSONDecodeError as e:
  1590. raise SafetensorsParsingError(
  1591. f"Failed to parse safetensors header for '{filename}' ({context_msg}): header is not json-encoded string. "
  1592. "Please make sure this is a correctly formatted safetensors file."
  1593. ) from e
  1594. try:
  1595. return SafetensorsFileMetadata(
  1596. metadata=metadata_as_dict.get("__metadata__", {}),
  1597. tensors={
  1598. key: TensorInfo(
  1599. dtype=tensor["dtype"],
  1600. shape=tensor["shape"],
  1601. data_offsets=tuple(tensor["data_offsets"]), # type: ignore
  1602. )
  1603. for key, tensor in metadata_as_dict.items()
  1604. if key != "__metadata__"
  1605. },
  1606. )
  1607. except (KeyError, IndexError) as e:
  1608. raise SafetensorsParsingError(
  1609. f"Failed to parse safetensors header for '{filename}' ({context_msg}): header format not recognized. "
  1610. "Please make sure this is a correctly formatted safetensors file."
  1611. ) from e
  1612. class HfApi:
  1613. """
  1614. Client to interact with the Hugging Face Hub via HTTP.
  1615. The client is initialized with some high-level settings used in all requests
  1616. made to the Hub (HF endpoint, authentication, user agents...). Using the `HfApi`
  1617. client is preferred but not mandatory as all of its public methods are exposed
  1618. directly at the root of `huggingface_hub`.
  1619. Args:
  1620. endpoint (`str`, *optional*):
  1621. Endpoint of the Hub. Defaults to <https://huggingface.co>.
  1622. token (`bool` or `str`, *optional*):
  1623. A valid user access token (string). Defaults to the locally saved
  1624. token, which is the recommended method for authentication (see
  1625. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  1626. To disable authentication, pass `False`.
  1627. library_name (`str`, *optional*):
  1628. The name of the library that is making the HTTP request. Will be added to
  1629. the user-agent header. Example: `"transformers"`.
  1630. library_version (`str`, *optional*):
  1631. The version of the library that is making the HTTP request. Will be added
  1632. to the user-agent header. Example: `"4.24.0"`.
  1633. user_agent (`str`, `dict`, *optional*):
  1634. The user agent info in the form of a dictionary or a single string. It will
  1635. be completed with information about the installed packages.
  1636. headers (`dict`, *optional*):
  1637. Additional headers to be sent with each request. Example: `{"X-My-Header": "value"}`.
  1638. Headers passed here are taking precedence over the default headers.
  1639. """
  1640. def __init__(
  1641. self,
  1642. endpoint: Optional[str] = None,
  1643. token: Union[str, bool, None] = None,
  1644. library_name: Optional[str] = None,
  1645. library_version: Optional[str] = None,
  1646. user_agent: Union[dict, str, None] = None,
  1647. headers: Optional[dict[str, str]] = None,
  1648. ) -> None:
  1649. self.endpoint = endpoint if endpoint is not None else constants.ENDPOINT
  1650. self.token = token
  1651. self.library_name = library_name
  1652. self.library_version = library_version
  1653. self.user_agent = user_agent
  1654. self.headers = headers
  1655. self._thread_pool: Optional[ThreadPoolExecutor] = None
  1656. # /whoami-v2 is the only endpoint for which we may want to cache results
  1657. self._whoami_cache: dict[str, dict] = {}
  1658. def run_as_future(self, fn: Callable[..., R], *args, **kwargs) -> Future[R]:
  1659. """
  1660. Run a method in the background and return a Future instance.
  1661. The main goal is to run methods without blocking the main thread (e.g. to push data during a training).
  1662. Background jobs are queued to preserve order but are not ran in parallel. If you need to speed-up your scripts
  1663. by parallelizing lots of call to the API, you must setup and use your own [ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor).
  1664. Note: Most-used methods like [`upload_file`], [`upload_folder`] and [`create_commit`] have a `run_as_future: bool`
  1665. argument to directly call them in the background. This is equivalent to calling `api.run_as_future(...)` on them
  1666. but less verbose.
  1667. Args:
  1668. fn (`Callable`):
  1669. The method to run in the background.
  1670. *args, **kwargs:
  1671. Arguments with which the method will be called.
  1672. Return:
  1673. `Future`: a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) instance to
  1674. get the result of the task.
  1675. Example:
  1676. ```py
  1677. >>> from huggingface_hub import HfApi
  1678. >>> api = HfApi()
  1679. >>> future = api.run_as_future(api.whoami) # instant
  1680. >>> future.done()
  1681. False
  1682. >>> future.result() # wait until complete and return result
  1683. (...)
  1684. >>> future.done()
  1685. True
  1686. ```
  1687. """
  1688. if self._thread_pool is None:
  1689. self._thread_pool = ThreadPoolExecutor(max_workers=1)
  1690. self._thread_pool
  1691. return self._thread_pool.submit(fn, *args, **kwargs)
  1692. @validate_hf_hub_args
  1693. def whoami(self, token: Union[bool, str, None] = None, *, cache: bool = False) -> dict:
  1694. """
  1695. Call HF API to know "whoami".
  1696. If passing `cache=True`, the result will be cached for subsequent calls for the duration of the Python process. This is useful if you plan to call
  1697. `whoami` multiple times as this endpoint is heavily rate-limited for security reasons.
  1698. Args:
  1699. token (`bool` or `str`, *optional*):
  1700. A valid user access token (string). Defaults to the locally saved
  1701. token, which is the recommended method for authentication (see
  1702. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  1703. To disable authentication, pass `False`.
  1704. cache (`bool`, *optional*):
  1705. Whether to cache the result of the `whoami` call for subsequent calls.
  1706. If an error occurs during the first call, it won't be cached.
  1707. Defaults to `False`.
  1708. """
  1709. # Get the effective token using the helper function get_token
  1710. token = self.token if token is None else token
  1711. if token is False:
  1712. raise ValueError("Cannot use `token=False` with `whoami` method as it requires authentication.")
  1713. if token is True or token is None:
  1714. token = get_token()
  1715. if token is None:
  1716. raise LocalTokenNotFoundError(
  1717. "Token is required to call the /whoami-v2 endpoint, but no token found. You must provide a token or be logged in to "
  1718. "Hugging Face with `hf auth login` or `huggingface_hub.login`. See https://huggingface.co/settings/tokens."
  1719. )
  1720. if cache and (cached_token := self._whoami_cache.get(token)):
  1721. return cached_token
  1722. # Call Hub
  1723. output = self._inner_whoami(token=token)
  1724. # Cache result and return
  1725. if cache:
  1726. self._whoami_cache[token] = output
  1727. return output
  1728. def _inner_whoami(self, token: str) -> dict:
  1729. r = get_session().get(
  1730. f"{self.endpoint}/api/whoami-v2",
  1731. headers=self._build_hf_headers(token=token),
  1732. )
  1733. try:
  1734. hf_raise_for_status(r)
  1735. except HfHubHTTPError as e:
  1736. if e.response.status_code == 401:
  1737. error_message = "Invalid user token."
  1738. # Check which token is the effective one and generate the error message accordingly
  1739. if token == _get_token_from_google_colab():
  1740. error_message += " The token from Google Colab vault is invalid. Please update it from the UI."
  1741. elif token == _get_token_from_environment():
  1742. error_message += (
  1743. " The token from HF_TOKEN environment variable is invalid. "
  1744. "Note that HF_TOKEN takes precedence over `hf auth login`."
  1745. )
  1746. elif token == _get_token_from_file():
  1747. error_message += " The token stored is invalid. Please run `hf auth login` to update it."
  1748. raise HfHubHTTPError(error_message, response=e.response) from e
  1749. if e.response.status_code == 429:
  1750. error_message = (
  1751. "You've hit the rate limit for the /whoami-v2 endpoint, which is intentionally strict for security reasons."
  1752. " If you're calling it often, consider caching the response with `whoami(..., cache=True)`."
  1753. )
  1754. raise HfHubHTTPError(error_message, response=e.response) from e
  1755. raise
  1756. return r.json()
  1757. def get_model_tags(self) -> dict:
  1758. """
  1759. List all valid model tags as a nested namespace object
  1760. """
  1761. path = f"{self.endpoint}/api/models-tags-by-type"
  1762. r = get_session().get(path)
  1763. hf_raise_for_status(r)
  1764. return r.json()
  1765. def get_dataset_tags(self) -> dict:
  1766. """
  1767. List all valid dataset tags as a nested namespace object.
  1768. """
  1769. path = f"{self.endpoint}/api/datasets-tags-by-type"
  1770. r = get_session().get(path)
  1771. hf_raise_for_status(r)
  1772. return r.json()
  1773. @_deprecate_arguments(version="1.5", deprecated_args=["direction"], custom_message="Sorting is always descending.")
  1774. @validate_hf_hub_args
  1775. def list_models(
  1776. self,
  1777. *,
  1778. # Search-query parameter
  1779. filter: Union[str, Iterable[str], None] = None,
  1780. author: Optional[str] = None,
  1781. apps: Optional[Union[str, list[str]]] = None,
  1782. gated: Optional[bool] = None,
  1783. inference: Optional[Literal["warm"]] = None,
  1784. inference_provider: Optional[Union[Literal["all"], "PROVIDER_T", list["PROVIDER_T"]]] = None,
  1785. model_name: Optional[str] = None,
  1786. trained_dataset: Optional[Union[str, list[str]]] = None,
  1787. search: Optional[str] = None,
  1788. pipeline_tag: Optional[str] = None,
  1789. emissions_thresholds: Optional[tuple[float, float]] = None,
  1790. # Sorting and pagination parameters
  1791. sort: Optional[ModelSort_T] = None,
  1792. direction: Optional[Literal[-1]] = None,
  1793. limit: Optional[int] = None,
  1794. # Additional data to fetch
  1795. expand: Optional[list[ExpandModelProperty_T]] = None,
  1796. full: Optional[bool] = None,
  1797. cardData: bool = False,
  1798. fetch_config: bool = False,
  1799. token: Union[bool, str, None] = None,
  1800. ) -> Iterable[ModelInfo]:
  1801. """
  1802. List models hosted on the Huggingface Hub, given some filters.
  1803. Args:
  1804. filter (`str` or `Iterable[str]`, *optional*):
  1805. A string or list of string to filter models on the Hub.
  1806. Models can be filtered by library, language, task, tags, and more.
  1807. author (`str`, *optional*):
  1808. A string which identify the author (user or organization) of the
  1809. returned models.
  1810. apps (`str` or `List`, *optional*):
  1811. A string or list of strings to filter models on the Hub that
  1812. support the specified apps. Example values include `"ollama"` or `["ollama", "vllm"]`.
  1813. gated (`bool`, *optional*):
  1814. A boolean to filter models on the Hub that are gated or not. By default, all models are returned.
  1815. If `gated=True` is passed, only gated models are returned.
  1816. If `gated=False` is passed, only non-gated models are returned.
  1817. inference (`Literal["warm"]`, *optional*):
  1818. If "warm", filter models on the Hub currently served by at least one provider.
  1819. inference_provider (`Literal["all"]` or `str`, *optional*):
  1820. A string to filter models on the Hub that are served by a specific provider.
  1821. Pass `"all"` to get all models served by at least one provider.
  1822. model_name (`str`, *optional*):
  1823. A string that contain complete or partial names for models on the
  1824. Hub, such as "bert" or "bert-base-cased"
  1825. trained_dataset (`str` or `List`, *optional*):
  1826. A string tag or a list of string tags of the trained dataset for a
  1827. model on the Hub.
  1828. search (`str`, *optional*):
  1829. A string that will be contained in the returned model ids.
  1830. pipeline_tag (`str`, *optional*):
  1831. A string pipeline tag to filter models on the Hub by, such as `summarization`.
  1832. emissions_thresholds (`Tuple`, *optional*):
  1833. A tuple of two ints or floats representing a minimum and maximum
  1834. carbon footprint to filter the resulting models with in grams.
  1835. sort (`ModelSort_T`, *optional*):
  1836. The key with which to sort the resulting models. Possible values are "created_at", "downloads",
  1837. "last_modified", "likes" and "trending_score".
  1838. direction (`Literal[-1]` or `int`, *optional*):
  1839. Deprecated. This parameter is not used and will be removed in version 1.5.
  1840. limit (`int`, *optional*):
  1841. The limit on the number of models fetched. Leaving this option
  1842. to `None` fetches all models.
  1843. expand (`list[ExpandModelProperty_T]`, *optional*):
  1844. List properties to return in the response. When used, only the properties in the list will be returned.
  1845. This parameter cannot be used if `full`, `cardData` or `fetch_config` are passed.
  1846. Possible values are `"author"`, `"cardData"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"gguf"`, `"inference"`, `"inferenceProviderMapping"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, and `"resourceGroup"`.
  1847. full (`bool`, *optional*):
  1848. Whether to fetch all model data, including the `last_modified`,
  1849. the `sha`, the files and the `tags`. This is set to `True` by
  1850. default when using a filter.
  1851. cardData (`bool`, *optional*):
  1852. Whether to grab the metadata for the model as well. Can contain
  1853. useful information such as carbon emissions, metrics, and
  1854. datasets trained on.
  1855. fetch_config (`bool`, *optional*):
  1856. Whether to fetch the model configs as well. This is not included
  1857. in `full` due to its size.
  1858. token (`bool` or `str`, *optional*):
  1859. A valid user access token (string). Defaults to the locally saved
  1860. token, which is the recommended method for authentication (see
  1861. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  1862. To disable authentication, pass `False`.
  1863. Returns:
  1864. `Iterable[ModelInfo]`: an iterable of [`huggingface_hub.hf_api.ModelInfo`] objects.
  1865. Example:
  1866. ```python
  1867. >>> from huggingface_hub import HfApi
  1868. >>> api = HfApi()
  1869. # List all models
  1870. >>> api.list_models()
  1871. # List text classification models
  1872. >>> api.list_models(filter="text-classification")
  1873. # List models from the KerasHub library
  1874. >>> api.list_models(filter="keras-hub")
  1875. # List models served by Cohere
  1876. >>> api.list_models(inference_provider="cohere")
  1877. # List models with "bert" in their name
  1878. >>> api.list_models(search="bert")
  1879. # List models with "bert" in their name and pushed by google
  1880. >>> api.list_models(search="bert", author="google")
  1881. ```
  1882. """
  1883. if expand and (full or cardData or fetch_config):
  1884. raise ValueError("`expand` cannot be used if `full`, `cardData` or `fetch_config` are passed.")
  1885. if emissions_thresholds is not None and not cardData:
  1886. raise ValueError("`emissions_thresholds` were passed without setting `cardData=True`.")
  1887. path = f"{self.endpoint}/api/models"
  1888. headers = self._build_hf_headers(token=token)
  1889. params: dict[str, Any] = {}
  1890. # Build the filter list
  1891. filter_list: list[str] = []
  1892. if filter:
  1893. filter_list.extend([filter] if isinstance(filter, str) else filter)
  1894. if trained_dataset:
  1895. datasets = [trained_dataset] if isinstance(trained_dataset, str) else trained_dataset
  1896. filter_list.extend(f"dataset:{d}" if not d.startswith("dataset:") else d for d in datasets)
  1897. if len(filter_list) > 0:
  1898. params["filter"] = filter_list
  1899. # Handle other query params
  1900. if author:
  1901. params["author"] = author
  1902. if apps:
  1903. if isinstance(apps, str):
  1904. apps = [apps]
  1905. params["apps"] = apps
  1906. if gated is not None:
  1907. params["gated"] = gated
  1908. if inference is not None:
  1909. params["inference"] = inference
  1910. if inference_provider is not None:
  1911. params["inference_provider"] = inference_provider
  1912. if pipeline_tag:
  1913. params["pipeline_tag"] = pipeline_tag
  1914. search_list = []
  1915. if model_name:
  1916. search_list.append(model_name)
  1917. if search:
  1918. search_list.append(search)
  1919. if len(search_list) > 0:
  1920. params["search"] = search_list
  1921. if sort is not None:
  1922. params["sort"] = (
  1923. "lastModified"
  1924. if sort == "last_modified"
  1925. else "trendingScore"
  1926. if sort == "trending_score"
  1927. else "createdAt"
  1928. if sort == "created_at"
  1929. else sort
  1930. )
  1931. if direction is not None:
  1932. params["direction"] = direction
  1933. if limit is not None:
  1934. params["limit"] = limit
  1935. # Request additional data
  1936. if full:
  1937. params["full"] = True
  1938. if fetch_config:
  1939. params["config"] = True
  1940. if cardData:
  1941. params["cardData"] = True
  1942. if expand:
  1943. params["expand"] = expand
  1944. # `items` is a generator
  1945. items = paginate(path, params=params, headers=headers)
  1946. if limit is not None:
  1947. items = islice(items, limit) # Do not iterate over all pages
  1948. for item in items:
  1949. if "siblings" not in item:
  1950. item["siblings"] = None
  1951. model_info = ModelInfo(**item)
  1952. if emissions_thresholds is None or _is_emission_within_threshold(model_info, *emissions_thresholds):
  1953. yield model_info
  1954. @_deprecate_arguments(version="1.5", deprecated_args=["direction"], custom_message="Sorting is always descending.")
  1955. @validate_hf_hub_args
  1956. def list_datasets(
  1957. self,
  1958. *,
  1959. # Search-query parameter
  1960. filter: Union[str, Iterable[str], None] = None,
  1961. author: Optional[str] = None,
  1962. benchmark: Optional[Union[str, list[str]]] = None,
  1963. dataset_name: Optional[str] = None,
  1964. gated: Optional[bool] = None,
  1965. language_creators: Optional[Union[str, list[str]]] = None,
  1966. language: Optional[Union[str, list[str]]] = None,
  1967. multilinguality: Optional[Union[str, list[str]]] = None,
  1968. size_categories: Optional[Union[str, list[str]]] = None,
  1969. task_categories: Optional[Union[str, list[str]]] = None,
  1970. task_ids: Optional[Union[str, list[str]]] = None,
  1971. search: Optional[str] = None,
  1972. # Sorting and pagination parameters
  1973. sort: Optional[DatasetSort_T] = None,
  1974. direction: Optional[Literal[-1]] = None,
  1975. limit: Optional[int] = None,
  1976. # Additional data to fetch
  1977. expand: Optional[list[ExpandDatasetProperty_T]] = None,
  1978. full: Optional[bool] = None,
  1979. token: Union[bool, str, None] = None,
  1980. ) -> Iterable[DatasetInfo]:
  1981. """
  1982. List datasets hosted on the Huggingface Hub, given some filters.
  1983. Args:
  1984. filter (`str` or `Iterable[str]`, *optional*):
  1985. A string or list of string to filter datasets on the hub.
  1986. author (`str`, *optional*):
  1987. A string which identify the author of the returned datasets.
  1988. benchmark (`str` or `List`, *optional*):
  1989. A string or list of strings that can be used to identify datasets on
  1990. the Hub by their official benchmark.
  1991. dataset_name (`str`, *optional*):
  1992. A string or list of strings that can be used to identify datasets on
  1993. the Hub by its name, such as `SQAC` or `wikineural`
  1994. gated (`bool`, *optional*):
  1995. A boolean to filter datasets on the Hub that are gated or not. By default, all datasets are returned.
  1996. If `gated=True` is passed, only gated datasets are returned.
  1997. If `gated=False` is passed, only non-gated datasets are returned.
  1998. language_creators (`str` or `List`, *optional*):
  1999. A string or list of strings that can be used to identify datasets on
  2000. the Hub with how the data was curated, such as `crowdsourced` or
  2001. `machine_generated`.
  2002. language (`str` or `List`, *optional*):
  2003. A string or list of strings representing a two-character language to
  2004. filter datasets by on the Hub.
  2005. multilinguality (`str` or `List`, *optional*):
  2006. A string or list of strings representing a filter for datasets that
  2007. contain multiple languages.
  2008. size_categories (`str` or `List`, *optional*):
  2009. A string or list of strings that can be used to identify datasets on
  2010. the Hub by the size of the dataset such as `100K<n<1M` or
  2011. `1M<n<10M`.
  2012. tags (`str` or `List`, *optional*):
  2013. Deprecated. Pass tags in `filter` to filter datasets by tags.
  2014. task_categories (`str` or `List`, *optional*):
  2015. A string or list of strings that can be used to identify datasets on
  2016. the Hub by the designed task, such as `audio_classification` or
  2017. `named_entity_recognition`.
  2018. task_ids (`str` or `List`, *optional*):
  2019. A string or list of strings that can be used to identify datasets on
  2020. the Hub by the specific task such as `speech_emotion_recognition` or
  2021. `paraphrase`.
  2022. search (`str`, *optional*):
  2023. A string that will be contained in the returned datasets.
  2024. sort (`DatasetSort_T`, *optional*):
  2025. The key with which to sort the resulting datasets. Possible values are "created_at", "downloads",
  2026. "last_modified", "likes" and "trending_score".
  2027. direction (`Literal[-1]` or `int`, *optional*):
  2028. Deprecated. This parameter is not used and will be removed in version 1.5.
  2029. limit (`int`, *optional*):
  2030. The limit on the number of datasets fetched. Leaving this option
  2031. to `None` fetches all datasets.
  2032. expand (`list[ExpandDatasetProperty_T]`, *optional*):
  2033. List properties to return in the response. When used, only the properties in the list will be returned.
  2034. This parameter cannot be used if `full` is passed.
  2035. Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
  2036. full (`bool`, *optional*):
  2037. Whether to fetch all dataset data, including the `last_modified`,
  2038. the `card_data` and the files. Can contain useful information such as the
  2039. PapersWithCode ID.
  2040. token (`bool` or `str`, *optional*):
  2041. A valid user access token (string). Defaults to the locally saved
  2042. token, which is the recommended method for authentication (see
  2043. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2044. To disable authentication, pass `False`.
  2045. Returns:
  2046. `Iterable[DatasetInfo]`: an iterable of [`huggingface_hub.hf_api.DatasetInfo`] objects.
  2047. Example usage with the `filter` argument:
  2048. ```python
  2049. >>> from huggingface_hub import HfApi
  2050. >>> api = HfApi()
  2051. # List all datasets
  2052. >>> api.list_datasets()
  2053. # List only the text classification datasets
  2054. >>> api.list_datasets(filter="task_categories:text-classification")
  2055. # List only the datasets in russian for language modeling
  2056. >>> api.list_datasets(
  2057. ... filter=("language:ru", "task_ids:language-modeling")
  2058. ... )
  2059. # List FiftyOne datasets (identified by the tag "fiftyone" in dataset card)
  2060. >>> api.list_datasets(tags="fiftyone")
  2061. ```
  2062. Example usage with the `search` argument:
  2063. ```python
  2064. >>> from huggingface_hub import HfApi
  2065. >>> api = HfApi()
  2066. # List all datasets with "text" in their name
  2067. >>> api.list_datasets(search="text")
  2068. # List all datasets with "text" in their name made by google
  2069. >>> api.list_datasets(search="text", author="google")
  2070. ```
  2071. """
  2072. if expand and full:
  2073. raise ValueError("`expand` cannot be used if `full` is passed.")
  2074. path = f"{self.endpoint}/api/datasets"
  2075. headers = self._build_hf_headers(token=token)
  2076. params: dict[str, Any] = {}
  2077. # Build `filter` list
  2078. filter_list = []
  2079. if filter is not None:
  2080. if isinstance(filter, str):
  2081. filter_list.append(filter)
  2082. else:
  2083. filter_list.extend(filter)
  2084. for key, value in (
  2085. ("benchmark", benchmark),
  2086. ("language_creators", language_creators),
  2087. ("language", language),
  2088. ("multilinguality", multilinguality),
  2089. ("size_categories", size_categories),
  2090. ("task_categories", task_categories),
  2091. ("task_ids", task_ids),
  2092. ):
  2093. if value:
  2094. if isinstance(value, str):
  2095. value = [value]
  2096. for value_item in value:
  2097. if not value_item.startswith(f"{key}:"):
  2098. data = f"{key}:{value_item}"
  2099. filter_list.append(data)
  2100. if len(filter_list) > 0:
  2101. params["filter"] = filter_list
  2102. # Handle other query params
  2103. if author:
  2104. params["author"] = author
  2105. if gated is not None:
  2106. params["gated"] = gated
  2107. search_list = []
  2108. if dataset_name:
  2109. search_list.append(dataset_name)
  2110. if search:
  2111. search_list.append(search)
  2112. if len(search_list) > 0:
  2113. params["search"] = search_list
  2114. if sort is not None:
  2115. params["sort"] = (
  2116. "lastModified"
  2117. if sort == "last_modified"
  2118. else "trendingScore"
  2119. if sort == "trending_score"
  2120. else "createdAt"
  2121. if sort == "created_at"
  2122. else sort
  2123. )
  2124. if direction is not None:
  2125. params["direction"] = direction
  2126. if limit is not None:
  2127. params["limit"] = limit
  2128. # Request additional data
  2129. if expand:
  2130. params["expand"] = expand
  2131. if full:
  2132. params["full"] = True
  2133. items = paginate(path, params=params, headers=headers)
  2134. if limit is not None:
  2135. items = islice(items, limit) # Do not iterate over all pages
  2136. for item in items:
  2137. if "siblings" not in item:
  2138. item["siblings"] = None
  2139. yield DatasetInfo(**item)
  2140. @_deprecate_arguments(version="1.5", deprecated_args=["direction"], custom_message="Sorting is always descending.")
  2141. @validate_hf_hub_args
  2142. def list_spaces(
  2143. self,
  2144. *,
  2145. # Search-query parameter
  2146. filter: Union[str, Iterable[str], None] = None,
  2147. author: Optional[str] = None,
  2148. search: Optional[str] = None,
  2149. datasets: Union[str, Iterable[str], None] = None,
  2150. models: Union[str, Iterable[str], None] = None,
  2151. linked: bool = False,
  2152. # Sorting and pagination parameters
  2153. sort: Optional[SpaceSort_T] = None,
  2154. direction: Optional[Literal[-1]] = None,
  2155. limit: Optional[int] = None,
  2156. # Additional data to fetch
  2157. expand: Optional[list[ExpandSpaceProperty_T]] = None,
  2158. full: Optional[bool] = None,
  2159. token: Union[bool, str, None] = None,
  2160. ) -> Iterable[SpaceInfo]:
  2161. """
  2162. List spaces hosted on the Huggingface Hub, given some filters.
  2163. Args:
  2164. filter (`str` or `Iterable`, *optional*):
  2165. A string tag or list of tags that can be used to identify Spaces on the Hub.
  2166. author (`str`, *optional*):
  2167. A string which identify the author of the returned Spaces.
  2168. search (`str`, *optional*):
  2169. A string that will be contained in the returned Spaces.
  2170. datasets (`str` or `Iterable`, *optional*):
  2171. Whether to return Spaces that make use of a dataset.
  2172. The name of a specific dataset can be passed as a string.
  2173. models (`str` or `Iterable`, *optional*):
  2174. Whether to return Spaces that make use of a model.
  2175. The name of a specific model can be passed as a string.
  2176. linked (`bool`, *optional*):
  2177. Whether to return Spaces that make use of either a model or a dataset.
  2178. sort (`SpaceSort_T`, *optional*):
  2179. The key with which to sort the resulting spaces. Possible values are "created_at", "last_modified",
  2180. "likes" and "trending_score".
  2181. direction (`Literal[-1]` or `int`, *optional*):
  2182. Deprecated. This parameter is not used and will be removed in version 1.5.
  2183. limit (`int`, *optional*):
  2184. The limit on the number of Spaces fetched. Leaving this option
  2185. to `None` fetches all Spaces.
  2186. expand (`list[ExpandSpaceProperty_T]`, *optional*):
  2187. List properties to return in the response. When used, only the properties in the list will be returned.
  2188. This parameter cannot be used if `full` is passed.
  2189. Possible values are `"author"`, `"cardData"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"createdAt"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
  2190. full (`bool`, *optional*):
  2191. Whether to fetch all Spaces data, including the `last_modified`, `siblings`
  2192. and `card_data` fields.
  2193. token (`bool` or `str`, *optional*):
  2194. A valid user access token (string). Defaults to the locally saved
  2195. token, which is the recommended method for authentication (see
  2196. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2197. To disable authentication, pass `False`.
  2198. Returns:
  2199. `Iterable[SpaceInfo]`: an iterable of [`huggingface_hub.hf_api.SpaceInfo`] objects.
  2200. """
  2201. if expand and full:
  2202. raise ValueError("`expand` cannot be used if `full` is passed.")
  2203. path = f"{self.endpoint}/api/spaces"
  2204. headers = self._build_hf_headers(token=token)
  2205. params: dict[str, Any] = {}
  2206. if filter is not None:
  2207. params["filter"] = filter
  2208. if author is not None:
  2209. params["author"] = author
  2210. if search is not None:
  2211. params["search"] = search
  2212. if sort is not None:
  2213. params["sort"] = (
  2214. "lastModified"
  2215. if sort == "last_modified"
  2216. else "trendingScore"
  2217. if sort == "trending_score"
  2218. else "createdAt"
  2219. if sort == "created_at"
  2220. else sort
  2221. )
  2222. if direction is not None:
  2223. params["direction"] = direction
  2224. if limit is not None:
  2225. params["limit"] = limit
  2226. if linked:
  2227. params["linked"] = True
  2228. if datasets is not None:
  2229. params["datasets"] = datasets
  2230. if models is not None:
  2231. params["models"] = models
  2232. # Request additional data
  2233. if expand:
  2234. params["expand"] = expand
  2235. if full:
  2236. params["full"] = True
  2237. items = paginate(path, params=params, headers=headers)
  2238. if limit is not None:
  2239. items = islice(items, limit) # Do not iterate over all pages
  2240. for item in items:
  2241. if "siblings" not in item:
  2242. item["siblings"] = None
  2243. yield SpaceInfo(**item)
  2244. @validate_hf_hub_args
  2245. def unlike(
  2246. self,
  2247. repo_id: str,
  2248. *,
  2249. token: Union[bool, str, None] = None,
  2250. repo_type: Optional[str] = None,
  2251. ) -> None:
  2252. """
  2253. Unlike a given repo on the Hub (e.g. remove from favorite list).
  2254. To prevent spam usage, it is not possible to `like` a repository from a script.
  2255. See also [`list_liked_repos`].
  2256. Args:
  2257. repo_id (`str`):
  2258. The repository to unlike. Example: `"user/my-cool-model"`.
  2259. token (`bool` or `str`, *optional*):
  2260. A valid user access token (string). Defaults to the locally saved
  2261. token, which is the recommended method for authentication (see
  2262. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2263. To disable authentication, pass `False`.
  2264. repo_type (`str`, *optional*):
  2265. Set to `"dataset"` or `"space"` if unliking a dataset or space, `None` or
  2266. `"model"` if unliking a model. Default is `None`.
  2267. Raises:
  2268. [`~utils.RepositoryNotFoundError`]:
  2269. If repository is not found (error 404): wrong repo_id/repo_type, private
  2270. but not authenticated or repo does not exist.
  2271. Example:
  2272. ```python
  2273. >>> from huggingface_hub import list_liked_repos, unlike
  2274. >>> "gpt2" in list_liked_repos().models # we assume you have already liked gpt2
  2275. True
  2276. >>> unlike("gpt2")
  2277. >>> "gpt2" in list_liked_repos().models
  2278. False
  2279. ```
  2280. """
  2281. if repo_type is None:
  2282. repo_type = constants.REPO_TYPE_MODEL
  2283. response = get_session().delete(
  2284. url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/like", headers=self._build_hf_headers(token=token)
  2285. )
  2286. hf_raise_for_status(response)
  2287. @validate_hf_hub_args
  2288. def list_liked_repos(
  2289. self,
  2290. user: Optional[str] = None,
  2291. *,
  2292. token: Union[bool, str, None] = None,
  2293. ) -> UserLikes:
  2294. """
  2295. List all public repos liked by a user on huggingface.co.
  2296. This list is public so token is optional. If `user` is not passed, it defaults to
  2297. the logged in user.
  2298. See also [`unlike`].
  2299. Args:
  2300. user (`str`, *optional*):
  2301. Name of the user for which you want to fetch the likes.
  2302. token (`bool` or `str`, *optional*):
  2303. A valid user access token (string). Defaults to the locally saved
  2304. token, which is the recommended method for authentication (see
  2305. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2306. To disable authentication, pass `False`.
  2307. Returns:
  2308. [`UserLikes`]: object containing the user name and 3 lists of repo ids (1 for
  2309. models, 1 for datasets and 1 for Spaces).
  2310. Raises:
  2311. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  2312. If `user` is not passed and no token found (either from argument or from machine).
  2313. Example:
  2314. ```python
  2315. >>> from huggingface_hub import list_liked_repos
  2316. >>> likes = list_liked_repos("julien-c")
  2317. >>> likes.user
  2318. "julien-c"
  2319. >>> likes.models
  2320. ["osanseviero/streamlit_1.15", "Xhaheen/ChatGPT_HF", ...]
  2321. ```
  2322. """
  2323. # User is either provided explicitly or retrieved from current token.
  2324. if user is None:
  2325. me = self.whoami(token=token)
  2326. if me["type"] == "user":
  2327. user = me["name"]
  2328. else:
  2329. raise ValueError(
  2330. "Cannot list liked repos. You must provide a 'user' as input or be logged in as a user."
  2331. )
  2332. path = f"{self.endpoint}/api/users/{user}/likes"
  2333. headers = self._build_hf_headers(token=token)
  2334. likes = list(paginate(path, params={}, headers=headers))
  2335. # Looping over a list of items similar to:
  2336. # {
  2337. # 'createdAt': '2021-09-09T21:53:27.000Z',
  2338. # 'repo': {
  2339. # 'name': 'PaddlePaddle/PaddleOCR',
  2340. # 'type': 'space'
  2341. # }
  2342. # }
  2343. # Let's loop 3 times over the received list. Less efficient but more straightforward to read.
  2344. return UserLikes(
  2345. user=user,
  2346. total=len(likes),
  2347. models=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "model"],
  2348. datasets=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "dataset"],
  2349. spaces=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "space"],
  2350. )
  2351. @validate_hf_hub_args
  2352. def list_repo_likers(
  2353. self,
  2354. repo_id: str,
  2355. *,
  2356. repo_type: Optional[str] = None,
  2357. token: Union[bool, str, None] = None,
  2358. ) -> Iterable[User]:
  2359. """
  2360. List all users who liked a given repo on the hugging Face Hub.
  2361. See also [`list_liked_repos`].
  2362. Args:
  2363. repo_id (`str`):
  2364. The repository to retrieve . Example: `"user/my-cool-model"`.
  2365. token (`bool` or `str`, *optional*):
  2366. A valid user access token (string). Defaults to the locally saved
  2367. token, which is the recommended method for authentication (see
  2368. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2369. To disable authentication, pass `False`.
  2370. repo_type (`str`, *optional*):
  2371. Set to `"dataset"` or `"space"` if uploading to a dataset or
  2372. space, `None` or `"model"` if uploading to a model. Default is
  2373. `None`.
  2374. Returns:
  2375. `Iterable[User]`: an iterable of [`huggingface_hub.hf_api.User`] objects.
  2376. """
  2377. # Construct the API endpoint
  2378. if repo_type is None:
  2379. repo_type = constants.REPO_TYPE_MODEL
  2380. path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/likers"
  2381. for liker in paginate(path, params={}, headers=self._build_hf_headers(token=token)):
  2382. yield User(username=liker["user"], fullname=liker["fullname"], avatar_url=liker["avatarUrl"])
  2383. @validate_hf_hub_args
  2384. def model_info(
  2385. self,
  2386. repo_id: str,
  2387. *,
  2388. revision: Optional[str] = None,
  2389. timeout: Optional[float] = None,
  2390. securityStatus: Optional[bool] = None,
  2391. files_metadata: bool = False,
  2392. expand: Optional[list[ExpandModelProperty_T]] = None,
  2393. token: Union[bool, str, None] = None,
  2394. ) -> ModelInfo:
  2395. """
  2396. Get info on one specific model on huggingface.co
  2397. Model can be private if you pass an acceptable token or are logged in.
  2398. Args:
  2399. repo_id (`str`):
  2400. A namespace (user or an organization) and a repo name separated
  2401. by a `/`.
  2402. revision (`str`, *optional*):
  2403. The revision of the model repository from which to get the
  2404. information.
  2405. timeout (`float`, *optional*):
  2406. Whether to set a timeout for the request to the Hub.
  2407. securityStatus (`bool`, *optional*):
  2408. Whether to retrieve the security status from the model
  2409. repository as well. The security status will be returned in the `security_repo_status` field.
  2410. files_metadata (`bool`, *optional*):
  2411. Whether or not to retrieve metadata for files in the repository
  2412. (size, LFS metadata, etc). Defaults to `False`.
  2413. expand (`list[ExpandModelProperty_T]`, *optional*):
  2414. List properties to return in the response. When used, only the properties in the list will be returned.
  2415. This parameter cannot be used if `securityStatus` or `files_metadata` are passed.
  2416. Possible values are `"author"`, `"baseModels"`, `"cardData"`, `"childrenModelCount"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"gguf"`, `"inference"`, `"inferenceProviderMapping"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, `"usedStorage"`, and `"resourceGroup"`.
  2417. token (`bool` or `str`, *optional*):
  2418. A valid user access token (string). Defaults to the locally saved
  2419. token, which is the recommended method for authentication (see
  2420. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2421. To disable authentication, pass `False`.
  2422. Returns:
  2423. [`huggingface_hub.hf_api.ModelInfo`]: The model repository information.
  2424. > [!TIP]
  2425. > Raises the following errors:
  2426. >
  2427. > - [`~utils.RepositoryNotFoundError`]
  2428. > If the repository to download from cannot be found. This may be because it doesn't exist,
  2429. > or because it is set to `private` and you do not have access.
  2430. > - [`~utils.RevisionNotFoundError`]
  2431. > If the revision to download from cannot be found.
  2432. """
  2433. if expand and (securityStatus or files_metadata):
  2434. raise ValueError("`expand` cannot be used if `securityStatus` or `files_metadata` are set.")
  2435. headers = self._build_hf_headers(token=token)
  2436. path = (
  2437. f"{self.endpoint}/api/models/{repo_id}"
  2438. if revision is None
  2439. else (f"{self.endpoint}/api/models/{repo_id}/revision/{quote(revision, safe='')}")
  2440. )
  2441. params: dict = {}
  2442. if securityStatus:
  2443. params["securityStatus"] = True
  2444. if files_metadata:
  2445. params["blobs"] = True
  2446. if expand:
  2447. params["expand"] = expand
  2448. r = get_session().get(path, headers=headers, timeout=timeout, params=params)
  2449. hf_raise_for_status(r)
  2450. data = r.json()
  2451. return ModelInfo(**data)
  2452. @validate_hf_hub_args
  2453. def dataset_info(
  2454. self,
  2455. repo_id: str,
  2456. *,
  2457. revision: Optional[str] = None,
  2458. timeout: Optional[float] = None,
  2459. files_metadata: bool = False,
  2460. expand: Optional[list[ExpandDatasetProperty_T]] = None,
  2461. token: Union[bool, str, None] = None,
  2462. ) -> DatasetInfo:
  2463. """
  2464. Get info on one specific dataset on huggingface.co.
  2465. Dataset can be private if you pass an acceptable token.
  2466. Args:
  2467. repo_id (`str`):
  2468. A namespace (user or an organization) and a repo name separated
  2469. by a `/`.
  2470. revision (`str`, *optional*):
  2471. The revision of the dataset repository from which to get the
  2472. information.
  2473. timeout (`float`, *optional*):
  2474. Whether to set a timeout for the request to the Hub.
  2475. files_metadata (`bool`, *optional*):
  2476. Whether or not to retrieve metadata for files in the repository
  2477. (size, LFS metadata, etc). Defaults to `False`.
  2478. expand (`list[ExpandDatasetProperty_T]`, *optional*):
  2479. List properties to return in the response. When used, only the properties in the list will be returned.
  2480. This parameter cannot be used if `files_metadata` is passed.
  2481. Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`,`"usedStorage"`, and `"resourceGroup"`.
  2482. token (`bool` or `str`, *optional*):
  2483. A valid user access token (string). Defaults to the locally saved
  2484. token, which is the recommended method for authentication (see
  2485. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2486. To disable authentication, pass `False`.
  2487. Returns:
  2488. [`hf_api.DatasetInfo`]: The dataset repository information.
  2489. > [!TIP]
  2490. > Raises the following errors:
  2491. >
  2492. > - [`~utils.RepositoryNotFoundError`]
  2493. > If the repository to download from cannot be found. This may be because it doesn't exist,
  2494. > or because it is set to `private` and you do not have access.
  2495. > - [`~utils.RevisionNotFoundError`]
  2496. > If the revision to download from cannot be found.
  2497. """
  2498. if expand and files_metadata:
  2499. raise ValueError("`expand` cannot be used if `files_metadata` is set.")
  2500. headers = self._build_hf_headers(token=token)
  2501. path = (
  2502. f"{self.endpoint}/api/datasets/{repo_id}"
  2503. if revision is None
  2504. else (f"{self.endpoint}/api/datasets/{repo_id}/revision/{quote(revision, safe='')}")
  2505. )
  2506. params: dict = {}
  2507. if files_metadata:
  2508. params["blobs"] = True
  2509. if expand:
  2510. params["expand"] = expand
  2511. r = get_session().get(path, headers=headers, timeout=timeout, params=params)
  2512. hf_raise_for_status(r)
  2513. data = r.json()
  2514. return DatasetInfo(**data)
  2515. @validate_hf_hub_args
  2516. def space_info(
  2517. self,
  2518. repo_id: str,
  2519. *,
  2520. revision: Optional[str] = None,
  2521. timeout: Optional[float] = None,
  2522. files_metadata: bool = False,
  2523. expand: Optional[list[ExpandSpaceProperty_T]] = None,
  2524. token: Union[bool, str, None] = None,
  2525. ) -> SpaceInfo:
  2526. """
  2527. Get info on one specific Space on huggingface.co.
  2528. Space can be private if you pass an acceptable token.
  2529. Args:
  2530. repo_id (`str`):
  2531. A namespace (user or an organization) and a repo name separated
  2532. by a `/`.
  2533. revision (`str`, *optional*):
  2534. The revision of the space repository from which to get the
  2535. information.
  2536. timeout (`float`, *optional*):
  2537. Whether to set a timeout for the request to the Hub.
  2538. files_metadata (`bool`, *optional*):
  2539. Whether or not to retrieve metadata for files in the repository
  2540. (size, LFS metadata, etc). Defaults to `False`.
  2541. expand (`list[ExpandSpaceProperty_T]`, *optional*):
  2542. List properties to return in the response. When used, only the properties in the list will be returned.
  2543. This parameter cannot be used if `full` is passed.
  2544. Possible values are `"author"`, `"cardData"`, `"createdAt"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
  2545. token (`bool` or `str`, *optional*):
  2546. A valid user access token (string). Defaults to the locally saved
  2547. token, which is the recommended method for authentication (see
  2548. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2549. To disable authentication, pass `False`.
  2550. Returns:
  2551. [`~hf_api.SpaceInfo`]: The space repository information.
  2552. > [!TIP]
  2553. > Raises the following errors:
  2554. >
  2555. > - [`~utils.RepositoryNotFoundError`]
  2556. > If the repository to download from cannot be found. This may be because it doesn't exist,
  2557. > or because it is set to `private` and you do not have access.
  2558. > - [`~utils.RevisionNotFoundError`]
  2559. > If the revision to download from cannot be found.
  2560. """
  2561. if expand and files_metadata:
  2562. raise ValueError("`expand` cannot be used if `files_metadata` is set.")
  2563. headers = self._build_hf_headers(token=token)
  2564. path = (
  2565. f"{self.endpoint}/api/spaces/{repo_id}"
  2566. if revision is None
  2567. else (f"{self.endpoint}/api/spaces/{repo_id}/revision/{quote(revision, safe='')}")
  2568. )
  2569. params: dict = {}
  2570. if files_metadata:
  2571. params["blobs"] = True
  2572. if expand:
  2573. params["expand"] = expand
  2574. r = get_session().get(path, headers=headers, timeout=timeout, params=params)
  2575. hf_raise_for_status(r)
  2576. data = r.json()
  2577. return SpaceInfo(**data)
  2578. @validate_hf_hub_args
  2579. def repo_info(
  2580. self,
  2581. repo_id: str,
  2582. *,
  2583. revision: Optional[str] = None,
  2584. repo_type: Optional[str] = None,
  2585. timeout: Optional[float] = None,
  2586. files_metadata: bool = False,
  2587. expand: Optional[Union[ExpandModelProperty_T, ExpandDatasetProperty_T, ExpandSpaceProperty_T]] = None,
  2588. token: Union[bool, str, None] = None,
  2589. ) -> Union[ModelInfo, DatasetInfo, SpaceInfo]:
  2590. """
  2591. Get the info object for a given repo of a given type.
  2592. Args:
  2593. repo_id (`str`):
  2594. A namespace (user or an organization) and a repo name separated
  2595. by a `/`.
  2596. revision (`str`, *optional*):
  2597. The revision of the repository from which to get the
  2598. information.
  2599. repo_type (`str`, *optional*):
  2600. Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
  2601. `None` or `"model"` if getting repository info from a model. Default is `None`.
  2602. timeout (`float`, *optional*):
  2603. Whether to set a timeout for the request to the Hub.
  2604. expand (`ExpandModelProperty_T` or `ExpandDatasetProperty_T` or `ExpandSpaceProperty_T`, *optional*):
  2605. List properties to return in the response. When used, only the properties in the list will be returned.
  2606. This parameter cannot be used if `files_metadata` is passed.
  2607. For an exhaustive list of available properties, check out [`model_info`], [`dataset_info`] or [`space_info`].
  2608. files_metadata (`bool`, *optional*):
  2609. Whether or not to retrieve metadata for files in the repository
  2610. (size, LFS metadata, etc). Defaults to `False`.
  2611. token (`bool` or `str`, *optional*):
  2612. A valid user access token (string). Defaults to the locally saved
  2613. token, which is the recommended method for authentication (see
  2614. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2615. To disable authentication, pass `False`.
  2616. Returns:
  2617. `Union[SpaceInfo, DatasetInfo, ModelInfo]`: The repository information, as a
  2618. [`huggingface_hub.hf_api.DatasetInfo`], [`huggingface_hub.hf_api.ModelInfo`]
  2619. or [`huggingface_hub.hf_api.SpaceInfo`] object.
  2620. > [!TIP]
  2621. > Raises the following errors:
  2622. >
  2623. > - [`~utils.RepositoryNotFoundError`]
  2624. > If the repository to download from cannot be found. This may be because it doesn't exist,
  2625. > or because it is set to `private` and you do not have access.
  2626. > - [`~utils.RevisionNotFoundError`]
  2627. > If the revision to download from cannot be found.
  2628. """
  2629. if repo_type is None or repo_type == "model":
  2630. method = self.model_info
  2631. elif repo_type == "dataset":
  2632. method = self.dataset_info # type: ignore
  2633. elif repo_type == "space":
  2634. method = self.space_info # type: ignore
  2635. else:
  2636. raise ValueError("Unsupported repo type.")
  2637. return method(
  2638. repo_id,
  2639. revision=revision,
  2640. token=token,
  2641. timeout=timeout,
  2642. expand=expand, # type: ignore[arg-type]
  2643. files_metadata=files_metadata,
  2644. )
  2645. @validate_hf_hub_args
  2646. def repo_exists(
  2647. self,
  2648. repo_id: str,
  2649. *,
  2650. repo_type: Optional[str] = None,
  2651. token: Union[str, bool, None] = None,
  2652. ) -> bool:
  2653. """
  2654. Checks if a repository exists on the Hugging Face Hub.
  2655. Args:
  2656. repo_id (`str`):
  2657. A namespace (user or an organization) and a repo name separated
  2658. by a `/`.
  2659. repo_type (`str`, *optional*):
  2660. Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
  2661. `None` or `"model"` if getting repository info from a model. Default is `None`.
  2662. token (`bool` or `str`, *optional*):
  2663. A valid user access token (string). Defaults to the locally saved
  2664. token, which is the recommended method for authentication (see
  2665. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2666. To disable authentication, pass `False`.
  2667. Returns:
  2668. True if the repository exists, False otherwise.
  2669. Examples:
  2670. ```py
  2671. >>> from huggingface_hub import repo_exists
  2672. >>> repo_exists("google/gemma-7b")
  2673. True
  2674. >>> repo_exists("google/not-a-repo")
  2675. False
  2676. ```
  2677. """
  2678. try:
  2679. self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token)
  2680. return True
  2681. except GatedRepoError:
  2682. return True # we don't have access but it exists
  2683. except RepositoryNotFoundError:
  2684. return False
  2685. @validate_hf_hub_args
  2686. def revision_exists(
  2687. self,
  2688. repo_id: str,
  2689. revision: str,
  2690. *,
  2691. repo_type: Optional[str] = None,
  2692. token: Union[str, bool, None] = None,
  2693. ) -> bool:
  2694. """
  2695. Checks if a specific revision exists on a repo on the Hugging Face Hub.
  2696. Args:
  2697. repo_id (`str`):
  2698. A namespace (user or an organization) and a repo name separated
  2699. by a `/`.
  2700. revision (`str`):
  2701. The revision of the repository to check.
  2702. repo_type (`str`, *optional*):
  2703. Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
  2704. `None` or `"model"` if getting repository info from a model. Default is `None`.
  2705. token (`bool` or `str`, *optional*):
  2706. A valid user access token (string). Defaults to the locally saved
  2707. token, which is the recommended method for authentication (see
  2708. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2709. To disable authentication, pass `False`.
  2710. Returns:
  2711. True if the repository and the revision exists, False otherwise.
  2712. Examples:
  2713. ```py
  2714. >>> from huggingface_hub import revision_exists
  2715. >>> revision_exists("google/gemma-7b", "float16")
  2716. True
  2717. >>> revision_exists("google/gemma-7b", "not-a-revision")
  2718. False
  2719. ```
  2720. """
  2721. try:
  2722. self.repo_info(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token)
  2723. return True
  2724. except RevisionNotFoundError:
  2725. return False
  2726. except RepositoryNotFoundError:
  2727. return False
  2728. @validate_hf_hub_args
  2729. def file_exists(
  2730. self,
  2731. repo_id: str,
  2732. filename: str,
  2733. *,
  2734. repo_type: Optional[str] = None,
  2735. revision: Optional[str] = None,
  2736. token: Union[str, bool, None] = None,
  2737. ) -> bool:
  2738. """
  2739. Checks if a file exists in a repository on the Hugging Face Hub.
  2740. Args:
  2741. repo_id (`str`):
  2742. A namespace (user or an organization) and a repo name separated
  2743. by a `/`.
  2744. filename (`str`):
  2745. The name of the file to check, for example:
  2746. `"config.json"`
  2747. repo_type (`str`, *optional*):
  2748. Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
  2749. `None` or `"model"` if getting repository info from a model. Default is `None`.
  2750. revision (`str`, *optional*):
  2751. The revision of the repository from which to get the information. Defaults to `"main"` branch.
  2752. token (`bool` or `str`, *optional*):
  2753. A valid user access token (string). Defaults to the locally saved
  2754. token, which is the recommended method for authentication (see
  2755. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2756. To disable authentication, pass `False`.
  2757. Returns:
  2758. True if the file exists, False otherwise.
  2759. Examples:
  2760. ```py
  2761. >>> from huggingface_hub import file_exists
  2762. >>> file_exists("bigcode/starcoder", "config.json")
  2763. True
  2764. >>> file_exists("bigcode/starcoder", "not-a-file")
  2765. False
  2766. >>> file_exists("bigcode/not-a-repo", "config.json")
  2767. False
  2768. ```
  2769. """
  2770. url = hf_hub_url(
  2771. repo_id=repo_id, repo_type=repo_type, revision=revision, filename=filename, endpoint=self.endpoint
  2772. )
  2773. try:
  2774. if token is None:
  2775. token = self.token
  2776. get_hf_file_metadata(url, token=token)
  2777. return True
  2778. except GatedRepoError: # raise specifically on gated repo
  2779. raise
  2780. except (RepositoryNotFoundError, RemoteEntryNotFoundError, RevisionNotFoundError):
  2781. return False
  2782. @validate_hf_hub_args
  2783. def list_repo_files(
  2784. self,
  2785. repo_id: str,
  2786. *,
  2787. revision: Optional[str] = None,
  2788. repo_type: Optional[str] = None,
  2789. token: Union[str, bool, None] = None,
  2790. ) -> list[str]:
  2791. """
  2792. Get the list of files in a given repo.
  2793. Args:
  2794. repo_id (`str`):
  2795. A namespace (user or an organization) and a repo name separated by a `/`.
  2796. revision (`str`, *optional*):
  2797. The revision of the repository from which to get the information.
  2798. repo_type (`str`, *optional*):
  2799. Set to `"dataset"` or `"space"` if uploading to a dataset or space, `None` or `"model"` if uploading to
  2800. a model. Default is `None`.
  2801. token (`bool` or `str`, *optional*):
  2802. A valid user access token (string). Defaults to the locally saved
  2803. token, which is the recommended method for authentication (see
  2804. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2805. To disable authentication, pass `False`.
  2806. Returns:
  2807. `list[str]`: the list of files in a given repository.
  2808. """
  2809. return [
  2810. f.rfilename
  2811. for f in self.list_repo_tree(
  2812. repo_id=repo_id, recursive=True, revision=revision, repo_type=repo_type, token=token
  2813. )
  2814. if isinstance(f, RepoFile)
  2815. ]
  2816. @validate_hf_hub_args
  2817. def list_repo_tree(
  2818. self,
  2819. repo_id: str,
  2820. path_in_repo: Optional[str] = None,
  2821. *,
  2822. recursive: bool = False,
  2823. expand: bool = False,
  2824. revision: Optional[str] = None,
  2825. repo_type: Optional[str] = None,
  2826. token: Union[str, bool, None] = None,
  2827. ) -> Iterable[Union[RepoFile, RepoFolder]]:
  2828. """
  2829. List a repo tree's files and folders and get information about them.
  2830. Args:
  2831. repo_id (`str`):
  2832. A namespace (user or an organization) and a repo name separated by a `/`.
  2833. path_in_repo (`str`, *optional*):
  2834. Relative path of the tree (folder) in the repo, for example:
  2835. `"checkpoints/1fec34a/results"`. Will default to the root tree (folder) of the repository.
  2836. recursive (`bool`, *optional*, defaults to `False`):
  2837. Whether to list tree's files and folders recursively.
  2838. expand (`bool`, *optional*, defaults to `False`):
  2839. Whether to fetch more information about the tree's files and folders (e.g. last commit and files' security scan results). This
  2840. operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
  2841. As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
  2842. takes to get the results.
  2843. revision (`str`, *optional*):
  2844. The revision of the repository from which to get the tree. Defaults to `"main"` branch.
  2845. repo_type (`str`, *optional*):
  2846. The type of the repository from which to get the tree (`"model"`, `"dataset"` or `"space"`.
  2847. Defaults to `"model"`.
  2848. token (`bool` or `str`, *optional*):
  2849. A valid user access token (string). Defaults to the locally saved
  2850. token, which is the recommended method for authentication (see
  2851. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2852. To disable authentication, pass `False`.
  2853. Returns:
  2854. `Iterable[Union[RepoFile, RepoFolder]]`:
  2855. The information about the tree's files and folders, as an iterable of [`RepoFile`] and [`RepoFolder`] objects. The order of the files and folders is
  2856. not guaranteed.
  2857. Raises:
  2858. [`~utils.RepositoryNotFoundError`]:
  2859. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  2860. does not exist.
  2861. [`~utils.RevisionNotFoundError`]:
  2862. If revision is not found (error 404) on the repo.
  2863. [`~utils.RemoteEntryNotFoundError`]:
  2864. If the tree (folder) does not exist (error 404) on the repo.
  2865. Examples:
  2866. Get information about a repo's tree.
  2867. ```py
  2868. >>> from huggingface_hub import list_repo_tree
  2869. >>> repo_tree = list_repo_tree("lysandre/arxiv-nlp")
  2870. >>> repo_tree
  2871. <generator object HfApi.list_repo_tree at 0x7fa4088e1ac0>
  2872. >>> list(repo_tree)
  2873. [
  2874. RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None),
  2875. RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None),
  2876. RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None),
  2877. RepoFile(
  2878. path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e',
  2879. lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None
  2880. ),
  2881. RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None),
  2882. RepoFile(
  2883. path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523',
  2884. lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None
  2885. ),
  2886. RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)]
  2887. ]
  2888. ```
  2889. Get even more information about a repo's tree (last commit and files' security scan results)
  2890. ```py
  2891. >>> from huggingface_hub import list_repo_tree
  2892. >>> repo_tree = list_repo_tree("prompthero/openjourney-v4", expand=True)
  2893. >>> list(repo_tree)
  2894. [
  2895. RepoFolder(
  2896. path='feature_extractor',
  2897. tree_id='aa536c4ea18073388b5b0bc791057a7296a00398',
  2898. last_commit={
  2899. 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
  2900. 'title': 'Upload diffusers weights (#48)',
  2901. 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
  2902. }
  2903. ),
  2904. RepoFolder(
  2905. path='safety_checker',
  2906. tree_id='65aef9d787e5557373fdf714d6c34d4fcdd70440',
  2907. last_commit={
  2908. 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
  2909. 'title': 'Upload diffusers weights (#48)',
  2910. 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
  2911. }
  2912. ),
  2913. RepoFile(
  2914. path='model_index.json',
  2915. size=582,
  2916. blob_id='d3d7c1e8c3e78eeb1640b8e2041ee256e24c9ee1',
  2917. lfs=None,
  2918. last_commit={
  2919. 'oid': 'b195ed2d503f3eb29637050a886d77bd81d35f0e',
  2920. 'title': 'Fix deprecation warning by changing `CLIPFeatureExtractor` to `CLIPImageProcessor`. (#54)',
  2921. 'date': datetime.datetime(2023, 5, 15, 21, 41, 59, tzinfo=datetime.timezone.utc)
  2922. },
  2923. security={
  2924. 'safe': True,
  2925. 'av_scan': {'virusFound': False, 'virusNames': None},
  2926. 'pickle_import_scan': None
  2927. }
  2928. )
  2929. ...
  2930. ]
  2931. ```
  2932. """
  2933. repo_type = repo_type or constants.REPO_TYPE_MODEL
  2934. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  2935. headers = self._build_hf_headers(token=token)
  2936. encoded_path_in_repo = "/" + quote(path_in_repo, safe="") if path_in_repo else ""
  2937. tree_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tree/{revision}{encoded_path_in_repo}"
  2938. for path_info in paginate(path=tree_url, headers=headers, params={"recursive": recursive, "expand": expand}):
  2939. yield (RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info))
  2940. @validate_hf_hub_args
  2941. def verify_repo_checksums(
  2942. self,
  2943. repo_id: str,
  2944. *,
  2945. repo_type: Optional[str] = None,
  2946. revision: Optional[str] = None,
  2947. local_dir: Optional[Union[str, Path]] = None,
  2948. cache_dir: Optional[Union[str, Path]] = None,
  2949. token: Union[str, bool, None] = None,
  2950. ) -> "FolderVerification":
  2951. """
  2952. Verify local files for a repo against Hub checksums.
  2953. Args:
  2954. repo_id (`str`):
  2955. A namespace (user or an organization) and a repo name separated by a `/`.
  2956. repo_type (`str`, *optional*):
  2957. The type of the repository from which to get the tree (`"model"`, `"dataset"` or `"space"`.
  2958. Defaults to `"model"`.
  2959. revision (`str`, *optional*):
  2960. The revision of the repository from which to get the tree. Defaults to `"main"` branch.
  2961. local_dir (`str` or `Path`, *optional*):
  2962. The local directory to verify.
  2963. cache_dir (`str` or `Path`, *optional*):
  2964. The cache directory to verify.
  2965. token (Union[bool, str, None], optional):
  2966. A valid user access token (string). Defaults to the locally saved
  2967. token, which is the recommended method for authentication (see
  2968. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2969. To disable authentication, pass `False`.
  2970. Returns:
  2971. [`FolderVerification`]: a structured result containing the verification details.
  2972. Raises:
  2973. [`~utils.RepositoryNotFoundError`]:
  2974. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  2975. does not exist.
  2976. [`~utils.RevisionNotFoundError`]:
  2977. If revision is not found (error 404) on the repo.
  2978. """
  2979. if repo_type is None:
  2980. repo_type = constants.REPO_TYPE_MODEL
  2981. if local_dir is not None and cache_dir is not None:
  2982. raise ValueError("Pass either `local_dir` or `cache_dir`, not both.")
  2983. root, remote_revision = resolve_local_root(
  2984. repo_id=repo_id,
  2985. repo_type=repo_type,
  2986. revision=revision,
  2987. cache_dir=Path(cache_dir) if cache_dir is not None else None,
  2988. local_dir=Path(local_dir) if local_dir is not None else None,
  2989. )
  2990. local_by_path = collect_local_files(root)
  2991. # get remote entries (only files, not folders)
  2992. remote_by_path: dict[str, RepoFile] = {}
  2993. for entry in self.list_repo_tree(
  2994. repo_id=repo_id, recursive=True, revision=remote_revision, repo_type=repo_type, token=token
  2995. ):
  2996. if isinstance(entry, RepoFile):
  2997. remote_by_path[entry.path] = entry
  2998. return verify_maps(
  2999. remote_by_path=remote_by_path,
  3000. local_by_path=local_by_path,
  3001. revision=remote_revision,
  3002. verified_path=root,
  3003. )
  3004. @validate_hf_hub_args
  3005. def list_repo_refs(
  3006. self,
  3007. repo_id: str,
  3008. *,
  3009. repo_type: Optional[str] = None,
  3010. include_pull_requests: bool = False,
  3011. token: Union[str, bool, None] = None,
  3012. ) -> GitRefs:
  3013. """
  3014. Get the list of refs of a given repo (both tags and branches).
  3015. Args:
  3016. repo_id (`str`):
  3017. A namespace (user or an organization) and a repo name separated
  3018. by a `/`.
  3019. repo_type (`str`, *optional*):
  3020. Set to `"dataset"` or `"space"` if listing refs from a dataset or a Space,
  3021. `None` or `"model"` if listing from a model. Default is `None`.
  3022. include_pull_requests (`bool`, *optional*):
  3023. Whether to include refs from pull requests in the list. Defaults to `False`.
  3024. token (`bool` or `str`, *optional*):
  3025. A valid user access token (string). Defaults to the locally saved
  3026. token, which is the recommended method for authentication (see
  3027. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3028. To disable authentication, pass `False`.
  3029. Example:
  3030. ```py
  3031. >>> from huggingface_hub import HfApi
  3032. >>> api = HfApi()
  3033. >>> api.list_repo_refs("gpt2")
  3034. GitRefs(branches=[GitRefInfo(name='main', ref='refs/heads/main', target_commit='e7da7f221d5bf496a48136c0cd264e630fe9fcc8')], converts=[], tags=[])
  3035. >>> api.list_repo_refs("bigcode/the-stack", repo_type='dataset')
  3036. GitRefs(
  3037. branches=[
  3038. GitRefInfo(name='main', ref='refs/heads/main', target_commit='18edc1591d9ce72aa82f56c4431b3c969b210ae3'),
  3039. GitRefInfo(name='v1.1.a1', ref='refs/heads/v1.1.a1', target_commit='f9826b862d1567f3822d3d25649b0d6d22ace714')
  3040. ],
  3041. converts=[],
  3042. tags=[
  3043. GitRefInfo(name='v1.0', ref='refs/tags/v1.0', target_commit='c37a8cd1e382064d8aced5e05543c5f7753834da')
  3044. ]
  3045. )
  3046. ```
  3047. Returns:
  3048. [`GitRefs`]: object containing all information about branches and tags for a
  3049. repo on the Hub.
  3050. """
  3051. repo_type = repo_type or constants.REPO_TYPE_MODEL
  3052. response = get_session().get(
  3053. f"{self.endpoint}/api/{repo_type}s/{repo_id}/refs",
  3054. headers=self._build_hf_headers(token=token),
  3055. params={"include_prs": 1} if include_pull_requests else {},
  3056. )
  3057. hf_raise_for_status(response)
  3058. data = response.json()
  3059. def _format_as_git_ref_info(item: dict) -> GitRefInfo:
  3060. return GitRefInfo(name=item["name"], ref=item["ref"], target_commit=item["targetCommit"])
  3061. return GitRefs(
  3062. branches=[_format_as_git_ref_info(item) for item in data["branches"]],
  3063. converts=[_format_as_git_ref_info(item) for item in data["converts"]],
  3064. tags=[_format_as_git_ref_info(item) for item in data["tags"]],
  3065. pull_requests=[_format_as_git_ref_info(item) for item in data["pullRequests"]]
  3066. if include_pull_requests
  3067. else None,
  3068. )
  3069. @validate_hf_hub_args
  3070. def list_repo_commits(
  3071. self,
  3072. repo_id: str,
  3073. *,
  3074. repo_type: Optional[str] = None,
  3075. token: Union[bool, str, None] = None,
  3076. revision: Optional[str] = None,
  3077. formatted: bool = False,
  3078. ) -> list[GitCommitInfo]:
  3079. """
  3080. Get the list of commits of a given revision for a repo on the Hub.
  3081. Commits are sorted by date (last commit first).
  3082. Args:
  3083. repo_id (`str`):
  3084. A namespace (user or an organization) and a repo name separated by a `/`.
  3085. repo_type (`str`, *optional*):
  3086. Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
  3087. listing from a model. Default is `None`.
  3088. token (`bool` or `str`, *optional*):
  3089. A valid user access token (string). Defaults to the locally saved
  3090. token, which is the recommended method for authentication (see
  3091. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3092. To disable authentication, pass `False`.
  3093. revision (`str`, *optional*):
  3094. The git revision to commit from. Defaults to the head of the `"main"` branch.
  3095. formatted (`bool`):
  3096. Whether to return the HTML-formatted title and description of the commits. Defaults to False.
  3097. Example:
  3098. ```py
  3099. >>> from huggingface_hub import HfApi
  3100. >>> api = HfApi()
  3101. # Commits are sorted by date (last commit first)
  3102. >>> initial_commit = api.list_repo_commits("gpt2")[-1]
  3103. # Initial commit is always a system commit containing the `.gitattributes` file.
  3104. >>> initial_commit
  3105. GitCommitInfo(
  3106. commit_id='9b865efde13a30c13e0a33e536cf3e4a5a9d71d8',
  3107. authors=['system'],
  3108. created_at=datetime.datetime(2019, 2, 18, 10, 36, 15, tzinfo=datetime.timezone.utc),
  3109. title='initial commit',
  3110. message='',
  3111. formatted_title=None,
  3112. formatted_message=None
  3113. )
  3114. # Create an empty branch by deriving from initial commit
  3115. >>> api.create_branch("gpt2", "new_empty_branch", revision=initial_commit.commit_id)
  3116. ```
  3117. Returns:
  3118. list[[`GitCommitInfo`]]: list of objects containing information about the commits for a repo on the Hub.
  3119. Raises:
  3120. [`~utils.RepositoryNotFoundError`]:
  3121. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  3122. does not exist.
  3123. [`~utils.RevisionNotFoundError`]:
  3124. If revision is not found (error 404) on the repo.
  3125. """
  3126. repo_type = repo_type or constants.REPO_TYPE_MODEL
  3127. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  3128. # Paginate over results and return the list of commits.
  3129. return [
  3130. GitCommitInfo(
  3131. commit_id=item["id"],
  3132. authors=[author["user"] for author in item["authors"]],
  3133. created_at=parse_datetime(item["date"]),
  3134. title=item["title"],
  3135. message=item["message"],
  3136. formatted_title=item.get("formatted", {}).get("title"),
  3137. formatted_message=item.get("formatted", {}).get("message"),
  3138. )
  3139. for item in paginate(
  3140. f"{self.endpoint}/api/{repo_type}s/{repo_id}/commits/{revision}",
  3141. headers=self._build_hf_headers(token=token),
  3142. params={"expand[]": "formatted"} if formatted else {},
  3143. )
  3144. ]
  3145. @validate_hf_hub_args
  3146. def get_paths_info(
  3147. self,
  3148. repo_id: str,
  3149. paths: Union[list[str], str],
  3150. *,
  3151. expand: bool = False,
  3152. revision: Optional[str] = None,
  3153. repo_type: Optional[str] = None,
  3154. token: Union[str, bool, None] = None,
  3155. ) -> list[Union[RepoFile, RepoFolder]]:
  3156. """
  3157. Get information about a repo's paths.
  3158. Args:
  3159. repo_id (`str`):
  3160. A namespace (user or an organization) and a repo name separated by a `/`.
  3161. paths (`Union[list[str], str]`, *optional*):
  3162. The paths to get information about. If a path do not exist, it is ignored without raising
  3163. an exception.
  3164. expand (`bool`, *optional*, defaults to `False`):
  3165. Whether to fetch more information about the paths (e.g. last commit and files' security scan results). This
  3166. operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
  3167. As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
  3168. takes to get the results.
  3169. revision (`str`, *optional*):
  3170. The revision of the repository from which to get the information. Defaults to `"main"` branch.
  3171. repo_type (`str`, *optional*):
  3172. The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`.
  3173. Defaults to `"model"`.
  3174. token (`bool` or `str`, *optional*):
  3175. A valid user access token (string). Defaults to the locally saved
  3176. token, which is the recommended method for authentication (see
  3177. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3178. To disable authentication, pass `False`.
  3179. Returns:
  3180. `list[Union[RepoFile, RepoFolder]]`:
  3181. The information about the paths, as a list of [`RepoFile`] and [`RepoFolder`] objects.
  3182. Raises:
  3183. [`~utils.RepositoryNotFoundError`]:
  3184. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  3185. does not exist.
  3186. [`~utils.RevisionNotFoundError`]:
  3187. If revision is not found (error 404) on the repo.
  3188. Example:
  3189. ```py
  3190. >>> from huggingface_hub import get_paths_info
  3191. >>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset")
  3192. >>> paths_info
  3193. [
  3194. RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None),
  3195. RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None)
  3196. ]
  3197. ```
  3198. """
  3199. repo_type = repo_type or constants.REPO_TYPE_MODEL
  3200. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  3201. headers = self._build_hf_headers(token=token)
  3202. response = get_session().post(
  3203. f"{self.endpoint}/api/{repo_type}s/{repo_id}/paths-info/{revision}",
  3204. data={
  3205. "paths": paths if isinstance(paths, list) else [paths],
  3206. "expand": expand,
  3207. },
  3208. headers=headers,
  3209. )
  3210. hf_raise_for_status(response)
  3211. paths_info = response.json()
  3212. return [
  3213. RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info)
  3214. for path_info in paths_info
  3215. ]
  3216. @validate_hf_hub_args
  3217. def super_squash_history(
  3218. self,
  3219. repo_id: str,
  3220. *,
  3221. branch: Optional[str] = None,
  3222. commit_message: Optional[str] = None,
  3223. repo_type: Optional[str] = None,
  3224. token: Union[str, bool, None] = None,
  3225. ) -> None:
  3226. """Squash commit history on a branch for a repo on the Hub.
  3227. Squashing the repo history is useful when you know you'll make hundreds of commits and you don't want to
  3228. clutter the history. Squashing commits can only be performed from the head of a branch.
  3229. > [!WARNING]
  3230. > Once squashed, the commit history cannot be retrieved. This is a non-revertible operation.
  3231. > [!WARNING]
  3232. > Once the history of a branch has been squashed, it is not possible to merge it back into another branch since
  3233. > their history will have diverged.
  3234. Args:
  3235. repo_id (`str`):
  3236. A namespace (user or an organization) and a repo name separated by a `/`.
  3237. branch (`str`, *optional*):
  3238. The branch to squash. Defaults to the head of the `"main"` branch.
  3239. commit_message (`str`, *optional*):
  3240. The commit message to use for the squashed commit.
  3241. repo_type (`str`, *optional*):
  3242. Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
  3243. listing from a model. Default is `None`.
  3244. token (`bool` or `str`, *optional*):
  3245. A valid user access token (string). Defaults to the locally saved
  3246. token, which is the recommended method for authentication (see
  3247. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3248. To disable authentication, pass `False`.
  3249. Raises:
  3250. [`~utils.RepositoryNotFoundError`]:
  3251. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  3252. does not exist.
  3253. [`~utils.RevisionNotFoundError`]:
  3254. If the branch to squash cannot be found.
  3255. [`~utils.BadRequestError`]:
  3256. If invalid reference for a branch. You cannot squash history on tags.
  3257. Example:
  3258. ```py
  3259. >>> from huggingface_hub import HfApi
  3260. >>> api = HfApi()
  3261. # Create repo
  3262. >>> repo_id = api.create_repo("test-squash").repo_id
  3263. # Make a lot of commits.
  3264. >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content")
  3265. >>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content")
  3266. >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content")
  3267. # Squash history
  3268. >>> api.super_squash_history(repo_id=repo_id)
  3269. ```
  3270. """
  3271. if repo_type is None:
  3272. repo_type = constants.REPO_TYPE_MODEL
  3273. if repo_type not in constants.REPO_TYPES:
  3274. raise ValueError("Invalid repo type")
  3275. if branch is None:
  3276. branch = constants.DEFAULT_REVISION
  3277. # Prepare request
  3278. url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/super-squash/{quote(branch, safe='')}"
  3279. headers = self._build_hf_headers(token=token)
  3280. commit_message = commit_message or f"Super-squash branch '{branch}' using huggingface_hub"
  3281. # Super-squash
  3282. response = get_session().post(url=url, headers=headers, json={"message": commit_message})
  3283. hf_raise_for_status(response)
  3284. @validate_hf_hub_args
  3285. def list_lfs_files(
  3286. self,
  3287. repo_id: str,
  3288. *,
  3289. repo_type: Optional[str] = None,
  3290. token: Union[bool, str, None] = None,
  3291. ) -> Iterable[LFSFileInfo]:
  3292. """
  3293. List all LFS files in a repo on the Hub.
  3294. This is primarily useful to count how much storage a repo is using and to eventually clean up large files
  3295. with [`permanently_delete_lfs_files`]. Note that this would be a permanent action that will affect all commits
  3296. referencing this deleted files and that cannot be undone.
  3297. Args:
  3298. repo_id (`str`):
  3299. The repository for which you are listing LFS files.
  3300. repo_type (`str`, *optional*):
  3301. Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or
  3302. `"model"` if listing from a model. Default is `None`.
  3303. token (`bool` or `str`, *optional*):
  3304. A valid user access token (string). Defaults to the locally saved
  3305. token, which is the recommended method for authentication (see
  3306. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3307. To disable authentication, pass `False`.
  3308. Returns:
  3309. `Iterable[LFSFileInfo]`: An iterator of [`LFSFileInfo`] objects.
  3310. Example:
  3311. ```py
  3312. >>> from huggingface_hub import HfApi
  3313. >>> api = HfApi()
  3314. >>> lfs_files = api.list_lfs_files("username/my-cool-repo")
  3315. # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
  3316. # e.g. select only LFS files in the "checkpoints" folder
  3317. >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
  3318. # Permanently delete LFS files
  3319. >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
  3320. ```
  3321. """
  3322. # Prepare request
  3323. if repo_type is None:
  3324. repo_type = constants.REPO_TYPE_MODEL
  3325. url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/lfs-files"
  3326. headers = self._build_hf_headers(token=token)
  3327. # Paginate over LFS items
  3328. for item in paginate(url, params={}, headers=headers):
  3329. yield LFSFileInfo(**item)
  3330. @validate_hf_hub_args
  3331. def permanently_delete_lfs_files(
  3332. self,
  3333. repo_id: str,
  3334. lfs_files: Iterable[LFSFileInfo],
  3335. *,
  3336. rewrite_history: bool = True,
  3337. repo_type: Optional[str] = None,
  3338. token: Union[bool, str, None] = None,
  3339. ) -> None:
  3340. """
  3341. Permanently delete LFS files from a repo on the Hub.
  3342. > [!WARNING]
  3343. > This is a permanent action that will affect all commits referencing the deleted files and might corrupt your
  3344. > repository. This is a non-revertible operation. Use it only if you know what you are doing.
  3345. Args:
  3346. repo_id (`str`):
  3347. The repository for which you are listing LFS files.
  3348. lfs_files (`Iterable[LFSFileInfo]`):
  3349. An iterable of [`LFSFileInfo`] items to permanently delete from the repo. Use [`list_lfs_files`] to list
  3350. all LFS files from a repo.
  3351. rewrite_history (`bool`, *optional*, default to `True`):
  3352. Whether to rewrite repository history to remove file pointers referencing the deleted LFS files (recommended).
  3353. repo_type (`str`, *optional*):
  3354. Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or
  3355. `"model"` if listing from a model. Default is `None`.
  3356. token (`bool` or `str`, *optional*):
  3357. A valid user access token (string). Defaults to the locally saved
  3358. token, which is the recommended method for authentication (see
  3359. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3360. To disable authentication, pass `False`.
  3361. Example:
  3362. ```py
  3363. >>> from huggingface_hub import HfApi
  3364. >>> api = HfApi()
  3365. >>> lfs_files = api.list_lfs_files("username/my-cool-repo")
  3366. # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
  3367. # e.g. select only LFS files in the "checkpoints" folder
  3368. >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
  3369. # Permanently delete LFS files
  3370. >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
  3371. ```
  3372. """
  3373. # Prepare request
  3374. if repo_type is None:
  3375. repo_type = constants.REPO_TYPE_MODEL
  3376. url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/lfs-files/batch"
  3377. headers = self._build_hf_headers(token=token)
  3378. # Delete LFS items by batches of 1000
  3379. for batch in chunk_iterable(lfs_files, 1000):
  3380. shas = [item.file_oid for item in batch]
  3381. if len(shas) == 0:
  3382. return
  3383. payload = {
  3384. "deletions": {
  3385. "sha": shas,
  3386. "rewriteHistory": rewrite_history,
  3387. }
  3388. }
  3389. response = get_session().post(url, headers=headers, json=payload)
  3390. hf_raise_for_status(response)
  3391. @validate_hf_hub_args
  3392. def create_repo(
  3393. self,
  3394. repo_id: str,
  3395. *,
  3396. token: Union[str, bool, None] = None,
  3397. private: Optional[bool] = None,
  3398. repo_type: Optional[str] = None,
  3399. exist_ok: bool = False,
  3400. resource_group_id: Optional[str] = None,
  3401. space_sdk: Optional[str] = None,
  3402. space_hardware: Optional[SpaceHardware] = None,
  3403. space_storage: Optional[SpaceStorage] = None,
  3404. space_sleep_time: Optional[int] = None,
  3405. space_secrets: Optional[list[dict[str, str]]] = None,
  3406. space_variables: Optional[list[dict[str, str]]] = None,
  3407. ) -> RepoUrl:
  3408. """Create an empty repo on the HuggingFace Hub.
  3409. Args:
  3410. repo_id (`str`):
  3411. A namespace (user or an organization) and a repo name separated
  3412. by a `/`.
  3413. token (`bool` or `str`, *optional*):
  3414. A valid user access token (string). Defaults to the locally saved
  3415. token, which is the recommended method for authentication (see
  3416. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3417. To disable authentication, pass `False`.
  3418. private (`bool`, *optional*):
  3419. Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
  3420. repo_type (`str`, *optional*):
  3421. Set to `"dataset"` or `"space"` if uploading to a dataset or
  3422. space, `None` or `"model"` if uploading to a model. Default is
  3423. `None`.
  3424. exist_ok (`bool`, *optional*, defaults to `False`):
  3425. If `True`, do not raise an error if repo already exists.
  3426. resource_group_id (`str`, *optional*):
  3427. Resource group in which to create the repo. Resource groups is only available for Enterprise Hub organizations and
  3428. allow to define which members of the organization can access the resource. The ID of a resource group
  3429. can be found in the URL of the resource's page on the Hub (e.g. `"66670e5163145ca562cb1988"`).
  3430. To learn more about resource groups, see https://huggingface.co/docs/hub/en/security-resource-groups.
  3431. space_sdk (`str`, *optional*):
  3432. Choice of SDK to use if repo_type is "space". Can be "streamlit", "gradio", "docker", or "static".
  3433. space_hardware (`SpaceHardware` or `str`, *optional*):
  3434. Choice of Hardware if repo_type is "space". See [`SpaceHardware`] for a complete list.
  3435. space_storage (`SpaceStorage` or `str`, *optional*):
  3436. Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
  3437. space_sleep_time (`int`, *optional*):
  3438. Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
  3439. your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
  3440. the sleep time (value is fixed to 48 hours of inactivity).
  3441. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  3442. space_secrets (`list[dict[str, str]]`, *optional*):
  3443. A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
  3444. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  3445. space_variables (`list[dict[str, str]]`, *optional*):
  3446. A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
  3447. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
  3448. Returns:
  3449. [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
  3450. attributes like `endpoint`, `repo_type` and `repo_id`.
  3451. """
  3452. organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id)
  3453. path = f"{self.endpoint}/api/repos/create"
  3454. if repo_type not in constants.REPO_TYPES:
  3455. raise ValueError("Invalid repo type")
  3456. json: dict[str, Any] = {"name": name, "organization": organization}
  3457. if private is not None:
  3458. json["private"] = private
  3459. if repo_type is not None:
  3460. json["type"] = repo_type
  3461. if repo_type == "space":
  3462. if space_sdk is None:
  3463. raise ValueError(
  3464. "No space_sdk provided. `create_repo` expects space_sdk to be one"
  3465. f" of {constants.SPACES_SDK_TYPES} when repo_type is 'space'`"
  3466. )
  3467. if space_sdk not in constants.SPACES_SDK_TYPES:
  3468. raise ValueError(f"Invalid space_sdk. Please choose one of {constants.SPACES_SDK_TYPES}.")
  3469. json["sdk"] = space_sdk
  3470. if space_sdk is not None and repo_type != "space":
  3471. warnings.warn("Ignoring provided space_sdk because repo_type is not 'space'.")
  3472. function_args = [
  3473. "space_hardware",
  3474. "space_storage",
  3475. "space_sleep_time",
  3476. "space_secrets",
  3477. "space_variables",
  3478. ]
  3479. json_keys = ["hardware", "storageTier", "sleepTimeSeconds", "secrets", "variables"]
  3480. values = [space_hardware, space_storage, space_sleep_time, space_secrets, space_variables]
  3481. if repo_type == "space":
  3482. json.update({k: v for k, v in zip(json_keys, values) if v is not None})
  3483. else:
  3484. provided_space_args = [key for key, value in zip(function_args, values) if value is not None]
  3485. if provided_space_args:
  3486. warnings.warn(f"Ignoring provided {', '.join(provided_space_args)} because repo_type is not 'space'.")
  3487. if resource_group_id is not None:
  3488. json["resourceGroupId"] = resource_group_id
  3489. headers = self._build_hf_headers(token=token)
  3490. while True:
  3491. r = get_session().post(path, headers=headers, json=json)
  3492. if r.status_code == 409 and "Cannot create repo: another conflicting operation is in progress" in r.text:
  3493. # Since https://github.com/huggingface/moon-landing/pull/7272 (private repo), it is not possible to
  3494. # concurrently create repos on the Hub for a same user. This is rarely an issue, except when running
  3495. # tests. To avoid any inconvenience, we retry to create the repo for this specific error.
  3496. # NOTE: This could have being fixed directly in the tests but adding it here should fixed CIs for all
  3497. # dependent libraries.
  3498. # NOTE: If a fix is implemented server-side, we should be able to remove this retry mechanism.
  3499. logger.debug("Create repo failed due to a concurrency issue. Retrying...")
  3500. continue
  3501. break
  3502. try:
  3503. hf_raise_for_status(r)
  3504. except HfHubHTTPError as err:
  3505. if exist_ok and err.response.status_code == 409:
  3506. # Repo already exists and `exist_ok=True`
  3507. pass
  3508. elif exist_ok and err.response.status_code == 403:
  3509. # No write permission on the namespace but repo might already exist
  3510. try:
  3511. self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token)
  3512. if repo_type is None or repo_type == constants.REPO_TYPE_MODEL:
  3513. return RepoUrl(f"{self.endpoint}/{repo_id}")
  3514. return RepoUrl(f"{self.endpoint}/{constants.REPO_TYPES_URL_PREFIXES[repo_type]}{repo_id}")
  3515. except HfHubHTTPError:
  3516. raise err
  3517. else:
  3518. raise
  3519. d = r.json()
  3520. return RepoUrl(d["url"], endpoint=self.endpoint)
  3521. @validate_hf_hub_args
  3522. def delete_repo(
  3523. self,
  3524. repo_id: str,
  3525. *,
  3526. token: Union[str, bool, None] = None,
  3527. repo_type: Optional[str] = None,
  3528. missing_ok: bool = False,
  3529. ) -> None:
  3530. """
  3531. Delete a repo from the HuggingFace Hub. CAUTION: this is irreversible.
  3532. Args:
  3533. repo_id (`str`):
  3534. A namespace (user or an organization) and a repo name separated
  3535. by a `/`.
  3536. token (`bool` or `str`, *optional*):
  3537. A valid user access token (string). Defaults to the locally saved
  3538. token, which is the recommended method for authentication (see
  3539. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3540. To disable authentication, pass `False`.
  3541. repo_type (`str`, *optional*):
  3542. Set to `"dataset"` or `"space"` if uploading to a dataset or
  3543. space, `None` or `"model"` if uploading to a model.
  3544. missing_ok (`bool`, *optional*, defaults to `False`):
  3545. If `True`, do not raise an error if repo does not exist.
  3546. Raises:
  3547. [`~utils.RepositoryNotFoundError`]
  3548. If the repository to delete from cannot be found and `missing_ok` is set to False (default).
  3549. """
  3550. organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id)
  3551. path = f"{self.endpoint}/api/repos/delete"
  3552. if repo_type not in constants.REPO_TYPES:
  3553. raise ValueError("Invalid repo type")
  3554. json = {"name": name, "organization": organization}
  3555. if repo_type is not None:
  3556. json["type"] = repo_type
  3557. headers = self._build_hf_headers(token=token)
  3558. r = get_session().request("DELETE", path, headers=headers, json=json)
  3559. try:
  3560. hf_raise_for_status(r)
  3561. except RepositoryNotFoundError:
  3562. if not missing_ok:
  3563. raise
  3564. @validate_hf_hub_args
  3565. def update_repo_settings(
  3566. self,
  3567. repo_id: str,
  3568. *,
  3569. gated: Optional[Literal["auto", "manual", False]] = None,
  3570. private: Optional[bool] = None,
  3571. token: Union[str, bool, None] = None,
  3572. repo_type: Optional[str] = None,
  3573. ) -> None:
  3574. """
  3575. Update the settings of a repository, including gated access and visibility.
  3576. To give more control over how repos are used, the Hub allows repo authors to enable
  3577. access requests for their repos, and also to set the visibility of the repo to private.
  3578. Args:
  3579. repo_id (`str`):
  3580. A namespace (user or an organization) and a repo name separated by a /.
  3581. gated (`Literal["auto", "manual", False]`, *optional*):
  3582. The gated status for the repository. If set to `None` (default), the `gated` setting of the repository won't be updated.
  3583. * "auto": The repository is gated, and access requests are automatically approved or denied based on predefined criteria.
  3584. * "manual": The repository is gated, and access requests require manual approval.
  3585. * False : The repository is not gated, and anyone can access it.
  3586. private (`bool`, *optional*):
  3587. Whether the repository should be private.
  3588. token (`Union[str, bool, None]`, *optional*):
  3589. A valid user access token (string). Defaults to the locally saved token,
  3590. which is the recommended method for authentication (see
  3591. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3592. To disable authentication, pass False.
  3593. repo_type (`str`, *optional*):
  3594. The type of the repository to update settings from (`"model"`, `"dataset"` or `"space"`).
  3595. Defaults to `"model"`.
  3596. Raises:
  3597. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  3598. If gated is not one of "auto", "manual", or False.
  3599. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  3600. If repo_type is not one of the values in constants.REPO_TYPES.
  3601. [`~utils.HfHubHTTPError`]:
  3602. If the request to the Hugging Face Hub API fails.
  3603. [`~utils.RepositoryNotFoundError`]
  3604. If the repository to download from cannot be found. This may be because it doesn't exist,
  3605. or because it is set to `private` and you do not have access.
  3606. """
  3607. if repo_type not in constants.REPO_TYPES:
  3608. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  3609. if repo_type is None:
  3610. repo_type = constants.REPO_TYPE_MODEL # default repo type
  3611. # Prepare the JSON payload for the PUT request
  3612. payload: dict = {}
  3613. if gated is not None:
  3614. if gated not in ["auto", "manual", False]:
  3615. raise ValueError(f"Invalid gated status, must be one of 'auto', 'manual', or False. Got '{gated}'.")
  3616. payload["gated"] = gated
  3617. if private is not None:
  3618. payload["private"] = private
  3619. if len(payload) == 0:
  3620. raise ValueError("At least one setting must be updated.")
  3621. # Build headers
  3622. headers = self._build_hf_headers(token=token)
  3623. r = get_session().put(
  3624. url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/settings",
  3625. headers=headers,
  3626. json=payload,
  3627. )
  3628. hf_raise_for_status(r)
  3629. def move_repo(
  3630. self,
  3631. from_id: str,
  3632. to_id: str,
  3633. *,
  3634. repo_type: Optional[str] = None,
  3635. token: Union[str, bool, None] = None,
  3636. ):
  3637. """
  3638. Moving a repository from namespace1/repo_name1 to namespace2/repo_name2
  3639. Note there are certain limitations. For more information about moving
  3640. repositories, please see
  3641. https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.
  3642. Args:
  3643. from_id (`str`):
  3644. A namespace (user or an organization) and a repo name separated
  3645. by a `/`. Original repository identifier.
  3646. to_id (`str`):
  3647. A namespace (user or an organization) and a repo name separated
  3648. by a `/`. Final repository identifier.
  3649. repo_type (`str`, *optional*):
  3650. Set to `"dataset"` or `"space"` if uploading to a dataset or
  3651. space, `None` or `"model"` if uploading to a model. Default is
  3652. `None`.
  3653. token (`bool` or `str`, *optional*):
  3654. A valid user access token (string). Defaults to the locally saved
  3655. token, which is the recommended method for authentication (see
  3656. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3657. To disable authentication, pass `False`.
  3658. > [!TIP]
  3659. > Raises the following errors:
  3660. >
  3661. > - [`~utils.RepositoryNotFoundError`]
  3662. > If the repository to download from cannot be found. This may be because it doesn't exist,
  3663. > or because it is set to `private` and you do not have access.
  3664. """
  3665. if len(from_id.split("/")) != 2:
  3666. raise ValueError(f"Invalid repo_id: {from_id}. It should have a namespace (:namespace:/:repo_name:)")
  3667. if len(to_id.split("/")) != 2:
  3668. raise ValueError(f"Invalid repo_id: {to_id}. It should have a namespace (:namespace:/:repo_name:)")
  3669. if repo_type is None:
  3670. repo_type = constants.REPO_TYPE_MODEL # Hub won't accept `None`.
  3671. json = {"fromRepo": from_id, "toRepo": to_id, "type": repo_type}
  3672. path = f"{self.endpoint}/api/repos/move"
  3673. headers = self._build_hf_headers(token=token)
  3674. r = get_session().post(path, headers=headers, json=json)
  3675. try:
  3676. hf_raise_for_status(r)
  3677. except HfHubHTTPError as e:
  3678. e.append_to_message(
  3679. "\nFor additional documentation please see"
  3680. " https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo."
  3681. )
  3682. raise
  3683. @overload
  3684. def create_commit( # type: ignore
  3685. self,
  3686. repo_id: str,
  3687. operations: Iterable[CommitOperation],
  3688. *,
  3689. commit_message: str,
  3690. commit_description: Optional[str] = None,
  3691. token: Union[str, bool, None] = None,
  3692. repo_type: Optional[str] = None,
  3693. revision: Optional[str] = None,
  3694. create_pr: Optional[bool] = None,
  3695. num_threads: int = 5,
  3696. parent_commit: Optional[str] = None,
  3697. run_as_future: Literal[False] = ...,
  3698. ) -> CommitInfo: ...
  3699. @overload
  3700. def create_commit(
  3701. self,
  3702. repo_id: str,
  3703. operations: Iterable[CommitOperation],
  3704. *,
  3705. commit_message: str,
  3706. commit_description: Optional[str] = None,
  3707. token: Union[str, bool, None] = None,
  3708. repo_type: Optional[str] = None,
  3709. revision: Optional[str] = None,
  3710. create_pr: Optional[bool] = None,
  3711. num_threads: int = 5,
  3712. parent_commit: Optional[str] = None,
  3713. run_as_future: Literal[True] = ...,
  3714. ) -> Future[CommitInfo]: ...
  3715. @validate_hf_hub_args
  3716. @future_compatible
  3717. def create_commit(
  3718. self,
  3719. repo_id: str,
  3720. operations: Iterable[CommitOperation],
  3721. *,
  3722. commit_message: str,
  3723. commit_description: Optional[str] = None,
  3724. token: Union[str, bool, None] = None,
  3725. repo_type: Optional[str] = None,
  3726. revision: Optional[str] = None,
  3727. create_pr: Optional[bool] = None,
  3728. num_threads: int = 5,
  3729. parent_commit: Optional[str] = None,
  3730. run_as_future: bool = False,
  3731. ) -> Union[CommitInfo, Future[CommitInfo]]:
  3732. """
  3733. Creates a commit in the given repo, deleting & uploading files as needed.
  3734. > [!WARNING]
  3735. > The input list of `CommitOperation` will be mutated during the commit process. Do not reuse the same objects
  3736. > for multiple commits.
  3737. > [!WARNING]
  3738. > `create_commit` assumes that the repo already exists on the Hub. If you get a
  3739. > Client error 404, please make sure you are authenticated and that `repo_id` and
  3740. > `repo_type` are set correctly. If repo does not exist, create it first using
  3741. > [`~hf_api.create_repo`].
  3742. > [!WARNING]
  3743. > `create_commit` is limited to 25k LFS files and a 1GB payload for regular files.
  3744. Args:
  3745. repo_id (`str`):
  3746. The repository in which the commit will be created, for example:
  3747. `"username/custom_transformers"`
  3748. operations (`Iterable` of [`~hf_api.CommitOperation`]):
  3749. An iterable of operations to include in the commit, either:
  3750. - [`~hf_api.CommitOperationAdd`] to upload a file
  3751. - [`~hf_api.CommitOperationDelete`] to delete a file
  3752. - [`~hf_api.CommitOperationCopy`] to copy a file
  3753. Operation objects will be mutated to include information relative to the upload. Do not reuse the
  3754. same objects for multiple commits.
  3755. commit_message (`str`):
  3756. The summary (first line) of the commit that will be created.
  3757. commit_description (`str`, *optional*):
  3758. The description of the commit that will be created
  3759. token (`bool` or `str`, *optional*):
  3760. A valid user access token (string). Defaults to the locally saved
  3761. token, which is the recommended method for authentication (see
  3762. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3763. To disable authentication, pass `False`.
  3764. repo_type (`str`, *optional*):
  3765. Set to `"dataset"` or `"space"` if uploading to a dataset or
  3766. space, `None` or `"model"` if uploading to a model. Default is
  3767. `None`.
  3768. revision (`str`, *optional*):
  3769. The git revision to commit from. Defaults to the head of the `"main"` branch.
  3770. create_pr (`boolean`, *optional*):
  3771. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  3772. If `revision` is not set, PR is opened against the `"main"` branch. If
  3773. `revision` is set and is a branch, PR is opened against this branch. If
  3774. `revision` is set and is not a branch name (example: a commit oid), an
  3775. `RevisionNotFoundError` is returned by the server.
  3776. num_threads (`int`, *optional*):
  3777. Number of concurrent threads for uploading files. Defaults to 5.
  3778. Setting it to 2 means at most 2 files will be uploaded concurrently.
  3779. parent_commit (`str`, *optional*):
  3780. The OID / SHA of the parent commit, as a hexadecimal string.
  3781. Shorthands (7 first characters) are also supported. If specified and `create_pr` is `False`,
  3782. the commit will fail if `revision` does not point to `parent_commit`. If specified and `create_pr`
  3783. is `True`, the pull request will be created from `parent_commit`. Specifying `parent_commit`
  3784. ensures the repo has not changed before committing the changes, and can be especially useful
  3785. if the repo is updated / committed to concurrently.
  3786. run_as_future (`bool`, *optional*):
  3787. Whether or not to run this method in the background. Background jobs are run sequentially without
  3788. blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
  3789. object. Defaults to `False`.
  3790. Returns:
  3791. [`CommitInfo`] or `Future`:
  3792. Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
  3793. url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
  3794. contain the result when executed.
  3795. Raises:
  3796. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  3797. If commit message is empty.
  3798. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  3799. If parent commit is not a valid commit OID.
  3800. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  3801. If a README.md file with an invalid metadata section is committed. In this case, the commit will fail
  3802. early, before trying to upload any file.
  3803. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  3804. If `create_pr` is `True` and revision is neither `None` nor `"main"`.
  3805. [`~utils.RepositoryNotFoundError`]:
  3806. If repository is not found (error 404): wrong repo_id/repo_type, private
  3807. but not authenticated or repo does not exist.
  3808. """
  3809. if parent_commit is not None and not constants.REGEX_COMMIT_OID.fullmatch(parent_commit):
  3810. raise ValueError(
  3811. f"`parent_commit` is not a valid commit OID. It must match the following regex: {constants.REGEX_COMMIT_OID}"
  3812. )
  3813. if commit_message is None or len(commit_message) == 0:
  3814. raise ValueError("`commit_message` can't be empty, please pass a value.")
  3815. commit_description = commit_description if commit_description is not None else ""
  3816. repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL
  3817. if repo_type not in constants.REPO_TYPES:
  3818. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  3819. unquoted_revision = revision or constants.DEFAULT_REVISION
  3820. revision = quote(unquoted_revision, safe="")
  3821. create_pr = create_pr if create_pr is not None else False
  3822. headers = self._build_hf_headers(token=token)
  3823. operations = list(operations)
  3824. additions = [op for op in operations if isinstance(op, CommitOperationAdd)]
  3825. copies = [op for op in operations if isinstance(op, CommitOperationCopy)]
  3826. nb_additions = len(additions)
  3827. nb_copies = len(copies)
  3828. nb_deletions = len(operations) - nb_additions - nb_copies
  3829. for addition in additions:
  3830. if addition._is_committed:
  3831. raise ValueError(
  3832. f"CommitOperationAdd {addition} has already being committed and cannot be reused. Please create a"
  3833. " new CommitOperationAdd object if you want to create a new commit."
  3834. )
  3835. if repo_type != "dataset":
  3836. for addition in additions:
  3837. if addition.path_in_repo.endswith((".arrow", ".parquet")):
  3838. warnings.warn(
  3839. f"It seems that you are about to commit a data file ({addition.path_in_repo}) to a {repo_type}"
  3840. " repository. You are sure this is intended? If you are trying to upload a dataset, please"
  3841. " set `repo_type='dataset'` or `--repo-type=dataset` in a CLI."
  3842. )
  3843. logger.debug(
  3844. f"About to commit to the hub: {len(additions)} addition(s), {len(copies)} copie(s) and"
  3845. f" {nb_deletions} deletion(s)."
  3846. )
  3847. # If updating a README.md file, make sure the metadata format is valid
  3848. # It's better to fail early than to fail after all the files have been uploaded.
  3849. for addition in additions:
  3850. if addition.path_in_repo == "README.md":
  3851. with addition.as_file() as file:
  3852. content = file.read().decode()
  3853. self._validate_yaml(content, repo_type=repo_type, token=token)
  3854. # Skip other additions after `README.md` has been processed
  3855. break
  3856. # If updating twice the same file or update then delete a file in a single commit
  3857. _warn_on_overwriting_operations(operations)
  3858. self.preupload_lfs_files(
  3859. repo_id=repo_id,
  3860. additions=additions,
  3861. token=token,
  3862. repo_type=repo_type,
  3863. revision=unquoted_revision, # first-class methods take unquoted revision
  3864. create_pr=create_pr,
  3865. num_threads=num_threads,
  3866. free_memory=False, # do not remove `CommitOperationAdd.path_or_fileobj` on LFS files for "normal" users
  3867. )
  3868. files_to_copy = _fetch_files_to_copy(
  3869. copies=copies,
  3870. repo_type=repo_type,
  3871. repo_id=repo_id,
  3872. headers=headers,
  3873. revision=unquoted_revision,
  3874. endpoint=self.endpoint,
  3875. )
  3876. # Remove no-op operations (files that have not changed)
  3877. operations_without_no_op = []
  3878. for operation in operations:
  3879. if (
  3880. isinstance(operation, CommitOperationAdd)
  3881. and operation._remote_oid is not None
  3882. and operation._remote_oid == operation._local_oid
  3883. ):
  3884. # File already exists on the Hub and has not changed: we can skip it.
  3885. logger.debug(f"Skipping upload for '{operation.path_in_repo}' as the file has not changed.")
  3886. continue
  3887. if (
  3888. isinstance(operation, CommitOperationCopy)
  3889. and operation._dest_oid is not None
  3890. and operation._dest_oid == operation._src_oid
  3891. ):
  3892. # Source and destination files are identical - skip
  3893. logger.debug(
  3894. f"Skipping copy for '{operation.src_path_in_repo}' -> '{operation.path_in_repo}' as the content of the source file is the same as the destination file."
  3895. )
  3896. continue
  3897. operations_without_no_op.append(operation)
  3898. if len(operations) != len(operations_without_no_op):
  3899. logger.info(
  3900. f"Removing {len(operations) - len(operations_without_no_op)} file(s) from commit that have not changed."
  3901. )
  3902. # Return early if empty commit
  3903. if len(operations_without_no_op) == 0:
  3904. logger.warning("No files have been modified since last commit. Skipping to prevent empty commit.")
  3905. # Get latest commit info
  3906. try:
  3907. info = self.repo_info(repo_id=repo_id, repo_type=repo_type, revision=unquoted_revision, token=token)
  3908. except RepositoryNotFoundError as e:
  3909. e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE)
  3910. raise
  3911. # Return commit info based on latest commit
  3912. url_prefix = self.endpoint
  3913. if repo_type is not None and repo_type != constants.REPO_TYPE_MODEL:
  3914. url_prefix = f"{url_prefix}/{repo_type}s"
  3915. return CommitInfo(
  3916. commit_url=f"{url_prefix}/{repo_id}/commit/{info.sha}",
  3917. commit_message=commit_message,
  3918. commit_description=commit_description,
  3919. oid=info.sha, # type: ignore[arg-type]
  3920. _endpoint=self.endpoint,
  3921. )
  3922. commit_payload = _prepare_commit_payload(
  3923. operations=operations,
  3924. files_to_copy=files_to_copy,
  3925. commit_message=commit_message,
  3926. commit_description=commit_description,
  3927. parent_commit=parent_commit,
  3928. )
  3929. commit_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/commit/{revision}"
  3930. def _payload_as_ndjson() -> Iterable[bytes]:
  3931. for item in commit_payload:
  3932. yield json.dumps(item).encode()
  3933. yield b"\n"
  3934. headers = {
  3935. # See https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
  3936. "Content-Type": "application/x-ndjson",
  3937. **headers,
  3938. }
  3939. data = b"".join(_payload_as_ndjson())
  3940. params = {"create_pr": "1"} if create_pr else None
  3941. try:
  3942. commit_resp = get_session().post(url=commit_url, headers=headers, content=data, params=params)
  3943. hf_raise_for_status(commit_resp, endpoint_name="commit")
  3944. except RepositoryNotFoundError as e:
  3945. e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE)
  3946. raise
  3947. except RemoteEntryNotFoundError as e:
  3948. if nb_deletions > 0 and "A file with this name doesn't exist" in str(e):
  3949. e.append_to_message(
  3950. "\nMake sure to differentiate file and folder paths in delete"
  3951. " operations with a trailing '/' or using `is_folder=True/False`."
  3952. )
  3953. raise
  3954. # Mark additions as committed (cannot be reused in another commit)
  3955. for addition in additions:
  3956. addition._is_committed = True
  3957. commit_data = commit_resp.json()
  3958. return CommitInfo(
  3959. commit_url=commit_data["commitUrl"],
  3960. commit_message=commit_message,
  3961. commit_description=commit_description,
  3962. oid=commit_data["commitOid"],
  3963. pr_url=commit_data["pullRequestUrl"] if create_pr else None,
  3964. _endpoint=self.endpoint,
  3965. )
  3966. def preupload_lfs_files(
  3967. self,
  3968. repo_id: str,
  3969. additions: Iterable[CommitOperationAdd],
  3970. *,
  3971. token: Union[str, bool, None] = None,
  3972. repo_type: Optional[str] = None,
  3973. revision: Optional[str] = None,
  3974. create_pr: Optional[bool] = None,
  3975. num_threads: int = 5,
  3976. free_memory: bool = True,
  3977. gitignore_content: Optional[str] = None,
  3978. ):
  3979. """Pre-upload LFS files to S3 in preparation on a future commit.
  3980. This method is useful if you are generating the files to upload on-the-fly and you don't want to store them
  3981. in memory before uploading them all at once.
  3982. > [!WARNING]
  3983. > This is a power-user method. You shouldn't need to call it directly to make a normal commit.
  3984. > Use [`create_commit`] directly instead.
  3985. > [!WARNING]
  3986. > Commit operations will be mutated during the process. In particular, the attached `path_or_fileobj` will be
  3987. > removed after the upload to save memory (and replaced by an empty `bytes` object). Do not reuse the same
  3988. > objects except to pass them to [`create_commit`]. If you don't want to remove the attached content from the
  3989. > commit operation object, pass `free_memory=False`.
  3990. Args:
  3991. repo_id (`str`):
  3992. The repository in which you will commit the files, for example: `"username/custom_transformers"`.
  3993. operations (`Iterable` of [`CommitOperationAdd`]):
  3994. The list of files to upload. Warning: the objects in this list will be mutated to include information
  3995. relative to the upload. Do not reuse the same objects for multiple commits.
  3996. token (`bool` or `str`, *optional*):
  3997. A valid user access token (string). Defaults to the locally saved
  3998. token, which is the recommended method for authentication (see
  3999. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4000. To disable authentication, pass `False`.
  4001. repo_type (`str`, *optional*):
  4002. The type of repository to upload to (e.g. `"model"` -default-, `"dataset"` or `"space"`).
  4003. revision (`str`, *optional*):
  4004. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4005. create_pr (`boolean`, *optional*):
  4006. Whether or not you plan to create a Pull Request with that commit. Defaults to `False`.
  4007. num_threads (`int`, *optional*):
  4008. Number of concurrent threads for uploading files. Defaults to 5.
  4009. Setting it to 2 means at most 2 files will be uploaded concurrently.
  4010. gitignore_content (`str`, *optional*):
  4011. The content of the `.gitignore` file to know which files should be ignored. The order of priority
  4012. is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
  4013. in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
  4014. (if any).
  4015. Example:
  4016. ```py
  4017. >>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo
  4018. >>> repo_id = create_repo("test_preupload").repo_id
  4019. # Generate and preupload LFS files one by one
  4020. >>> operations = [] # List of all `CommitOperationAdd` objects that will be generated
  4021. >>> for i in range(5):
  4022. ... content = ... # generate binary content
  4023. ... addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content)
  4024. ... preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory
  4025. ... operations.append(addition)
  4026. # Create commit
  4027. >>> create_commit(repo_id, operations=operations, commit_message="Commit all shards")
  4028. ```
  4029. """
  4030. repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL
  4031. if repo_type not in constants.REPO_TYPES:
  4032. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  4033. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  4034. create_pr = create_pr if create_pr is not None else False
  4035. headers = self._build_hf_headers(token=token)
  4036. # Check if a `gitignore` file is being committed to the Hub.
  4037. additions = list(additions)
  4038. if gitignore_content is None:
  4039. for addition in additions:
  4040. if addition.path_in_repo == ".gitignore":
  4041. with addition.as_file() as f:
  4042. gitignore_content = f.read().decode()
  4043. break
  4044. # Filter out already uploaded files
  4045. new_additions = [addition for addition in additions if not addition._is_uploaded]
  4046. # Check which new files are LFS
  4047. # For some items, we might have already fetched the upload mode (in case of upload_large_folder)
  4048. additions_no_upload_mode = [addition for addition in new_additions if addition._upload_mode is None]
  4049. if len(additions_no_upload_mode) > 0:
  4050. try:
  4051. _fetch_upload_modes(
  4052. additions=additions_no_upload_mode,
  4053. repo_type=repo_type,
  4054. repo_id=repo_id,
  4055. headers=headers,
  4056. revision=revision,
  4057. endpoint=self.endpoint,
  4058. create_pr=create_pr or False,
  4059. gitignore_content=gitignore_content,
  4060. )
  4061. except RepositoryNotFoundError as e:
  4062. e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE)
  4063. raise
  4064. # Filter out regular files
  4065. new_lfs_additions = [addition for addition in new_additions if addition._upload_mode == "lfs"]
  4066. # Filter out files listed in .gitignore
  4067. new_lfs_additions_to_upload = []
  4068. for addition in new_lfs_additions:
  4069. if addition._should_ignore:
  4070. logger.debug(f"Skipping upload for LFS file '{addition.path_in_repo}' (ignored by gitignore file).")
  4071. else:
  4072. new_lfs_additions_to_upload.append(addition)
  4073. if len(new_lfs_additions) != len(new_lfs_additions_to_upload):
  4074. logger.info(
  4075. f"Skipped upload for {len(new_lfs_additions) - len(new_lfs_additions_to_upload)} LFS file(s) "
  4076. "(ignored by gitignore file)."
  4077. )
  4078. # If no LFS files remain to upload, keep previous behavior and log explicitly
  4079. if len(new_lfs_additions_to_upload) == 0:
  4080. logger.debug("No LFS files to upload.")
  4081. return
  4082. # Prepare upload parameters
  4083. upload_kwargs = {
  4084. "additions": new_lfs_additions_to_upload,
  4085. "repo_type": repo_type,
  4086. "repo_id": repo_id,
  4087. "headers": headers,
  4088. "endpoint": self.endpoint,
  4089. # If `create_pr`, we don't want to check user permission on the revision as users with read permission
  4090. # should still be able to create PRs even if they don't have write permission on the target branch of the
  4091. # PR (i.e. `revision`).
  4092. "revision": revision if not create_pr else None,
  4093. }
  4094. _upload_files(**upload_kwargs, num_threads=num_threads, create_pr=create_pr) # type: ignore [arg-type]
  4095. for addition in new_lfs_additions_to_upload:
  4096. addition._is_uploaded = True
  4097. if free_memory:
  4098. addition.path_or_fileobj = b""
  4099. @overload
  4100. def upload_file( # type: ignore
  4101. self,
  4102. *,
  4103. path_or_fileobj: Union[str, Path, bytes, BinaryIO],
  4104. path_in_repo: str,
  4105. repo_id: str,
  4106. token: Union[str, bool, None] = None,
  4107. repo_type: Optional[str] = None,
  4108. revision: Optional[str] = None,
  4109. commit_message: Optional[str] = None,
  4110. commit_description: Optional[str] = None,
  4111. create_pr: Optional[bool] = None,
  4112. parent_commit: Optional[str] = None,
  4113. run_as_future: Literal[False] = ...,
  4114. ) -> CommitInfo: ...
  4115. @overload
  4116. def upload_file(
  4117. self,
  4118. *,
  4119. path_or_fileobj: Union[str, Path, bytes, BinaryIO],
  4120. path_in_repo: str,
  4121. repo_id: str,
  4122. token: Union[str, bool, None] = None,
  4123. repo_type: Optional[str] = None,
  4124. revision: Optional[str] = None,
  4125. commit_message: Optional[str] = None,
  4126. commit_description: Optional[str] = None,
  4127. create_pr: Optional[bool] = None,
  4128. parent_commit: Optional[str] = None,
  4129. run_as_future: Literal[True] = ...,
  4130. ) -> Future[CommitInfo]: ...
  4131. @validate_hf_hub_args
  4132. @future_compatible
  4133. def upload_file(
  4134. self,
  4135. *,
  4136. path_or_fileobj: Union[str, Path, bytes, BinaryIO],
  4137. path_in_repo: str,
  4138. repo_id: str,
  4139. token: Union[str, bool, None] = None,
  4140. repo_type: Optional[str] = None,
  4141. revision: Optional[str] = None,
  4142. commit_message: Optional[str] = None,
  4143. commit_description: Optional[str] = None,
  4144. create_pr: Optional[bool] = None,
  4145. parent_commit: Optional[str] = None,
  4146. run_as_future: bool = False,
  4147. ) -> Union[CommitInfo, Future[CommitInfo]]:
  4148. """
  4149. Upload a local file (up to 50 GB) to the given repo. The upload is done
  4150. through a HTTP post request, and doesn't require git or git-lfs to be
  4151. installed.
  4152. Args:
  4153. path_or_fileobj (`str`, `Path`, `bytes`, or `IO`):
  4154. Path to a file on the local machine or binary data stream /
  4155. fileobj / buffer.
  4156. path_in_repo (`str`):
  4157. Relative filepath in the repo, for example:
  4158. `"checkpoints/1fec34a/weights.bin"`
  4159. repo_id (`str`):
  4160. The repository to which the file will be uploaded, for example:
  4161. `"username/custom_transformers"`
  4162. token (`bool` or `str`, *optional*):
  4163. A valid user access token (string). Defaults to the locally saved
  4164. token, which is the recommended method for authentication (see
  4165. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4166. To disable authentication, pass `False`.
  4167. repo_type (`str`, *optional*):
  4168. Set to `"dataset"` or `"space"` if uploading to a dataset or
  4169. space, `None` or `"model"` if uploading to a model. Default is
  4170. `None`.
  4171. revision (`str`, *optional*):
  4172. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4173. commit_message (`str`, *optional*):
  4174. The summary / title / first line of the generated commit
  4175. commit_description (`str` *optional*)
  4176. The description of the generated commit
  4177. create_pr (`boolean`, *optional*):
  4178. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  4179. If `revision` is not set, PR is opened against the `"main"` branch. If
  4180. `revision` is set and is a branch, PR is opened against this branch. If
  4181. `revision` is set and is not a branch name (example: a commit oid), an
  4182. `RevisionNotFoundError` is returned by the server.
  4183. parent_commit (`str`, *optional*):
  4184. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  4185. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  4186. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  4187. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  4188. especially useful if the repo is updated / committed to concurrently.
  4189. run_as_future (`bool`, *optional*):
  4190. Whether or not to run this method in the background. Background jobs are run sequentially without
  4191. blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
  4192. object. Defaults to `False`.
  4193. Returns:
  4194. [`CommitInfo`] or `Future`:
  4195. Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
  4196. url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
  4197. contain the result when executed.
  4198. > [!TIP]
  4199. > Raises the following errors:
  4200. >
  4201. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  4202. > if the HuggingFace API returned an error
  4203. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4204. > if some parameter value is invalid
  4205. > - [`~utils.RepositoryNotFoundError`]
  4206. > If the repository to download from cannot be found. This may be because it doesn't exist,
  4207. > or because it is set to `private` and you do not have access.
  4208. > - [`~utils.RevisionNotFoundError`]
  4209. > If the revision to download from cannot be found.
  4210. > [!WARNING]
  4211. > `upload_file` assumes that the repo already exists on the Hub. If you get a
  4212. > Client error 404, please make sure you are authenticated and that `repo_id` and
  4213. > `repo_type` are set correctly. If repo does not exist, create it first using
  4214. > [`~hf_api.create_repo`].
  4215. Example:
  4216. ```python
  4217. >>> from huggingface_hub import upload_file
  4218. >>> with open("./local/filepath", "rb") as fobj:
  4219. ... upload_file(
  4220. ... path_or_fileobj=fileobj,
  4221. ... path_in_repo="remote/file/path.h5",
  4222. ... repo_id="username/my-dataset",
  4223. ... repo_type="dataset",
  4224. ... token="my_token",
  4225. ... )
  4226. >>> upload_file(
  4227. ... path_or_fileobj=".\\\\local\\\\file\\\\path",
  4228. ... path_in_repo="remote/file/path.h5",
  4229. ... repo_id="username/my-model",
  4230. ... token="my_token",
  4231. ... )
  4232. >>> upload_file(
  4233. ... path_or_fileobj=".\\\\local\\\\file\\\\path",
  4234. ... path_in_repo="remote/file/path.h5",
  4235. ... repo_id="username/my-model",
  4236. ... token="my_token",
  4237. ... create_pr=True,
  4238. ... )
  4239. ```
  4240. """
  4241. if repo_type not in constants.REPO_TYPES:
  4242. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  4243. commit_message = (
  4244. commit_message if commit_message is not None else f"Upload {path_in_repo} with huggingface_hub"
  4245. )
  4246. operation = CommitOperationAdd(
  4247. path_or_fileobj=path_or_fileobj,
  4248. path_in_repo=path_in_repo,
  4249. )
  4250. return self.create_commit(
  4251. repo_id=repo_id,
  4252. repo_type=repo_type,
  4253. operations=[operation],
  4254. commit_message=commit_message,
  4255. commit_description=commit_description,
  4256. token=token,
  4257. revision=revision,
  4258. create_pr=create_pr,
  4259. parent_commit=parent_commit,
  4260. )
  4261. @overload
  4262. def upload_folder( # type: ignore
  4263. self,
  4264. *,
  4265. repo_id: str,
  4266. folder_path: Union[str, Path],
  4267. path_in_repo: Optional[str] = None,
  4268. commit_message: Optional[str] = None,
  4269. commit_description: Optional[str] = None,
  4270. token: Union[str, bool, None] = None,
  4271. repo_type: Optional[str] = None,
  4272. revision: Optional[str] = None,
  4273. create_pr: Optional[bool] = None,
  4274. parent_commit: Optional[str] = None,
  4275. allow_patterns: Optional[Union[list[str], str]] = None,
  4276. ignore_patterns: Optional[Union[list[str], str]] = None,
  4277. delete_patterns: Optional[Union[list[str], str]] = None,
  4278. run_as_future: Literal[False] = ...,
  4279. ) -> CommitInfo: ...
  4280. @overload
  4281. def upload_folder( # type: ignore
  4282. self,
  4283. *,
  4284. repo_id: str,
  4285. folder_path: Union[str, Path],
  4286. path_in_repo: Optional[str] = None,
  4287. commit_message: Optional[str] = None,
  4288. commit_description: Optional[str] = None,
  4289. token: Union[str, bool, None] = None,
  4290. repo_type: Optional[str] = None,
  4291. revision: Optional[str] = None,
  4292. create_pr: Optional[bool] = None,
  4293. parent_commit: Optional[str] = None,
  4294. allow_patterns: Optional[Union[list[str], str]] = None,
  4295. ignore_patterns: Optional[Union[list[str], str]] = None,
  4296. delete_patterns: Optional[Union[list[str], str]] = None,
  4297. run_as_future: Literal[True] = ...,
  4298. ) -> Future[CommitInfo]: ...
  4299. @validate_hf_hub_args
  4300. @future_compatible
  4301. def upload_folder(
  4302. self,
  4303. *,
  4304. repo_id: str,
  4305. folder_path: Union[str, Path],
  4306. path_in_repo: Optional[str] = None,
  4307. commit_message: Optional[str] = None,
  4308. commit_description: Optional[str] = None,
  4309. token: Union[str, bool, None] = None,
  4310. repo_type: Optional[str] = None,
  4311. revision: Optional[str] = None,
  4312. create_pr: Optional[bool] = None,
  4313. parent_commit: Optional[str] = None,
  4314. allow_patterns: Optional[Union[list[str], str]] = None,
  4315. ignore_patterns: Optional[Union[list[str], str]] = None,
  4316. delete_patterns: Optional[Union[list[str], str]] = None,
  4317. run_as_future: bool = False,
  4318. ) -> Union[CommitInfo, Future[CommitInfo]]:
  4319. """
  4320. Upload a local folder to the given repo. The upload is done through a HTTP requests, and doesn't require git or
  4321. git-lfs to be installed.
  4322. The structure of the folder will be preserved. Files with the same name already present in the repository will
  4323. be overwritten. Others will be left untouched.
  4324. Use the `allow_patterns` and `ignore_patterns` arguments to specify which files to upload. These parameters
  4325. accept either a single pattern or a list of patterns. Patterns are Standard Wildcards (globbing patterns) as
  4326. documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). If both `allow_patterns` and
  4327. `ignore_patterns` are provided, both constraints apply. By default, all files from the folder are uploaded.
  4328. Use the `delete_patterns` argument to specify remote files you want to delete. Input type is the same as for
  4329. `allow_patterns` (see above). If `path_in_repo` is also provided, the patterns are matched against paths
  4330. relative to this folder. For example, `upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*")`
  4331. will delete any remote file under `./experiment/logs/`. Note that the `.gitattributes` file will not be deleted
  4332. even if it matches the patterns.
  4333. Any `.git/` folder present in any subdirectory will be ignored. However, please be aware that the `.gitignore`
  4334. file is not taken into account.
  4335. Uses `HfApi.create_commit` under the hood.
  4336. Args:
  4337. repo_id (`str`):
  4338. The repository to which the file will be uploaded, for example:
  4339. `"username/custom_transformers"`
  4340. folder_path (`str` or `Path`):
  4341. Path to the folder to upload on the local file system
  4342. path_in_repo (`str`, *optional*):
  4343. Relative path of the directory in the repo, for example:
  4344. `"checkpoints/1fec34a/results"`. Will default to the root folder of the repository.
  4345. token (`bool` or `str`, *optional*):
  4346. A valid user access token (string). Defaults to the locally saved
  4347. token, which is the recommended method for authentication (see
  4348. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4349. To disable authentication, pass `False`.
  4350. repo_type (`str`, *optional*):
  4351. Set to `"dataset"` or `"space"` if uploading to a dataset or
  4352. space, `None` or `"model"` if uploading to a model. Default is
  4353. `None`.
  4354. revision (`str`, *optional*):
  4355. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4356. commit_message (`str`, *optional*):
  4357. The summary / title / first line of the generated commit. Defaults to:
  4358. `f"Upload {path_in_repo} with huggingface_hub"`
  4359. commit_description (`str` *optional*):
  4360. The description of the generated commit
  4361. create_pr (`boolean`, *optional*):
  4362. Whether or not to create a Pull Request with that commit. Defaults to `False`. If `revision` is not
  4363. set, PR is opened against the `"main"` branch. If `revision` is set and is a branch, PR is opened
  4364. against this branch. If `revision` is set and is not a branch name (example: a commit oid), an
  4365. `RevisionNotFoundError` is returned by the server.
  4366. parent_commit (`str`, *optional*):
  4367. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  4368. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  4369. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  4370. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  4371. especially useful if the repo is updated / committed to concurrently.
  4372. allow_patterns (`list[str]` or `str`, *optional*):
  4373. If provided, only files matching at least one pattern are uploaded.
  4374. ignore_patterns (`list[str]` or `str`, *optional*):
  4375. If provided, files matching any of the patterns are not uploaded.
  4376. delete_patterns (`list[str]` or `str`, *optional*):
  4377. If provided, remote files matching any of the patterns will be deleted from the repo while committing
  4378. new files. This is useful if you don't know which files have already been uploaded.
  4379. Note: to avoid discrepancies the `.gitattributes` file is not deleted even if it matches the pattern.
  4380. run_as_future (`bool`, *optional*):
  4381. Whether or not to run this method in the background. Background jobs are run sequentially without
  4382. blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
  4383. object. Defaults to `False`.
  4384. Returns:
  4385. [`CommitInfo`] or `Future`:
  4386. Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
  4387. url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
  4388. contain the result when executed.
  4389. > [!TIP]
  4390. > Raises the following errors:
  4391. >
  4392. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  4393. > if the HuggingFace API returned an error
  4394. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4395. > if some parameter value is invalid
  4396. > [!WARNING]
  4397. > `upload_folder` assumes that the repo already exists on the Hub. If you get a Client error 404, please make
  4398. > sure you are authenticated and that `repo_id` and `repo_type` are set correctly. If repo does not exist, create
  4399. > it first using [`~hf_api.create_repo`].
  4400. > [!TIP]
  4401. > When dealing with a large folder (thousands of files or hundreds of GB), we recommend using [`~hf_api.upload_large_folder`] instead.
  4402. Example:
  4403. ```python
  4404. # Upload checkpoints folder except the log files
  4405. >>> upload_folder(
  4406. ... folder_path="local/checkpoints",
  4407. ... path_in_repo="remote/experiment/checkpoints",
  4408. ... repo_id="username/my-dataset",
  4409. ... repo_type="datasets",
  4410. ... token="my_token",
  4411. ... ignore_patterns="**/logs/*.txt",
  4412. ... )
  4413. # Upload checkpoints folder including logs while deleting existing logs from the repo
  4414. # Useful if you don't know exactly which log files have already being pushed
  4415. >>> upload_folder(
  4416. ... folder_path="local/checkpoints",
  4417. ... path_in_repo="remote/experiment/checkpoints",
  4418. ... repo_id="username/my-dataset",
  4419. ... repo_type="datasets",
  4420. ... token="my_token",
  4421. ... delete_patterns="**/logs/*.txt",
  4422. ... )
  4423. # Upload checkpoints folder while creating a PR
  4424. >>> upload_folder(
  4425. ... folder_path="local/checkpoints",
  4426. ... path_in_repo="remote/experiment/checkpoints",
  4427. ... repo_id="username/my-dataset",
  4428. ... repo_type="datasets",
  4429. ... token="my_token",
  4430. ... create_pr=True,
  4431. ... )
  4432. ```
  4433. """
  4434. if repo_type not in constants.REPO_TYPES:
  4435. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  4436. # By default, upload folder to the root directory in repo.
  4437. if path_in_repo is None:
  4438. path_in_repo = ""
  4439. # Do not upload .git folder
  4440. if ignore_patterns is None:
  4441. ignore_patterns = []
  4442. elif isinstance(ignore_patterns, str):
  4443. ignore_patterns = [ignore_patterns]
  4444. ignore_patterns += DEFAULT_IGNORE_PATTERNS
  4445. delete_operations = self._prepare_folder_deletions(
  4446. repo_id=repo_id,
  4447. repo_type=repo_type,
  4448. revision=constants.DEFAULT_REVISION if create_pr else revision,
  4449. token=token,
  4450. path_in_repo=path_in_repo,
  4451. delete_patterns=delete_patterns,
  4452. )
  4453. add_operations = self._prepare_upload_folder_additions(
  4454. folder_path,
  4455. path_in_repo,
  4456. allow_patterns=allow_patterns,
  4457. ignore_patterns=ignore_patterns,
  4458. token=token,
  4459. repo_type=repo_type,
  4460. )
  4461. # Optimize operations: if some files will be overwritten, we don't need to delete them first
  4462. if len(add_operations) > 0:
  4463. added_paths = set(op.path_in_repo for op in add_operations)
  4464. delete_operations = [
  4465. delete_op for delete_op in delete_operations if delete_op.path_in_repo not in added_paths
  4466. ]
  4467. commit_operations = delete_operations + add_operations
  4468. commit_message = commit_message or "Upload folder using huggingface_hub"
  4469. return self.create_commit(
  4470. repo_type=repo_type,
  4471. repo_id=repo_id,
  4472. operations=commit_operations,
  4473. commit_message=commit_message,
  4474. commit_description=commit_description,
  4475. token=token,
  4476. revision=revision,
  4477. create_pr=create_pr,
  4478. parent_commit=parent_commit,
  4479. )
  4480. @validate_hf_hub_args
  4481. def delete_file(
  4482. self,
  4483. path_in_repo: str,
  4484. repo_id: str,
  4485. *,
  4486. token: Union[str, bool, None] = None,
  4487. repo_type: Optional[str] = None,
  4488. revision: Optional[str] = None,
  4489. commit_message: Optional[str] = None,
  4490. commit_description: Optional[str] = None,
  4491. create_pr: Optional[bool] = None,
  4492. parent_commit: Optional[str] = None,
  4493. ) -> CommitInfo:
  4494. """
  4495. Deletes a file in the given repo.
  4496. Args:
  4497. path_in_repo (`str`):
  4498. Relative filepath in the repo, for example:
  4499. `"checkpoints/1fec34a/weights.bin"`
  4500. repo_id (`str`):
  4501. The repository from which the file will be deleted, for example:
  4502. `"username/custom_transformers"`
  4503. token (`bool` or `str`, *optional*):
  4504. A valid user access token (string). Defaults to the locally saved
  4505. token, which is the recommended method for authentication (see
  4506. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4507. To disable authentication, pass `False`.
  4508. repo_type (`str`, *optional*):
  4509. Set to `"dataset"` or `"space"` if the file is in a dataset or
  4510. space, `None` or `"model"` if in a model. Default is `None`.
  4511. revision (`str`, *optional*):
  4512. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4513. commit_message (`str`, *optional*):
  4514. The summary / title / first line of the generated commit. Defaults to
  4515. `f"Delete {path_in_repo} with huggingface_hub"`.
  4516. commit_description (`str` *optional*)
  4517. The description of the generated commit
  4518. create_pr (`boolean`, *optional*):
  4519. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  4520. If `revision` is not set, PR is opened against the `"main"` branch. If
  4521. `revision` is set and is a branch, PR is opened against this branch. If
  4522. `revision` is set and is not a branch name (example: a commit oid), an
  4523. `RevisionNotFoundError` is returned by the server.
  4524. parent_commit (`str`, *optional*):
  4525. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  4526. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  4527. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  4528. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  4529. especially useful if the repo is updated / committed to concurrently.
  4530. > [!TIP]
  4531. > Raises the following errors:
  4532. >
  4533. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  4534. > if the HuggingFace API returned an error
  4535. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4536. > if some parameter value is invalid
  4537. > - [`~utils.RepositoryNotFoundError`]
  4538. > If the repository to download from cannot be found. This may be because it doesn't exist,
  4539. > or because it is set to `private` and you do not have access.
  4540. > - [`~utils.RevisionNotFoundError`]
  4541. > If the revision to download from cannot be found.
  4542. > - [`~utils.EntryNotFoundError`]
  4543. > If the file to download cannot be found.
  4544. """
  4545. commit_message = (
  4546. commit_message if commit_message is not None else f"Delete {path_in_repo} with huggingface_hub"
  4547. )
  4548. operations = [CommitOperationDelete(path_in_repo=path_in_repo)]
  4549. return self.create_commit(
  4550. repo_id=repo_id,
  4551. repo_type=repo_type,
  4552. token=token,
  4553. operations=operations,
  4554. revision=revision,
  4555. commit_message=commit_message,
  4556. commit_description=commit_description,
  4557. create_pr=create_pr,
  4558. parent_commit=parent_commit,
  4559. )
  4560. @validate_hf_hub_args
  4561. def delete_files(
  4562. self,
  4563. repo_id: str,
  4564. delete_patterns: list[str],
  4565. *,
  4566. token: Union[bool, str, None] = None,
  4567. repo_type: Optional[str] = None,
  4568. revision: Optional[str] = None,
  4569. commit_message: Optional[str] = None,
  4570. commit_description: Optional[str] = None,
  4571. create_pr: Optional[bool] = None,
  4572. parent_commit: Optional[str] = None,
  4573. ) -> CommitInfo:
  4574. """
  4575. Delete files from a repository on the Hub.
  4576. If a folder path is provided, the entire folder is deleted as well as
  4577. all files it contained.
  4578. Args:
  4579. repo_id (`str`):
  4580. The repository from which the folder will be deleted, for example:
  4581. `"username/custom_transformers"`
  4582. delete_patterns (`list[str]`):
  4583. List of files or folders to delete. Each string can either be
  4584. a file path, a folder path, or a wildcard pattern. Patterns are Standard
  4585. Wildcards (globbing patterns) as documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm).
  4586. The pattern matching is based on [`fnmatch`](https://docs.python.org/3/library/fnmatch.html).
  4587. Note that `fnmatch` matches `*` across path boundaries, unlike traditional Unix shell globbing.
  4588. E.g. `["file.txt", "folder/", "data/*.parquet"]`
  4589. token (`bool` or `str`, *optional*):
  4590. A valid user access token (string). Defaults to the locally saved
  4591. token, which is the recommended method for authentication (see
  4592. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4593. To disable authentication, pass `False`.
  4594. to the stored token.
  4595. repo_type (`str`, *optional*):
  4596. Type of the repo to delete files from. Can be `"model"`,
  4597. `"dataset"` or `"space"`. Defaults to `"model"`.
  4598. revision (`str`, *optional*):
  4599. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4600. commit_message (`str`, *optional*):
  4601. The summary (first line) of the generated commit. Defaults to
  4602. `f"Delete files using huggingface_hub"`.
  4603. commit_description (`str` *optional*)
  4604. The description of the generated commit.
  4605. create_pr (`boolean`, *optional*):
  4606. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  4607. If `revision` is not set, PR is opened against the `"main"` branch. If
  4608. `revision` is set and is a branch, PR is opened against this branch. If
  4609. `revision` is set and is not a branch name (example: a commit oid), an
  4610. `RevisionNotFoundError` is returned by the server.
  4611. parent_commit (`str`, *optional*):
  4612. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  4613. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  4614. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  4615. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  4616. especially useful if the repo is updated / committed to concurrently.
  4617. """
  4618. operations = self._prepare_folder_deletions(
  4619. repo_id=repo_id, repo_type=repo_type, delete_patterns=delete_patterns, path_in_repo="", revision=revision
  4620. )
  4621. if commit_message is None:
  4622. commit_message = f"Delete files {' '.join(delete_patterns)} with huggingface_hub"
  4623. return self.create_commit(
  4624. repo_id=repo_id,
  4625. repo_type=repo_type,
  4626. token=token,
  4627. operations=operations,
  4628. revision=revision,
  4629. commit_message=commit_message,
  4630. commit_description=commit_description,
  4631. create_pr=create_pr,
  4632. parent_commit=parent_commit,
  4633. )
  4634. @validate_hf_hub_args
  4635. def delete_folder(
  4636. self,
  4637. path_in_repo: str,
  4638. repo_id: str,
  4639. *,
  4640. token: Union[bool, str, None] = None,
  4641. repo_type: Optional[str] = None,
  4642. revision: Optional[str] = None,
  4643. commit_message: Optional[str] = None,
  4644. commit_description: Optional[str] = None,
  4645. create_pr: Optional[bool] = None,
  4646. parent_commit: Optional[str] = None,
  4647. ) -> CommitInfo:
  4648. """
  4649. Deletes a folder in the given repo.
  4650. Simple wrapper around [`create_commit`] method.
  4651. Args:
  4652. path_in_repo (`str`):
  4653. Relative folder path in the repo, for example: `"checkpoints/1fec34a"`.
  4654. repo_id (`str`):
  4655. The repository from which the folder will be deleted, for example:
  4656. `"username/custom_transformers"`
  4657. token (`bool` or `str`, *optional*):
  4658. A valid user access token (string). Defaults to the locally saved
  4659. token, which is the recommended method for authentication (see
  4660. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4661. To disable authentication, pass `False`.
  4662. to the stored token.
  4663. repo_type (`str`, *optional*):
  4664. Set to `"dataset"` or `"space"` if the folder is in a dataset or
  4665. space, `None` or `"model"` if in a model. Default is `None`.
  4666. revision (`str`, *optional*):
  4667. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4668. commit_message (`str`, *optional*):
  4669. The summary / title / first line of the generated commit. Defaults to
  4670. `f"Delete folder {path_in_repo} with huggingface_hub"`.
  4671. commit_description (`str` *optional*)
  4672. The description of the generated commit.
  4673. create_pr (`boolean`, *optional*):
  4674. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  4675. If `revision` is not set, PR is opened against the `"main"` branch. If
  4676. `revision` is set and is a branch, PR is opened against this branch. If
  4677. `revision` is set and is not a branch name (example: a commit oid), an
  4678. `RevisionNotFoundError` is returned by the server.
  4679. parent_commit (`str`, *optional*):
  4680. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  4681. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  4682. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  4683. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  4684. especially useful if the repo is updated / committed to concurrently.
  4685. """
  4686. return self.create_commit(
  4687. repo_id=repo_id,
  4688. repo_type=repo_type,
  4689. token=token,
  4690. operations=[CommitOperationDelete(path_in_repo=path_in_repo, is_folder=True)],
  4691. revision=revision,
  4692. commit_message=(
  4693. commit_message if commit_message is not None else f"Delete folder {path_in_repo} with huggingface_hub"
  4694. ),
  4695. commit_description=commit_description,
  4696. create_pr=create_pr,
  4697. parent_commit=parent_commit,
  4698. )
  4699. def upload_large_folder(
  4700. self,
  4701. repo_id: str,
  4702. folder_path: Union[str, Path],
  4703. *,
  4704. repo_type: str, # Repo type is required!
  4705. revision: Optional[str] = None,
  4706. private: Optional[bool] = None,
  4707. allow_patterns: Optional[Union[list[str], str]] = None,
  4708. ignore_patterns: Optional[Union[list[str], str]] = None,
  4709. num_workers: Optional[int] = None,
  4710. print_report: bool = True,
  4711. print_report_every: int = 60,
  4712. ) -> None:
  4713. """Upload a large folder to the Hub in the most resilient way possible.
  4714. Several workers are started to upload files in an optimized way. Before being committed to a repo, files must be
  4715. hashed and be pre-uploaded if they are LFS files. Workers will perform these tasks for each file in the folder.
  4716. At each step, some metadata information about the upload process is saved in the folder under `.cache/.huggingface/`
  4717. to be able to resume the process if interrupted. The whole process might result in several commits.
  4718. Args:
  4719. repo_id (`str`):
  4720. The repository to which the file will be uploaded.
  4721. E.g. `"HuggingFaceTB/smollm-corpus"`.
  4722. folder_path (`str` or `Path`):
  4723. Path to the folder to upload on the local file system.
  4724. repo_type (`str`):
  4725. Type of the repository. Must be one of `"model"`, `"dataset"` or `"space"`.
  4726. Unlike in all other `HfApi` methods, `repo_type` is explicitly required here. This is to avoid
  4727. any mistake when uploading a large folder to the Hub, and therefore prevent from having to re-upload
  4728. everything.
  4729. revision (`str`, `optional`):
  4730. The branch to commit to. If not provided, the `main` branch will be used.
  4731. private (`bool`, `optional`):
  4732. Whether the repository should be private.
  4733. If `None` (default), the repo will be public unless the organization's default is private.
  4734. allow_patterns (`list[str]` or `str`, *optional*):
  4735. If provided, only files matching at least one pattern are uploaded.
  4736. ignore_patterns (`list[str]` or `str`, *optional*):
  4737. If provided, files matching any of the patterns are not uploaded.
  4738. num_workers (`int`, *optional*):
  4739. Number of workers to start. Defaults to half of CPU cores (minimum 1).
  4740. A higher number of workers may speed up the process if your machine allows it. However, on machines with a
  4741. slower connection, it is recommended to keep the number of workers low to ensure better resumability.
  4742. Indeed, partially uploaded files will have to be completely re-uploaded if the process is interrupted.
  4743. print_report (`bool`, *optional*):
  4744. Whether to print a report of the upload progress. Defaults to True.
  4745. Report is printed to `sys.stdout` every X seconds (60 by defaults) and overwrites the previous report.
  4746. print_report_every (`int`, *optional*):
  4747. Frequency at which the report is printed. Defaults to 60 seconds.
  4748. > [!TIP]
  4749. > A few things to keep in mind:
  4750. > - Repository limits still apply: https://huggingface.co/docs/hub/repositories-recommendations
  4751. > - Do not start several processes in parallel.
  4752. > - You can interrupt and resume the process at any time.
  4753. > - Do not upload the same folder to several repositories. If you need to do so, you must delete the local `.cache/.huggingface/` folder first.
  4754. > [!WARNING]
  4755. > While being much more robust to upload large folders, `upload_large_folder` is more limited than [`upload_folder`] feature-wise. In practice:
  4756. > - you cannot set a custom `path_in_repo`. If you want to upload to a subfolder, you need to set the proper structure locally.
  4757. > - you cannot set a custom `commit_message` and `commit_description` since multiple commits are created.
  4758. > - you cannot delete from the repo while uploading. Please make a separate commit first.
  4759. > - you cannot create a PR directly. Please create a PR first (from the UI or using [`create_pull_request`]) and then commit to it by passing `revision`.
  4760. **Technical details:**
  4761. `upload_large_folder` process is as follow:
  4762. 1. (Check parameters and setup.)
  4763. 2. Create repo if missing.
  4764. 3. List local files to upload.
  4765. 4. Run validation checks and display warnings if repository limits might be exceeded:
  4766. - Warns if the total number of files exceeds 100k (recommended limit).
  4767. - Warns if any folder contains more than 10k files (recommended limit).
  4768. - Warns about files larger than 20GB (recommended) or 50GB (hard limit).
  4769. 5. Start workers. Workers can perform the following tasks:
  4770. - Hash a file.
  4771. - Get upload mode (regular or LFS) for a list of files.
  4772. - Pre-upload an LFS file.
  4773. - Commit a bunch of files.
  4774. Once a worker finishes a task, it will move on to the next task based on the priority list (see below) until
  4775. all files are uploaded and committed.
  4776. 6. While workers are up, regularly print a report to sys.stdout.
  4777. Order of priority:
  4778. 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file).
  4779. 2. Commit if at least 150 files are ready to commit.
  4780. 3. Get upload mode if at least 10 files have been hashed.
  4781. 4. Pre-upload LFS file if at least 1 file and no worker is pre-uploading.
  4782. 5. Hash file if at least 1 file and no worker is hashing.
  4783. 6. Get upload mode if at least 1 file and no worker is getting upload mode.
  4784. 7. Pre-upload LFS file if at least 1 file.
  4785. 8. Hash file if at least 1 file to hash.
  4786. 9. Get upload mode if at least 1 file to get upload mode.
  4787. 10. Commit if at least 1 file to commit and at least 1 min since last commit attempt.
  4788. 11. Commit if at least 1 file to commit and all other queues are empty.
  4789. Special rules:
  4790. - Only one worker can commit at a time.
  4791. - If no tasks are available, the worker waits for 10 seconds before checking again.
  4792. """
  4793. return upload_large_folder_internal(
  4794. self,
  4795. repo_id=repo_id,
  4796. folder_path=folder_path,
  4797. repo_type=repo_type,
  4798. revision=revision,
  4799. private=private,
  4800. allow_patterns=allow_patterns,
  4801. ignore_patterns=ignore_patterns,
  4802. num_workers=num_workers,
  4803. print_report=print_report,
  4804. print_report_every=print_report_every,
  4805. )
  4806. @validate_hf_hub_args
  4807. def get_hf_file_metadata(
  4808. self,
  4809. *,
  4810. url: str,
  4811. token: Union[bool, str, None] = None,
  4812. timeout: Optional[float] = constants.HF_HUB_ETAG_TIMEOUT,
  4813. ) -> HfFileMetadata:
  4814. """Fetch metadata of a file versioned on the Hub for a given url.
  4815. Args:
  4816. url (`str`):
  4817. File url, for example returned by [`hf_hub_url`].
  4818. token (`bool` or `str`, *optional*):
  4819. A valid user access token (string). Defaults to the locally saved
  4820. token, which is the recommended method for authentication (see
  4821. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4822. To disable authentication, pass `False`.
  4823. timeout (`float`, *optional*, defaults to 10):
  4824. How many seconds to wait for the server to send metadata before giving up.
  4825. Returns:
  4826. A [`HfFileMetadata`] object containing metadata such as location, etag, size and commit_hash.
  4827. """
  4828. if token is None:
  4829. # Cannot do `token = token or self.token` as token can be `False`.
  4830. token = self.token
  4831. return get_hf_file_metadata(
  4832. url=url,
  4833. token=token,
  4834. timeout=timeout,
  4835. library_name=self.library_name,
  4836. library_version=self.library_version,
  4837. user_agent=self.user_agent,
  4838. endpoint=self.endpoint,
  4839. )
  4840. @overload
  4841. def hf_hub_download(
  4842. self,
  4843. repo_id: str,
  4844. filename: str,
  4845. *,
  4846. subfolder: Optional[str] = None,
  4847. repo_type: Optional[str] = None,
  4848. revision: Optional[str] = None,
  4849. cache_dir: Union[str, Path, None] = None,
  4850. local_dir: Union[str, Path, None] = None,
  4851. force_download: bool = False,
  4852. etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
  4853. token: Union[bool, str, None] = None,
  4854. local_files_only: bool = False,
  4855. tqdm_class: Optional[type[base_tqdm]] = None,
  4856. dry_run: Literal[False] = False,
  4857. ) -> str: ...
  4858. @overload
  4859. def hf_hub_download(
  4860. self,
  4861. repo_id: str,
  4862. filename: str,
  4863. *,
  4864. subfolder: Optional[str] = None,
  4865. repo_type: Optional[str] = None,
  4866. revision: Optional[str] = None,
  4867. cache_dir: Union[str, Path, None] = None,
  4868. local_dir: Union[str, Path, None] = None,
  4869. force_download: bool = False,
  4870. etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
  4871. token: Union[bool, str, None] = None,
  4872. local_files_only: bool = False,
  4873. tqdm_class: Optional[type[base_tqdm]] = None,
  4874. dry_run: Literal[True],
  4875. ) -> DryRunFileInfo: ...
  4876. @validate_hf_hub_args
  4877. def hf_hub_download(
  4878. self,
  4879. repo_id: str,
  4880. filename: str,
  4881. *,
  4882. subfolder: Optional[str] = None,
  4883. repo_type: Optional[str] = None,
  4884. revision: Optional[str] = None,
  4885. cache_dir: Union[str, Path, None] = None,
  4886. local_dir: Union[str, Path, None] = None,
  4887. force_download: bool = False,
  4888. etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
  4889. token: Union[bool, str, None] = None,
  4890. local_files_only: bool = False,
  4891. tqdm_class: Optional[type[base_tqdm]] = None,
  4892. dry_run: bool = False,
  4893. ) -> Union[str, DryRunFileInfo]:
  4894. """Download a given file if it's not already present in the local cache.
  4895. The new cache file layout looks like this:
  4896. - The cache directory contains one subfolder per repo_id (namespaced by repo type)
  4897. - inside each repo folder:
  4898. - refs is a list of the latest known revision => commit_hash pairs
  4899. - blobs contains the actual file blobs (identified by their git-sha or sha256, depending on
  4900. whether they're LFS files or not)
  4901. - snapshots contains one subfolder per commit, each "commit" contains the subset of the files
  4902. that have been resolved at that particular commit. Each filename is a symlink to the blob
  4903. at that particular commit.
  4904. ```
  4905. [ 96] .
  4906. └── [ 160] models--julien-c--EsperBERTo-small
  4907. ├── [ 160] blobs
  4908. │ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
  4909. │ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e
  4910. │ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812
  4911. ├── [ 96] refs
  4912. │ └── [ 40] main
  4913. └── [ 128] snapshots
  4914. ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
  4915. │ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
  4916. │ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
  4917. └── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48
  4918. ├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
  4919. └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
  4920. ```
  4921. If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
  4922. option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
  4923. to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
  4924. cache-system, it's optimized for regularly pulling the latest version of a repository.
  4925. Args:
  4926. repo_id (`str`):
  4927. A user or an organization name and a repo name separated by a `/`.
  4928. filename (`str`):
  4929. The name of the file in the repo.
  4930. subfolder (`str`, *optional*):
  4931. An optional value corresponding to a folder inside the repository.
  4932. repo_type (`str`, *optional*):
  4933. Set to `"dataset"` or `"space"` if downloading from a dataset or space,
  4934. `None` or `"model"` if downloading from a model. Default is `None`.
  4935. revision (`str`, *optional*):
  4936. An optional Git revision id which can be a branch name, a tag, or a
  4937. commit hash.
  4938. cache_dir (`str`, `Path`, *optional*):
  4939. Path to the folder where cached files are stored.
  4940. local_dir (`str` or `Path`, *optional*):
  4941. If provided, the downloaded file will be placed under this directory.
  4942. force_download (`bool`, *optional*, defaults to `False`):
  4943. Whether the file should be downloaded even if it already exists in
  4944. the local cache.
  4945. etag_timeout (`float`, *optional*, defaults to `10`):
  4946. When fetching ETag, how many seconds to wait for the server to send
  4947. data before giving up which is passed to `httpx.request`.
  4948. token (`bool` or `str`, *optional*):
  4949. A valid user access token (string). Defaults to the locally saved
  4950. token, which is the recommended method for authentication (see
  4951. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4952. To disable authentication, pass `False`.
  4953. local_files_only (`bool`, *optional*, defaults to `False`):
  4954. If `True`, avoid downloading the file and return the path to the
  4955. local cached file if it exists.
  4956. tqdm_class (`tqdm`, *optional*):
  4957. If provided, overwrites the default behavior for the progress bar. Passed
  4958. argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
  4959. Defaults to the custom HF progress bar that can be disabled by setting
  4960. `HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
  4961. dry_run (`bool`, *optional*, defaults to `False`):
  4962. If `True`, perform a dry run without actually downloading the file. Returns a
  4963. [`DryRunFileInfo`] object containing information about what would be downloaded.
  4964. Returns:
  4965. `str` or [`DryRunFileInfo`]:
  4966. - If `dry_run=False`: Local path of file or if networking is off, last version of file cached on disk.
  4967. - If `dry_run=True`: A [`DryRunFileInfo`] object containing download information.
  4968. Raises:
  4969. [`~utils.RepositoryNotFoundError`]
  4970. If the repository to download from cannot be found. This may be because it doesn't exist,
  4971. or because it is set to `private` and you do not have access.
  4972. [`~utils.RevisionNotFoundError`]
  4973. If the revision to download from cannot be found.
  4974. [`~utils.RemoteEntryNotFoundError`]
  4975. If the file to download cannot be found.
  4976. [`~utils.LocalEntryNotFoundError`]
  4977. If network is disabled or unavailable and file is not found in cache.
  4978. [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
  4979. If `token=True` but the token cannot be found.
  4980. [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
  4981. If ETag cannot be determined.
  4982. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4983. If some parameter value is invalid.
  4984. """
  4985. from .file_download import hf_hub_download
  4986. if token is None:
  4987. # Cannot do `token = token or self.token` as token can be `False`.
  4988. token = self.token
  4989. return hf_hub_download(
  4990. repo_id=repo_id,
  4991. filename=filename,
  4992. subfolder=subfolder,
  4993. repo_type=repo_type,
  4994. revision=revision,
  4995. endpoint=self.endpoint,
  4996. library_name=self.library_name,
  4997. library_version=self.library_version,
  4998. cache_dir=cache_dir,
  4999. local_dir=local_dir,
  5000. user_agent=self.user_agent,
  5001. force_download=force_download,
  5002. etag_timeout=etag_timeout,
  5003. token=token,
  5004. headers=self.headers,
  5005. local_files_only=local_files_only,
  5006. tqdm_class=tqdm_class,
  5007. dry_run=dry_run,
  5008. )
  5009. @validate_hf_hub_args
  5010. def snapshot_download(
  5011. self,
  5012. repo_id: str,
  5013. *,
  5014. repo_type: Optional[str] = None,
  5015. revision: Optional[str] = None,
  5016. cache_dir: Union[str, Path, None] = None,
  5017. local_dir: Union[str, Path, None] = None,
  5018. etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
  5019. force_download: bool = False,
  5020. token: Union[bool, str, None] = None,
  5021. local_files_only: bool = False,
  5022. allow_patterns: Optional[Union[list[str], str]] = None,
  5023. ignore_patterns: Optional[Union[list[str], str]] = None,
  5024. max_workers: int = 8,
  5025. tqdm_class: Optional[type[base_tqdm]] = None,
  5026. dry_run: bool = False,
  5027. ) -> Union[str, list[DryRunFileInfo]]:
  5028. """Download repo files.
  5029. Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from
  5030. a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order
  5031. to keep their actual filename relative to that folder. You can also filter which files to download using
  5032. `allow_patterns` and `ignore_patterns`.
  5033. If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
  5034. option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
  5035. to store some metadata related to the downloaded files.While this mechanism is not as robust as the main
  5036. cache-system, it's optimized for regularly pulling the latest version of a repository.
  5037. An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly
  5038. configured. It is also not possible to filter which files to download when cloning a repository using git.
  5039. Args:
  5040. repo_id (`str`):
  5041. A user or an organization name and a repo name separated by a `/`.
  5042. repo_type (`str`, *optional*):
  5043. Set to `"dataset"` or `"space"` if downloading from a dataset or space,
  5044. `None` or `"model"` if downloading from a model. Default is `None`.
  5045. revision (`str`, *optional*):
  5046. An optional Git revision id which can be a branch name, a tag, or a
  5047. commit hash.
  5048. cache_dir (`str`, `Path`, *optional*):
  5049. Path to the folder where cached files are stored.
  5050. local_dir (`str` or `Path`, *optional*):
  5051. If provided, the downloaded files will be placed under this directory.
  5052. etag_timeout (`float`, *optional*, defaults to `10`):
  5053. When fetching ETag, how many seconds to wait for the server to send
  5054. data before giving up which is passed to `httpx.request`.
  5055. force_download (`bool`, *optional*, defaults to `False`):
  5056. Whether the file should be downloaded even if it already exists in the local cache.
  5057. token (`bool` or `str`, *optional*):
  5058. A valid user access token (string). Defaults to the locally saved
  5059. token, which is the recommended method for authentication (see
  5060. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5061. To disable authentication, pass `False`.
  5062. local_files_only (`bool`, *optional*, defaults to `False`):
  5063. If `True`, avoid downloading the file and return the path to the
  5064. local cached file if it exists.
  5065. allow_patterns (`list[str]` or `str`, *optional*):
  5066. If provided, only files matching at least one pattern are downloaded.
  5067. ignore_patterns (`list[str]` or `str`, *optional*):
  5068. If provided, files matching any of the patterns are not downloaded.
  5069. max_workers (`int`, *optional*):
  5070. Number of concurrent threads to download files (1 thread = 1 file download).
  5071. Defaults to 8.
  5072. tqdm_class (`tqdm`, *optional*):
  5073. If provided, overwrites the default behavior for the progress bar. Passed
  5074. argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
  5075. Note that the `tqdm_class` is not passed to each individual download.
  5076. Defaults to the custom HF progress bar that can be disabled by setting
  5077. `HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
  5078. dry_run (`bool`, *optional*, defaults to `False`):
  5079. If `True`, perform a dry run without actually downloading the files. Returns a list of
  5080. [`DryRunFileInfo`] objects containing information about what would be downloaded.
  5081. Returns:
  5082. `str` or list of [`DryRunFileInfo`]:
  5083. - If `dry_run=False`: Folder path of the repo snapshot.
  5084. - If `dry_run=True`: A list of [`DryRunFileInfo`] objects containing download information.
  5085. Raises:
  5086. [`~utils.RepositoryNotFoundError`]
  5087. If the repository to download from cannot be found. This may be because it doesn't exist,
  5088. or because it is set to `private` and you do not have access.
  5089. [`~utils.RevisionNotFoundError`]
  5090. If the revision to download from cannot be found.
  5091. [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
  5092. If `token=True` and the token cannot be found.
  5093. [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if
  5094. ETag cannot be determined.
  5095. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5096. if some parameter value is invalid.
  5097. """
  5098. from ._snapshot_download import snapshot_download
  5099. if token is None:
  5100. # Cannot do `token = token or self.token` as token can be `False`.
  5101. token = self.token
  5102. return snapshot_download(
  5103. repo_id=repo_id,
  5104. repo_type=repo_type,
  5105. revision=revision,
  5106. endpoint=self.endpoint,
  5107. cache_dir=cache_dir,
  5108. local_dir=local_dir,
  5109. library_name=self.library_name,
  5110. library_version=self.library_version,
  5111. user_agent=self.user_agent,
  5112. etag_timeout=etag_timeout,
  5113. force_download=force_download,
  5114. token=token,
  5115. local_files_only=local_files_only,
  5116. allow_patterns=allow_patterns,
  5117. ignore_patterns=ignore_patterns,
  5118. max_workers=max_workers,
  5119. tqdm_class=tqdm_class,
  5120. headers=self.headers,
  5121. dry_run=dry_run,
  5122. )
  5123. def get_safetensors_metadata(
  5124. self,
  5125. repo_id: str,
  5126. *,
  5127. repo_type: Optional[str] = None,
  5128. revision: Optional[str] = None,
  5129. token: Union[bool, str, None] = None,
  5130. ) -> SafetensorsRepoMetadata:
  5131. """
  5132. Parse metadata for a safetensors repo on the Hub.
  5133. We first check if the repo has a single safetensors file or a sharded safetensors repo. If it's a single
  5134. safetensors file, we parse the metadata from this file. If it's a sharded safetensors repo, we parse the
  5135. metadata from the index file and then parse the metadata from each shard.
  5136. To parse metadata from a single safetensors file, use [`parse_safetensors_file_metadata`].
  5137. For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
  5138. Args:
  5139. repo_id (`str`):
  5140. A user or an organization name and a repo name separated by a `/`.
  5141. repo_type (`str`, *optional*):
  5142. Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
  5143. model. Default is `None`.
  5144. revision (`str`, *optional*):
  5145. The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
  5146. head of the `"main"` branch.
  5147. token (`bool` or `str`, *optional*):
  5148. A valid user access token (string). Defaults to the locally saved
  5149. token, which is the recommended method for authentication (see
  5150. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5151. To disable authentication, pass `False`.
  5152. Returns:
  5153. [`SafetensorsRepoMetadata`]: information related to safetensors repo.
  5154. Raises:
  5155. [`NotASafetensorsRepoError`]
  5156. If the repo is not a safetensors repo i.e. doesn't have either a
  5157. `model.safetensors` or a `model.safetensors.index.json` file.
  5158. [`SafetensorsParsingError`]
  5159. If a safetensors file header couldn't be parsed correctly.
  5160. Example:
  5161. ```py
  5162. # Parse repo with single weights file
  5163. >>> metadata = get_safetensors_metadata("bigscience/bloomz-560m")
  5164. >>> metadata
  5165. SafetensorsRepoMetadata(
  5166. metadata=None,
  5167. sharded=False,
  5168. weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...},
  5169. files_metadata={'model.safetensors': SafetensorsFileMetadata(...)}
  5170. )
  5171. >>> metadata.files_metadata["model.safetensors"].metadata
  5172. {'format': 'pt'}
  5173. # Parse repo with sharded model
  5174. >>> metadata = get_safetensors_metadata("bigscience/bloom")
  5175. Parse safetensors files: 100%|██████████████████████████████████████████| 72/72 [00:12<00:00, 5.78it/s]
  5176. >>> metadata
  5177. SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...})
  5178. >>> len(metadata.files_metadata)
  5179. 72 # All safetensors files have been fetched
  5180. # Parse repo with sharded model
  5181. >>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5")
  5182. NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files.
  5183. ```
  5184. """
  5185. if self.file_exists( # Single safetensors file => non-sharded model
  5186. repo_id=repo_id,
  5187. filename=constants.SAFETENSORS_SINGLE_FILE,
  5188. repo_type=repo_type,
  5189. revision=revision,
  5190. token=token,
  5191. ):
  5192. file_metadata = self.parse_safetensors_file_metadata(
  5193. repo_id=repo_id,
  5194. filename=constants.SAFETENSORS_SINGLE_FILE,
  5195. repo_type=repo_type,
  5196. revision=revision,
  5197. token=token,
  5198. )
  5199. return SafetensorsRepoMetadata(
  5200. metadata=None,
  5201. sharded=False,
  5202. weight_map={
  5203. tensor_name: constants.SAFETENSORS_SINGLE_FILE for tensor_name in file_metadata.tensors.keys()
  5204. },
  5205. files_metadata={constants.SAFETENSORS_SINGLE_FILE: file_metadata},
  5206. )
  5207. elif self.file_exists( # Multiple safetensors files => sharded with index
  5208. repo_id=repo_id,
  5209. filename=constants.SAFETENSORS_INDEX_FILE,
  5210. repo_type=repo_type,
  5211. revision=revision,
  5212. token=token,
  5213. ):
  5214. # Fetch index
  5215. index_file = self.hf_hub_download(
  5216. repo_id=repo_id,
  5217. filename=constants.SAFETENSORS_INDEX_FILE,
  5218. repo_type=repo_type,
  5219. revision=revision,
  5220. token=token,
  5221. )
  5222. with open(index_file) as f:
  5223. index = json.load(f)
  5224. weight_map = index.get("weight_map", {})
  5225. # Fetch metadata per shard
  5226. files_metadata = {}
  5227. def _parse(filename: str) -> None:
  5228. files_metadata[filename] = self.parse_safetensors_file_metadata(
  5229. repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, token=token
  5230. )
  5231. thread_map(
  5232. _parse,
  5233. set(weight_map.values()),
  5234. desc="Parse safetensors files",
  5235. tqdm_class=hf_tqdm,
  5236. )
  5237. return SafetensorsRepoMetadata(
  5238. metadata=index.get("metadata", None),
  5239. sharded=True,
  5240. weight_map=weight_map,
  5241. files_metadata=files_metadata,
  5242. )
  5243. else:
  5244. # Not a safetensors repo
  5245. raise NotASafetensorsRepoError(
  5246. f"'{repo_id}' is not a safetensors repo. Couldn't find '{constants.SAFETENSORS_INDEX_FILE}' or '{constants.SAFETENSORS_SINGLE_FILE}' files."
  5247. )
  5248. def parse_safetensors_file_metadata(
  5249. self,
  5250. repo_id: str,
  5251. filename: str,
  5252. *,
  5253. repo_type: Optional[str] = None,
  5254. revision: Optional[str] = None,
  5255. token: Union[bool, str, None] = None,
  5256. ) -> SafetensorsFileMetadata:
  5257. """
  5258. Parse metadata from a safetensors file on the Hub.
  5259. To parse metadata from all safetensors files in a repo at once, use [`get_safetensors_metadata`].
  5260. For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
  5261. Args:
  5262. repo_id (`str`):
  5263. A user or an organization name and a repo name separated by a `/`.
  5264. filename (`str`):
  5265. The name of the file in the repo.
  5266. repo_type (`str`, *optional*):
  5267. Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
  5268. model. Default is `None`.
  5269. revision (`str`, *optional*):
  5270. The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
  5271. head of the `"main"` branch.
  5272. token (`bool` or `str`, *optional*):
  5273. A valid user access token (string). Defaults to the locally saved
  5274. token, which is the recommended method for authentication (see
  5275. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5276. To disable authentication, pass `False`.
  5277. Returns:
  5278. [`SafetensorsFileMetadata`]: information related to a safetensors file.
  5279. Raises:
  5280. [`NotASafetensorsRepoError`]:
  5281. If the repo is not a safetensors repo i.e. doesn't have either a
  5282. `model.safetensors` or a `model.safetensors.index.json` file.
  5283. [`SafetensorsParsingError`]:
  5284. If a safetensors file header couldn't be parsed correctly.
  5285. """
  5286. url = hf_hub_url(
  5287. repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, endpoint=self.endpoint
  5288. )
  5289. _headers = self._build_hf_headers(token=token)
  5290. context_msg = f"repo '{repo_id}', revision '{revision or constants.DEFAULT_REVISION}'"
  5291. # 1. Fetch first 100kb
  5292. # Empirically, 97% of safetensors files have a metadata size < 100kb (over the top 1000 models on the Hub).
  5293. # We assume fetching 100kb is faster than making 2 GET requests. Therefore we always fetch the first 100kb to
  5294. # avoid the 2nd GET in most cases.
  5295. # See https://github.com/huggingface/huggingface_hub/pull/1855#discussion_r1404286419.
  5296. response = get_session().get(url, headers={**_headers, "range": "bytes=0-100000"})
  5297. hf_raise_for_status(response)
  5298. # 2. Parse and validate metadata size using shared helper
  5299. metadata_size = _get_safetensors_metadata_size(response.content[:8], filename, context_msg)
  5300. # 3.a. Get metadata from payload
  5301. if metadata_size <= 100000:
  5302. metadata_as_bytes = response.content[8 : 8 + metadata_size]
  5303. else: # 3.b. Request full metadata
  5304. response = get_session().get(url, headers={**_headers, "range": f"bytes=8-{metadata_size + 7}"})
  5305. hf_raise_for_status(response)
  5306. metadata_as_bytes = response.content
  5307. # 4. Parse json header using shared helper
  5308. return _parse_safetensors_header(metadata_as_bytes, filename, context_msg)
  5309. @validate_hf_hub_args
  5310. def create_branch(
  5311. self,
  5312. repo_id: str,
  5313. *,
  5314. branch: str,
  5315. revision: Optional[str] = None,
  5316. token: Union[bool, str, None] = None,
  5317. repo_type: Optional[str] = None,
  5318. exist_ok: bool = False,
  5319. ) -> None:
  5320. """
  5321. Create a new branch for a repo on the Hub, starting from the specified revision (defaults to `main`).
  5322. To find a revision suiting your needs, you can use [`list_repo_refs`] or [`list_repo_commits`].
  5323. Args:
  5324. repo_id (`str`):
  5325. The repository in which the branch will be created.
  5326. Example: `"user/my-cool-model"`.
  5327. branch (`str`):
  5328. The name of the branch to create.
  5329. revision (`str`, *optional*):
  5330. The git revision to create the branch from. It can be a branch name or
  5331. the OID/SHA of a commit, as a hexadecimal string. Defaults to the head
  5332. of the `"main"` branch.
  5333. token (`bool` or `str`, *optional*):
  5334. A valid user access token (string). Defaults to the locally saved
  5335. token, which is the recommended method for authentication (see
  5336. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5337. To disable authentication, pass `False`.
  5338. repo_type (`str`, *optional*):
  5339. Set to `"dataset"` or `"space"` if creating a branch on a dataset or
  5340. space, `None` or `"model"` if tagging a model. Default is `None`.
  5341. exist_ok (`bool`, *optional*, defaults to `False`):
  5342. If `True`, do not raise an error if branch already exists.
  5343. Raises:
  5344. [`~utils.RepositoryNotFoundError`]:
  5345. If repository is not found (error 404): wrong repo_id/repo_type, private
  5346. but not authenticated or repo does not exist.
  5347. [`~utils.BadRequestError`]:
  5348. If invalid reference for a branch. Ex: `refs/pr/5` or 'refs/foo/bar'.
  5349. [`~utils.HfHubHTTPError`]:
  5350. If the branch already exists on the repo (error 409) and `exist_ok` is
  5351. set to `False`.
  5352. """
  5353. if repo_type is None:
  5354. repo_type = constants.REPO_TYPE_MODEL
  5355. branch = quote(branch, safe="")
  5356. # Prepare request
  5357. branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}"
  5358. headers = self._build_hf_headers(token=token)
  5359. payload = {}
  5360. if revision is not None:
  5361. payload["startingPoint"] = revision
  5362. # Create branch
  5363. response = get_session().post(url=branch_url, headers=headers, json=payload)
  5364. try:
  5365. hf_raise_for_status(response)
  5366. except HfHubHTTPError as e:
  5367. if exist_ok and e.response.status_code == 409:
  5368. return
  5369. elif exist_ok and e.response.status_code == 403:
  5370. # No write permission on the namespace but branch might already exist
  5371. try:
  5372. refs = self.list_repo_refs(repo_id=repo_id, repo_type=repo_type, token=token)
  5373. for branch_ref in refs.branches:
  5374. if branch_ref.name == branch:
  5375. return # Branch already exists => do not raise
  5376. except HfHubHTTPError:
  5377. pass # We raise the original error if the branch does not exist
  5378. raise
  5379. @validate_hf_hub_args
  5380. def delete_branch(
  5381. self,
  5382. repo_id: str,
  5383. *,
  5384. branch: str,
  5385. token: Union[bool, str, None] = None,
  5386. repo_type: Optional[str] = None,
  5387. ) -> None:
  5388. """
  5389. Delete a branch from a repo on the Hub.
  5390. Args:
  5391. repo_id (`str`):
  5392. The repository in which a branch will be deleted.
  5393. Example: `"user/my-cool-model"`.
  5394. branch (`str`):
  5395. The name of the branch to delete.
  5396. token (`bool` or `str`, *optional*):
  5397. A valid user access token (string). Defaults to the locally saved
  5398. token, which is the recommended method for authentication (see
  5399. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5400. To disable authentication, pass `False`.
  5401. repo_type (`str`, *optional*):
  5402. Set to `"dataset"` or `"space"` if creating a branch on a dataset or
  5403. space, `None` or `"model"` if tagging a model. Default is `None`.
  5404. Raises:
  5405. [`~utils.RepositoryNotFoundError`]:
  5406. If repository is not found (error 404): wrong repo_id/repo_type, private
  5407. but not authenticated or repo does not exist.
  5408. [`~utils.HfHubHTTPError`]:
  5409. If trying to delete a protected branch. Ex: `main` cannot be deleted.
  5410. [`~utils.HfHubHTTPError`]:
  5411. If trying to delete a branch that does not exist.
  5412. """
  5413. if repo_type is None:
  5414. repo_type = constants.REPO_TYPE_MODEL
  5415. branch = quote(branch, safe="")
  5416. # Prepare request
  5417. branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}"
  5418. headers = self._build_hf_headers(token=token)
  5419. # Delete branch
  5420. response = get_session().delete(url=branch_url, headers=headers)
  5421. hf_raise_for_status(response)
  5422. @validate_hf_hub_args
  5423. def create_tag(
  5424. self,
  5425. repo_id: str,
  5426. *,
  5427. tag: str,
  5428. tag_message: Optional[str] = None,
  5429. revision: Optional[str] = None,
  5430. token: Union[bool, str, None] = None,
  5431. repo_type: Optional[str] = None,
  5432. exist_ok: bool = False,
  5433. ) -> None:
  5434. """
  5435. Tag a given commit of a repo on the Hub.
  5436. Args:
  5437. repo_id (`str`):
  5438. The repository in which a commit will be tagged.
  5439. Example: `"user/my-cool-model"`.
  5440. tag (`str`):
  5441. The name of the tag to create.
  5442. tag_message (`str`, *optional*):
  5443. The description of the tag to create.
  5444. revision (`str`, *optional*):
  5445. The git revision to tag. It can be a branch name or the OID/SHA of a
  5446. commit, as a hexadecimal string. Shorthands (7 first characters) are
  5447. also supported. Defaults to the head of the `"main"` branch.
  5448. token (`bool` or `str`, *optional*):
  5449. A valid user access token (string). Defaults to the locally saved
  5450. token, which is the recommended method for authentication (see
  5451. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5452. To disable authentication, pass `False`.
  5453. repo_type (`str`, *optional*):
  5454. Set to `"dataset"` or `"space"` if tagging a dataset or
  5455. space, `None` or `"model"` if tagging a model. Default is
  5456. `None`.
  5457. exist_ok (`bool`, *optional*, defaults to `False`):
  5458. If `True`, do not raise an error if tag already exists.
  5459. Raises:
  5460. [`~utils.RepositoryNotFoundError`]:
  5461. If repository is not found (error 404): wrong repo_id/repo_type, private
  5462. but not authenticated or repo does not exist.
  5463. [`~utils.RevisionNotFoundError`]:
  5464. If revision is not found (error 404) on the repo.
  5465. [`~utils.HfHubHTTPError`]:
  5466. If the branch already exists on the repo (error 409) and `exist_ok` is
  5467. set to `False`.
  5468. """
  5469. if repo_type is None:
  5470. repo_type = constants.REPO_TYPE_MODEL
  5471. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  5472. # Prepare request
  5473. tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{revision}"
  5474. headers = self._build_hf_headers(token=token)
  5475. payload = {"tag": tag}
  5476. if tag_message is not None:
  5477. payload["message"] = tag_message
  5478. # Tag
  5479. response = get_session().post(url=tag_url, headers=headers, json=payload)
  5480. try:
  5481. hf_raise_for_status(response)
  5482. except HfHubHTTPError as e:
  5483. if not (e.response.status_code == 409 and exist_ok):
  5484. raise
  5485. @validate_hf_hub_args
  5486. def delete_tag(
  5487. self,
  5488. repo_id: str,
  5489. *,
  5490. tag: str,
  5491. token: Union[bool, str, None] = None,
  5492. repo_type: Optional[str] = None,
  5493. ) -> None:
  5494. """
  5495. Delete a tag from a repo on the Hub.
  5496. Args:
  5497. repo_id (`str`):
  5498. The repository in which a tag will be deleted.
  5499. Example: `"user/my-cool-model"`.
  5500. tag (`str`):
  5501. The name of the tag to delete.
  5502. token (`bool` or `str`, *optional*):
  5503. A valid user access token (string). Defaults to the locally saved
  5504. token, which is the recommended method for authentication (see
  5505. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5506. To disable authentication, pass `False`.
  5507. repo_type (`str`, *optional*):
  5508. Set to `"dataset"` or `"space"` if tagging a dataset or space, `None` or
  5509. `"model"` if tagging a model. Default is `None`.
  5510. Raises:
  5511. [`~utils.RepositoryNotFoundError`]:
  5512. If repository is not found (error 404): wrong repo_id/repo_type, private
  5513. but not authenticated or repo does not exist.
  5514. [`~utils.RevisionNotFoundError`]:
  5515. If tag is not found.
  5516. """
  5517. if repo_type is None:
  5518. repo_type = constants.REPO_TYPE_MODEL
  5519. tag = quote(tag, safe="")
  5520. # Prepare request
  5521. tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{tag}"
  5522. headers = self._build_hf_headers(token=token)
  5523. # Un-tag
  5524. response = get_session().delete(url=tag_url, headers=headers)
  5525. hf_raise_for_status(response)
  5526. @validate_hf_hub_args
  5527. def get_full_repo_name(
  5528. self,
  5529. model_id: str,
  5530. *,
  5531. organization: Optional[str] = None,
  5532. token: Union[bool, str, None] = None,
  5533. ):
  5534. """
  5535. Returns the repository name for a given model ID and optional
  5536. organization.
  5537. Args:
  5538. model_id (`str`):
  5539. The name of the model.
  5540. organization (`str`, *optional*):
  5541. If passed, the repository name will be in the organization
  5542. namespace instead of the user namespace.
  5543. token (`bool` or `str`, *optional*):
  5544. A valid user access token (string). Defaults to the locally saved
  5545. token, which is the recommended method for authentication (see
  5546. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5547. To disable authentication, pass `False`.
  5548. Returns:
  5549. `str`: The repository name in the user's namespace
  5550. ({username}/{model_id}) if no organization is passed, and under the
  5551. organization namespace ({organization}/{model_id}) otherwise.
  5552. """
  5553. if organization is None:
  5554. if "/" in model_id:
  5555. username = model_id.split("/")[0]
  5556. else:
  5557. username = self.whoami(token=token)["name"] # type: ignore
  5558. return f"{username}/{model_id}"
  5559. else:
  5560. return f"{organization}/{model_id}"
  5561. @validate_hf_hub_args
  5562. def get_repo_discussions(
  5563. self,
  5564. repo_id: str,
  5565. *,
  5566. author: Optional[str] = None,
  5567. discussion_type: Optional[constants.DiscussionTypeFilter] = None,
  5568. discussion_status: Optional[constants.DiscussionStatusFilter] = None,
  5569. repo_type: Optional[str] = None,
  5570. token: Union[bool, str, None] = None,
  5571. ) -> Iterator[Discussion]:
  5572. """
  5573. Fetches Discussions and Pull Requests for the given repo.
  5574. Args:
  5575. repo_id (`str`):
  5576. A namespace (user or an organization) and a repo name separated
  5577. by a `/`.
  5578. author (`str`, *optional*):
  5579. Pass a value to filter by discussion author. `None` means no filter.
  5580. Default is `None`.
  5581. discussion_type (`str`, *optional*):
  5582. Set to `"pull_request"` to fetch only pull requests, `"discussion"`
  5583. to fetch only discussions. Set to `"all"` or `None` to fetch both.
  5584. Default is `None`.
  5585. discussion_status (`str`, *optional*):
  5586. Set to `"open"` (respectively `"closed"`) to fetch only open
  5587. (respectively closed) discussions. Set to `"all"` or `None`
  5588. to fetch both.
  5589. Default is `None`.
  5590. repo_type (`str`, *optional*):
  5591. Set to `"dataset"` or `"space"` if fetching from a dataset or
  5592. space, `None` or `"model"` if fetching from a model. Default is
  5593. `None`.
  5594. token (`bool` or `str`, *optional*):
  5595. A valid user access token (string). Defaults to the locally saved
  5596. token, which is the recommended method for authentication (see
  5597. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5598. To disable authentication, pass `False`.
  5599. Returns:
  5600. `Iterator[Discussion]`: An iterator of [`Discussion`] objects.
  5601. Example:
  5602. Collecting all discussions of a repo in a list:
  5603. ```python
  5604. >>> from huggingface_hub import get_repo_discussions
  5605. >>> discussions_list = list(get_repo_discussions(repo_id="bert-base-uncased"))
  5606. ```
  5607. Iterating over discussions of a repo:
  5608. ```python
  5609. >>> from huggingface_hub import get_repo_discussions
  5610. >>> for discussion in get_repo_discussions(repo_id="bert-base-uncased"):
  5611. ... print(discussion.num, discussion.title)
  5612. ```
  5613. """
  5614. if repo_type not in constants.REPO_TYPES:
  5615. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  5616. if repo_type is None:
  5617. repo_type = constants.REPO_TYPE_MODEL
  5618. if discussion_type is not None and discussion_type not in constants.DISCUSSION_TYPES:
  5619. raise ValueError(f"Invalid discussion_type, must be one of {constants.DISCUSSION_TYPES}")
  5620. if discussion_status is not None and discussion_status not in constants.DISCUSSION_STATUS:
  5621. raise ValueError(f"Invalid discussion_status, must be one of {constants.DISCUSSION_STATUS}")
  5622. headers = self._build_hf_headers(token=token)
  5623. path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions"
  5624. params: dict[str, Union[str, int]] = {}
  5625. if discussion_type is not None:
  5626. params["type"] = discussion_type
  5627. if discussion_status is not None:
  5628. params["status"] = discussion_status
  5629. if author is not None:
  5630. params["author"] = author
  5631. def _fetch_discussion_page(page_index: int):
  5632. params["p"] = page_index
  5633. resp = get_session().get(path, headers=headers, params=params)
  5634. hf_raise_for_status(resp)
  5635. paginated_discussions = resp.json()
  5636. total = paginated_discussions["count"]
  5637. start = paginated_discussions["start"]
  5638. discussions = paginated_discussions["discussions"]
  5639. has_next = (start + len(discussions)) < total
  5640. return discussions, has_next
  5641. has_next, page_index = True, 0
  5642. while has_next:
  5643. discussions, has_next = _fetch_discussion_page(page_index=page_index)
  5644. for discussion in discussions:
  5645. yield Discussion(
  5646. title=discussion["title"],
  5647. num=discussion["num"],
  5648. author=discussion.get("author", {}).get("name", "deleted"),
  5649. created_at=parse_datetime(discussion["createdAt"]),
  5650. status=discussion["status"],
  5651. repo_id=discussion["repo"]["name"],
  5652. repo_type=discussion["repo"]["type"],
  5653. is_pull_request=discussion["isPullRequest"],
  5654. endpoint=self.endpoint,
  5655. )
  5656. page_index = page_index + 1
  5657. @validate_hf_hub_args
  5658. def get_discussion_details(
  5659. self,
  5660. repo_id: str,
  5661. discussion_num: int,
  5662. *,
  5663. repo_type: Optional[str] = None,
  5664. token: Union[bool, str, None] = None,
  5665. ) -> DiscussionWithDetails:
  5666. """Fetches a Discussion's / Pull Request 's details from the Hub.
  5667. Args:
  5668. repo_id (`str`):
  5669. A namespace (user or an organization) and a repo name separated
  5670. by a `/`.
  5671. discussion_num (`int`):
  5672. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  5673. repo_type (`str`, *optional*):
  5674. Set to `"dataset"` or `"space"` if uploading to a dataset or
  5675. space, `None` or `"model"` if uploading to a model. Default is
  5676. `None`.
  5677. token (`bool` or `str`, *optional*):
  5678. A valid user access token (string). Defaults to the locally saved
  5679. token, which is the recommended method for authentication (see
  5680. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5681. To disable authentication, pass `False`.
  5682. Returns: [`DiscussionWithDetails`]
  5683. > [!TIP]
  5684. > Raises the following errors:
  5685. >
  5686. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  5687. > if the HuggingFace API returned an error
  5688. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5689. > if some parameter value is invalid
  5690. > - [`~utils.RepositoryNotFoundError`]
  5691. > If the repository to download from cannot be found. This may be because it doesn't exist,
  5692. > or because it is set to `private` and you do not have access.
  5693. """
  5694. if not isinstance(discussion_num, int) or discussion_num <= 0:
  5695. raise ValueError("Invalid discussion_num, must be a positive integer")
  5696. if repo_type not in constants.REPO_TYPES:
  5697. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  5698. if repo_type is None:
  5699. repo_type = constants.REPO_TYPE_MODEL
  5700. path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions/{discussion_num}"
  5701. headers = self._build_hf_headers(token=token)
  5702. resp = get_session().get(path, params={"diff": "1"}, headers=headers)
  5703. hf_raise_for_status(resp)
  5704. discussion_details = resp.json()
  5705. is_pull_request = discussion_details["isPullRequest"]
  5706. target_branch = discussion_details["changes"]["base"] if is_pull_request else None
  5707. conflicting_files = discussion_details["filesWithConflicts"] if is_pull_request else None
  5708. merge_commit_oid = discussion_details["changes"].get("mergeCommitId", None) if is_pull_request else None
  5709. return DiscussionWithDetails(
  5710. title=discussion_details["title"],
  5711. num=discussion_details["num"],
  5712. author=discussion_details.get("author", {}).get("name", "deleted"),
  5713. created_at=parse_datetime(discussion_details["createdAt"]),
  5714. status=discussion_details["status"],
  5715. repo_id=discussion_details["repo"]["name"],
  5716. repo_type=discussion_details["repo"]["type"],
  5717. is_pull_request=discussion_details["isPullRequest"],
  5718. events=[deserialize_event(evt) for evt in discussion_details["events"]],
  5719. conflicting_files=conflicting_files,
  5720. target_branch=target_branch,
  5721. merge_commit_oid=merge_commit_oid,
  5722. diff=discussion_details.get("diff"),
  5723. endpoint=self.endpoint,
  5724. )
  5725. @validate_hf_hub_args
  5726. def create_discussion(
  5727. self,
  5728. repo_id: str,
  5729. title: str,
  5730. *,
  5731. token: Union[bool, str, None] = None,
  5732. description: Optional[str] = None,
  5733. repo_type: Optional[str] = None,
  5734. pull_request: bool = False,
  5735. ) -> DiscussionWithDetails:
  5736. """Creates a Discussion or Pull Request.
  5737. Pull Requests created programmatically will be in `"draft"` status.
  5738. Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`].
  5739. Args:
  5740. repo_id (`str`):
  5741. A namespace (user or an organization) and a repo name separated
  5742. by a `/`.
  5743. title (`str`):
  5744. The title of the discussion. It can be up to 200 characters long,
  5745. and must be at least 3 characters long. Leading and trailing whitespaces
  5746. will be stripped.
  5747. token (`bool` or `str`, *optional*):
  5748. A valid user access token (string). Defaults to the locally saved
  5749. token, which is the recommended method for authentication (see
  5750. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5751. To disable authentication, pass `False`.
  5752. description (`str`, *optional*):
  5753. An optional description for the Pull Request.
  5754. Defaults to `"Discussion opened with the huggingface_hub Python library"`
  5755. pull_request (`bool`, *optional*):
  5756. Whether to create a Pull Request or discussion. If `True`, creates a Pull Request.
  5757. If `False`, creates a discussion. Defaults to `False`.
  5758. repo_type (`str`, *optional*):
  5759. Set to `"dataset"` or `"space"` if uploading to a dataset or
  5760. space, `None` or `"model"` if uploading to a model. Default is
  5761. `None`.
  5762. Returns: [`DiscussionWithDetails`]
  5763. > [!TIP]
  5764. > Raises the following errors:
  5765. >
  5766. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  5767. > if the HuggingFace API returned an error
  5768. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5769. > if some parameter value is invalid
  5770. > - [`~utils.RepositoryNotFoundError`]
  5771. > If the repository to download from cannot be found. This may be because it doesn't exist,
  5772. > or because it is set to `private` and you do not have access."""
  5773. if repo_type not in constants.REPO_TYPES:
  5774. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  5775. if repo_type is None:
  5776. repo_type = constants.REPO_TYPE_MODEL
  5777. if description is not None:
  5778. description = description.strip()
  5779. description = (
  5780. description
  5781. if description
  5782. else (
  5783. f"{'Pull Request' if pull_request else 'Discussion'} opened with the"
  5784. " [huggingface_hub Python"
  5785. " library](https://huggingface.co/docs/huggingface_hub)"
  5786. )
  5787. )
  5788. headers = self._build_hf_headers(token=token)
  5789. resp = get_session().post(
  5790. f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions",
  5791. json={
  5792. "title": title.strip(),
  5793. "description": description,
  5794. "pullRequest": pull_request,
  5795. },
  5796. headers=headers,
  5797. )
  5798. hf_raise_for_status(resp)
  5799. num = resp.json()["num"]
  5800. return self.get_discussion_details(
  5801. repo_id=repo_id,
  5802. repo_type=repo_type,
  5803. discussion_num=num,
  5804. token=token,
  5805. )
  5806. @validate_hf_hub_args
  5807. def create_pull_request(
  5808. self,
  5809. repo_id: str,
  5810. title: str,
  5811. *,
  5812. token: Union[bool, str, None] = None,
  5813. description: Optional[str] = None,
  5814. repo_type: Optional[str] = None,
  5815. ) -> DiscussionWithDetails:
  5816. """Creates a Pull Request . Pull Requests created programmatically will be in `"draft"` status.
  5817. Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`];
  5818. This is a wrapper around [`HfApi.create_discussion`].
  5819. Args:
  5820. repo_id (`str`):
  5821. A namespace (user or an organization) and a repo name separated
  5822. by a `/`.
  5823. title (`str`):
  5824. The title of the discussion. It can be up to 200 characters long,
  5825. and must be at least 3 characters long. Leading and trailing whitespaces
  5826. will be stripped.
  5827. token (`bool` or `str`, *optional*):
  5828. A valid user access token (string). Defaults to the locally saved
  5829. token, which is the recommended method for authentication (see
  5830. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5831. To disable authentication, pass `False`.
  5832. description (`str`, *optional*):
  5833. An optional description for the Pull Request.
  5834. Defaults to `"Discussion opened with the huggingface_hub Python library"`
  5835. repo_type (`str`, *optional*):
  5836. Set to `"dataset"` or `"space"` if uploading to a dataset or
  5837. space, `None` or `"model"` if uploading to a model. Default is
  5838. `None`.
  5839. Returns: [`DiscussionWithDetails`]
  5840. > [!TIP]
  5841. > Raises the following errors:
  5842. >
  5843. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  5844. > if the HuggingFace API returned an error
  5845. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5846. > if some parameter value is invalid
  5847. > - [`~utils.RepositoryNotFoundError`]
  5848. > If the repository to download from cannot be found. This may be because it doesn't exist,
  5849. > or because it is set to `private` and you do not have access."""
  5850. return self.create_discussion(
  5851. repo_id=repo_id,
  5852. title=title,
  5853. token=token,
  5854. description=description,
  5855. repo_type=repo_type,
  5856. pull_request=True,
  5857. )
  5858. def _post_discussion_changes(
  5859. self,
  5860. *,
  5861. repo_id: str,
  5862. discussion_num: int,
  5863. resource: str,
  5864. body: Optional[dict] = None,
  5865. token: Union[bool, str, None] = None,
  5866. repo_type: Optional[str] = None,
  5867. ) -> httpx.Response:
  5868. """Internal utility to POST changes to a Discussion or Pull Request"""
  5869. if not isinstance(discussion_num, int) or discussion_num <= 0:
  5870. raise ValueError("Invalid discussion_num, must be a positive integer")
  5871. if repo_type not in constants.REPO_TYPES:
  5872. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  5873. if repo_type is None:
  5874. repo_type = constants.REPO_TYPE_MODEL
  5875. repo_id = f"{repo_type}s/{repo_id}"
  5876. path = f"{self.endpoint}/api/{repo_id}/discussions/{discussion_num}/{resource}"
  5877. headers = self._build_hf_headers(token=token)
  5878. resp = get_session().post(path, headers=headers, json=body)
  5879. hf_raise_for_status(resp)
  5880. return resp
  5881. @validate_hf_hub_args
  5882. def comment_discussion(
  5883. self,
  5884. repo_id: str,
  5885. discussion_num: int,
  5886. comment: str,
  5887. *,
  5888. token: Union[bool, str, None] = None,
  5889. repo_type: Optional[str] = None,
  5890. ) -> DiscussionComment:
  5891. """Creates a new comment on the given Discussion.
  5892. Args:
  5893. repo_id (`str`):
  5894. A namespace (user or an organization) and a repo name separated
  5895. by a `/`.
  5896. discussion_num (`int`):
  5897. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  5898. comment (`str`):
  5899. The content of the comment to create. Comments support markdown formatting.
  5900. repo_type (`str`, *optional*):
  5901. Set to `"dataset"` or `"space"` if uploading to a dataset or
  5902. space, `None` or `"model"` if uploading to a model. Default is
  5903. `None`.
  5904. token (`bool` or `str`, *optional*):
  5905. A valid user access token (string). Defaults to the locally saved
  5906. token, which is the recommended method for authentication (see
  5907. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5908. To disable authentication, pass `False`.
  5909. Returns:
  5910. [`DiscussionComment`]: the newly created comment
  5911. Examples:
  5912. ```python
  5913. >>> comment = \"\"\"
  5914. ... Hello @otheruser!
  5915. ...
  5916. ... # This is a title
  5917. ...
  5918. ... **This is bold**, *this is italic* and ~this is strikethrough~
  5919. ... And [this](http://url) is a link
  5920. ... \"\"\"
  5921. >>> HfApi().comment_discussion(
  5922. ... repo_id="username/repo_name",
  5923. ... discussion_num=34
  5924. ... comment=comment
  5925. ... )
  5926. # DiscussionComment(id='deadbeef0000000', type='comment', ...)
  5927. ```
  5928. > [!TIP]
  5929. > Raises the following errors:
  5930. >
  5931. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  5932. > if the HuggingFace API returned an error
  5933. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5934. > if some parameter value is invalid
  5935. > - [`~utils.RepositoryNotFoundError`]
  5936. > If the repository to download from cannot be found. This may be because it doesn't exist,
  5937. > or because it is set to `private` and you do not have access.
  5938. """
  5939. resp = self._post_discussion_changes(
  5940. repo_id=repo_id,
  5941. repo_type=repo_type,
  5942. discussion_num=discussion_num,
  5943. token=token,
  5944. resource="comment",
  5945. body={"comment": comment},
  5946. )
  5947. return deserialize_event(resp.json()["newMessage"]) # type: ignore
  5948. @validate_hf_hub_args
  5949. def rename_discussion(
  5950. self,
  5951. repo_id: str,
  5952. discussion_num: int,
  5953. new_title: str,
  5954. *,
  5955. token: Union[bool, str, None] = None,
  5956. repo_type: Optional[str] = None,
  5957. ) -> DiscussionTitleChange:
  5958. """Renames a Discussion.
  5959. Args:
  5960. repo_id (`str`):
  5961. A namespace (user or an organization) and a repo name separated
  5962. by a `/`.
  5963. discussion_num (`int`):
  5964. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  5965. new_title (`str`):
  5966. The new title for the discussion
  5967. repo_type (`str`, *optional*):
  5968. Set to `"dataset"` or `"space"` if uploading to a dataset or
  5969. space, `None` or `"model"` if uploading to a model. Default is
  5970. `None`.
  5971. token (`bool` or `str`, *optional*):
  5972. A valid user access token (string). Defaults to the locally saved
  5973. token, which is the recommended method for authentication (see
  5974. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5975. To disable authentication, pass `False`.
  5976. Returns:
  5977. [`DiscussionTitleChange`]: the title change event
  5978. Examples:
  5979. ```python
  5980. >>> new_title = "New title, fixing a typo"
  5981. >>> HfApi().rename_discussion(
  5982. ... repo_id="username/repo_name",
  5983. ... discussion_num=34
  5984. ... new_title=new_title
  5985. ... )
  5986. # DiscussionTitleChange(id='deadbeef0000000', type='title-change', ...)
  5987. ```
  5988. > [!TIP]
  5989. > Raises the following errors:
  5990. >
  5991. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  5992. > if the HuggingFace API returned an error
  5993. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5994. > if some parameter value is invalid
  5995. > - [`~utils.RepositoryNotFoundError`]
  5996. > If the repository to download from cannot be found. This may be because it doesn't exist,
  5997. > or because it is set to `private` and you do not have access.
  5998. """
  5999. resp = self._post_discussion_changes(
  6000. repo_id=repo_id,
  6001. repo_type=repo_type,
  6002. discussion_num=discussion_num,
  6003. token=token,
  6004. resource="title",
  6005. body={"title": new_title},
  6006. )
  6007. return deserialize_event(resp.json()["newTitle"]) # type: ignore
  6008. @validate_hf_hub_args
  6009. def change_discussion_status(
  6010. self,
  6011. repo_id: str,
  6012. discussion_num: int,
  6013. new_status: Literal["open", "closed"],
  6014. *,
  6015. token: Union[bool, str, None] = None,
  6016. comment: Optional[str] = None,
  6017. repo_type: Optional[str] = None,
  6018. ) -> DiscussionStatusChange:
  6019. """Closes or re-opens a Discussion or Pull Request.
  6020. Args:
  6021. repo_id (`str`):
  6022. A namespace (user or an organization) and a repo name separated
  6023. by a `/`.
  6024. discussion_num (`int`):
  6025. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6026. new_status (`str`):
  6027. The new status for the discussion, either `"open"` or `"closed"`.
  6028. comment (`str`, *optional*):
  6029. An optional comment to post with the status change.
  6030. repo_type (`str`, *optional*):
  6031. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6032. space, `None` or `"model"` if uploading to a model. Default is
  6033. `None`.
  6034. token (`bool` or `str`, *optional*):
  6035. A valid user access token (string). Defaults to the locally saved
  6036. token, which is the recommended method for authentication (see
  6037. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6038. To disable authentication, pass `False`.
  6039. Returns:
  6040. [`DiscussionStatusChange`]: the status change event
  6041. Examples:
  6042. ```python
  6043. >>> new_title = "New title, fixing a typo"
  6044. >>> HfApi().rename_discussion(
  6045. ... repo_id="username/repo_name",
  6046. ... discussion_num=34
  6047. ... new_title=new_title
  6048. ... )
  6049. # DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...)
  6050. ```
  6051. > [!TIP]
  6052. > Raises the following errors:
  6053. >
  6054. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6055. > if the HuggingFace API returned an error
  6056. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6057. > if some parameter value is invalid
  6058. > - [`~utils.RepositoryNotFoundError`]
  6059. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6060. > or because it is set to `private` and you do not have access.
  6061. """
  6062. if new_status not in ["open", "closed"]:
  6063. raise ValueError("Invalid status, valid statuses are: 'open' and 'closed'")
  6064. body: dict[str, str] = {"status": new_status}
  6065. if comment and comment.strip():
  6066. body["comment"] = comment.strip()
  6067. resp = self._post_discussion_changes(
  6068. repo_id=repo_id,
  6069. repo_type=repo_type,
  6070. discussion_num=discussion_num,
  6071. token=token,
  6072. resource="status",
  6073. body=body,
  6074. )
  6075. return deserialize_event(resp.json()["newStatus"]) # type: ignore
  6076. @validate_hf_hub_args
  6077. def merge_pull_request(
  6078. self,
  6079. repo_id: str,
  6080. discussion_num: int,
  6081. *,
  6082. token: Union[bool, str, None] = None,
  6083. comment: Optional[str] = None,
  6084. repo_type: Optional[str] = None,
  6085. ):
  6086. """Merges a Pull Request.
  6087. Args:
  6088. repo_id (`str`):
  6089. A namespace (user or an organization) and a repo name separated
  6090. by a `/`.
  6091. discussion_num (`int`):
  6092. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6093. comment (`str`, *optional*):
  6094. An optional comment to post with the status change.
  6095. repo_type (`str`, *optional*):
  6096. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6097. space, `None` or `"model"` if uploading to a model. Default is
  6098. `None`.
  6099. token (`bool` or `str`, *optional*):
  6100. A valid user access token (string). Defaults to the locally saved
  6101. token, which is the recommended method for authentication (see
  6102. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6103. To disable authentication, pass `False`.
  6104. Returns:
  6105. [`DiscussionStatusChange`]: the status change event
  6106. > [!TIP]
  6107. > Raises the following errors:
  6108. >
  6109. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6110. > if the HuggingFace API returned an error
  6111. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6112. > if some parameter value is invalid
  6113. > - [`~utils.RepositoryNotFoundError`]
  6114. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6115. > or because it is set to `private` and you do not have access.
  6116. """
  6117. self._post_discussion_changes(
  6118. repo_id=repo_id,
  6119. repo_type=repo_type,
  6120. discussion_num=discussion_num,
  6121. token=token,
  6122. resource="merge",
  6123. body={"comment": comment.strip()} if comment and comment.strip() else None,
  6124. )
  6125. @validate_hf_hub_args
  6126. def edit_discussion_comment(
  6127. self,
  6128. repo_id: str,
  6129. discussion_num: int,
  6130. comment_id: str,
  6131. new_content: str,
  6132. *,
  6133. token: Union[bool, str, None] = None,
  6134. repo_type: Optional[str] = None,
  6135. ) -> DiscussionComment:
  6136. """Edits a comment on a Discussion / Pull Request.
  6137. Args:
  6138. repo_id (`str`):
  6139. A namespace (user or an organization) and a repo name separated
  6140. by a `/`.
  6141. discussion_num (`int`):
  6142. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6143. comment_id (`str`):
  6144. The ID of the comment to edit.
  6145. new_content (`str`):
  6146. The new content of the comment. Comments support markdown formatting.
  6147. repo_type (`str`, *optional*):
  6148. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6149. space, `None` or `"model"` if uploading to a model. Default is
  6150. `None`.
  6151. token (`bool` or `str`, *optional*):
  6152. A valid user access token (string). Defaults to the locally saved
  6153. token, which is the recommended method for authentication (see
  6154. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6155. To disable authentication, pass `False`.
  6156. Returns:
  6157. [`DiscussionComment`]: the edited comment
  6158. > [!TIP]
  6159. > Raises the following errors:
  6160. >
  6161. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6162. > if the HuggingFace API returned an error
  6163. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6164. > if some parameter value is invalid
  6165. > - [`~utils.RepositoryNotFoundError`]
  6166. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6167. > or because it is set to `private` and you do not have access.
  6168. """
  6169. resp = self._post_discussion_changes(
  6170. repo_id=repo_id,
  6171. repo_type=repo_type,
  6172. discussion_num=discussion_num,
  6173. token=token,
  6174. resource=f"comment/{comment_id.lower()}/edit",
  6175. body={"content": new_content},
  6176. )
  6177. return deserialize_event(resp.json()["updatedComment"]) # type: ignore
  6178. @validate_hf_hub_args
  6179. def hide_discussion_comment(
  6180. self,
  6181. repo_id: str,
  6182. discussion_num: int,
  6183. comment_id: str,
  6184. *,
  6185. token: Union[bool, str, None] = None,
  6186. repo_type: Optional[str] = None,
  6187. ) -> DiscussionComment:
  6188. """Hides a comment on a Discussion / Pull Request.
  6189. > [!WARNING]
  6190. > Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.
  6191. Args:
  6192. repo_id (`str`):
  6193. A namespace (user or an organization) and a repo name separated
  6194. by a `/`.
  6195. discussion_num (`int`):
  6196. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6197. comment_id (`str`):
  6198. The ID of the comment to edit.
  6199. repo_type (`str`, *optional*):
  6200. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6201. space, `None` or `"model"` if uploading to a model. Default is
  6202. `None`.
  6203. token (`bool` or `str`, *optional*):
  6204. A valid user access token (string). Defaults to the locally saved
  6205. token, which is the recommended method for authentication (see
  6206. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6207. To disable authentication, pass `False`.
  6208. Returns:
  6209. [`DiscussionComment`]: the hidden comment
  6210. > [!TIP]
  6211. > Raises the following errors:
  6212. >
  6213. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6214. > if the HuggingFace API returned an error
  6215. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6216. > if some parameter value is invalid
  6217. > - [`~utils.RepositoryNotFoundError`]
  6218. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6219. > or because it is set to `private` and you do not have access.
  6220. """
  6221. warnings.warn(
  6222. "Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.",
  6223. UserWarning,
  6224. )
  6225. resp = self._post_discussion_changes(
  6226. repo_id=repo_id,
  6227. repo_type=repo_type,
  6228. discussion_num=discussion_num,
  6229. token=token,
  6230. resource=f"comment/{comment_id.lower()}/hide",
  6231. )
  6232. return deserialize_event(resp.json()["updatedComment"]) # type: ignore
  6233. @validate_hf_hub_args
  6234. def add_space_secret(
  6235. self,
  6236. repo_id: str,
  6237. key: str,
  6238. value: str,
  6239. *,
  6240. description: Optional[str] = None,
  6241. token: Union[bool, str, None] = None,
  6242. ) -> None:
  6243. """Adds or updates a secret in a Space.
  6244. Secrets allow to set secret keys or tokens to a Space without hardcoding them.
  6245. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  6246. Args:
  6247. repo_id (`str`):
  6248. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6249. key (`str`):
  6250. Secret key. Example: `"GITHUB_API_KEY"`
  6251. value (`str`):
  6252. Secret value. Example: `"your_github_api_key"`.
  6253. description (`str`, *optional*):
  6254. Secret description. Example: `"Github API key to access the Github API"`.
  6255. token (`bool` or `str`, *optional*):
  6256. A valid user access token (string). Defaults to the locally saved
  6257. token, which is the recommended method for authentication (see
  6258. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6259. To disable authentication, pass `False`.
  6260. """
  6261. payload = {"key": key, "value": value}
  6262. if description is not None:
  6263. payload["description"] = description
  6264. r = get_session().post(
  6265. f"{self.endpoint}/api/spaces/{repo_id}/secrets",
  6266. headers=self._build_hf_headers(token=token),
  6267. json=payload,
  6268. )
  6269. hf_raise_for_status(r)
  6270. @validate_hf_hub_args
  6271. def delete_space_secret(self, repo_id: str, key: str, *, token: Union[bool, str, None] = None) -> None:
  6272. """Deletes a secret from a Space.
  6273. Secrets allow to set secret keys or tokens to a Space without hardcoding them.
  6274. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  6275. Args:
  6276. repo_id (`str`):
  6277. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6278. key (`str`):
  6279. Secret key. Example: `"GITHUB_API_KEY"`.
  6280. token (`bool` or `str`, *optional*):
  6281. A valid user access token (string). Defaults to the locally saved
  6282. token, which is the recommended method for authentication (see
  6283. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6284. To disable authentication, pass `False`.
  6285. """
  6286. r = get_session().request(
  6287. "DELETE",
  6288. f"{self.endpoint}/api/spaces/{repo_id}/secrets",
  6289. headers=self._build_hf_headers(token=token),
  6290. json={"key": key},
  6291. )
  6292. hf_raise_for_status(r)
  6293. @validate_hf_hub_args
  6294. def get_space_variables(self, repo_id: str, *, token: Union[bool, str, None] = None) -> dict[str, SpaceVariable]:
  6295. """Gets all variables from a Space.
  6296. Variables allow to set environment variables to a Space without hardcoding them.
  6297. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
  6298. Args:
  6299. repo_id (`str`):
  6300. ID of the repo to query. Example: `"bigcode/in-the-stack"`.
  6301. token (`bool` or `str`, *optional*):
  6302. A valid user access token (string). Defaults to the locally saved
  6303. token, which is the recommended method for authentication (see
  6304. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6305. To disable authentication, pass `False`.
  6306. """
  6307. r = get_session().get(
  6308. f"{self.endpoint}/api/spaces/{repo_id}/variables",
  6309. headers=self._build_hf_headers(token=token),
  6310. )
  6311. hf_raise_for_status(r)
  6312. return {k: SpaceVariable(k, v) for k, v in r.json().items()}
  6313. @validate_hf_hub_args
  6314. def add_space_variable(
  6315. self,
  6316. repo_id: str,
  6317. key: str,
  6318. value: str,
  6319. *,
  6320. description: Optional[str] = None,
  6321. token: Union[bool, str, None] = None,
  6322. ) -> dict[str, SpaceVariable]:
  6323. """Adds or updates a variable in a Space.
  6324. Variables allow to set environment variables to a Space without hardcoding them.
  6325. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
  6326. Args:
  6327. repo_id (`str`):
  6328. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6329. key (`str`):
  6330. Variable key. Example: `"MODEL_REPO_ID"`
  6331. value (`str`):
  6332. Variable value. Example: `"the_model_repo_id"`.
  6333. description (`str`):
  6334. Description of the variable. Example: `"Model Repo ID of the implemented model"`.
  6335. token (`bool` or `str`, *optional*):
  6336. A valid user access token (string). Defaults to the locally saved
  6337. token, which is the recommended method for authentication (see
  6338. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6339. To disable authentication, pass `False`.
  6340. """
  6341. payload = {"key": key, "value": value}
  6342. if description is not None:
  6343. payload["description"] = description
  6344. r = get_session().post(
  6345. f"{self.endpoint}/api/spaces/{repo_id}/variables",
  6346. headers=self._build_hf_headers(token=token),
  6347. json=payload,
  6348. )
  6349. hf_raise_for_status(r)
  6350. return {k: SpaceVariable(k, v) for k, v in r.json().items()}
  6351. @validate_hf_hub_args
  6352. def delete_space_variable(
  6353. self, repo_id: str, key: str, *, token: Union[bool, str, None] = None
  6354. ) -> dict[str, SpaceVariable]:
  6355. """Deletes a variable from a Space.
  6356. Variables allow to set environment variables to a Space without hardcoding them.
  6357. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
  6358. Args:
  6359. repo_id (`str`):
  6360. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6361. key (`str`):
  6362. Variable key. Example: `"MODEL_REPO_ID"`
  6363. token (`bool` or `str`, *optional*):
  6364. A valid user access token (string). Defaults to the locally saved
  6365. token, which is the recommended method for authentication (see
  6366. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6367. To disable authentication, pass `False`.
  6368. """
  6369. r = get_session().request(
  6370. "DELETE",
  6371. f"{self.endpoint}/api/spaces/{repo_id}/variables",
  6372. headers=self._build_hf_headers(token=token),
  6373. json={"key": key},
  6374. )
  6375. hf_raise_for_status(r)
  6376. return {k: SpaceVariable(k, v) for k, v in r.json().items()}
  6377. @validate_hf_hub_args
  6378. def get_space_runtime(self, repo_id: str, *, token: Union[bool, str, None] = None) -> SpaceRuntime:
  6379. """Gets runtime information about a Space.
  6380. Args:
  6381. repo_id (`str`):
  6382. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6383. token (`bool` or `str`, *optional*):
  6384. A valid user access token (string). Defaults to the locally saved
  6385. token, which is the recommended method for authentication (see
  6386. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6387. To disable authentication, pass `False`.
  6388. Returns:
  6389. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  6390. """
  6391. r = get_session().get(
  6392. f"{self.endpoint}/api/spaces/{repo_id}/runtime", headers=self._build_hf_headers(token=token)
  6393. )
  6394. hf_raise_for_status(r)
  6395. return SpaceRuntime(r.json())
  6396. @validate_hf_hub_args
  6397. def request_space_hardware(
  6398. self,
  6399. repo_id: str,
  6400. hardware: SpaceHardware,
  6401. *,
  6402. token: Union[bool, str, None] = None,
  6403. sleep_time: Optional[int] = None,
  6404. ) -> SpaceRuntime:
  6405. """Request new hardware for a Space.
  6406. Args:
  6407. repo_id (`str`):
  6408. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6409. hardware (`str` or [`SpaceHardware`]):
  6410. Hardware on which to run the Space. Example: `"t4-medium"`.
  6411. token (`bool` or `str`, *optional*):
  6412. A valid user access token (string). Defaults to the locally saved
  6413. token, which is the recommended method for authentication (see
  6414. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6415. To disable authentication, pass `False`.
  6416. sleep_time (`int`, *optional*):
  6417. Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
  6418. your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
  6419. the sleep time (value is fixed to 48 hours of inactivity).
  6420. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  6421. Returns:
  6422. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  6423. > [!TIP]
  6424. > It is also possible to request hardware directly when creating the Space repo! See [`create_repo`] for details.
  6425. """
  6426. if sleep_time is not None and hardware == SpaceHardware.CPU_BASIC:
  6427. warnings.warn(
  6428. "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
  6429. " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
  6430. " you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
  6431. UserWarning,
  6432. )
  6433. payload: dict[str, Any] = {"flavor": hardware}
  6434. if sleep_time is not None:
  6435. payload["sleepTimeSeconds"] = sleep_time
  6436. r = get_session().post(
  6437. f"{self.endpoint}/api/spaces/{repo_id}/hardware",
  6438. headers=self._build_hf_headers(token=token),
  6439. json=payload,
  6440. )
  6441. hf_raise_for_status(r)
  6442. return SpaceRuntime(r.json())
  6443. @validate_hf_hub_args
  6444. def set_space_sleep_time(
  6445. self, repo_id: str, sleep_time: int, *, token: Union[bool, str, None] = None
  6446. ) -> SpaceRuntime:
  6447. """Set a custom sleep time for a Space running on upgraded hardware..
  6448. Your Space will go to sleep after X seconds of inactivity. You are not billed when your Space is in "sleep"
  6449. mode. If a new visitor lands on your Space, it will "wake it up". Only upgraded hardware can have a
  6450. configurable sleep time. To know more about the sleep stage, please refer to
  6451. https://huggingface.co/docs/hub/spaces-gpus#sleep-time.
  6452. Args:
  6453. repo_id (`str`):
  6454. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6455. sleep_time (`int`, *optional*):
  6456. Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
  6457. your Space to pause (default behavior for upgraded hardware). For free hardware, you can't configure
  6458. the sleep time (value is fixed to 48 hours of inactivity).
  6459. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  6460. token (`bool` or `str`, *optional*):
  6461. A valid user access token (string). Defaults to the locally saved
  6462. token, which is the recommended method for authentication (see
  6463. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6464. To disable authentication, pass `False`.
  6465. Returns:
  6466. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  6467. > [!TIP]
  6468. > It is also possible to set a custom sleep time when requesting hardware with [`request_space_hardware`].
  6469. """
  6470. r = get_session().post(
  6471. f"{self.endpoint}/api/spaces/{repo_id}/sleeptime",
  6472. headers=self._build_hf_headers(token=token),
  6473. json={"seconds": sleep_time},
  6474. )
  6475. hf_raise_for_status(r)
  6476. runtime = SpaceRuntime(r.json())
  6477. hardware = runtime.requested_hardware or runtime.hardware
  6478. if hardware == SpaceHardware.CPU_BASIC:
  6479. warnings.warn(
  6480. "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
  6481. " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
  6482. " you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
  6483. UserWarning,
  6484. )
  6485. return runtime
  6486. @validate_hf_hub_args
  6487. def pause_space(self, repo_id: str, *, token: Union[bool, str, None] = None) -> SpaceRuntime:
  6488. """Pause your Space.
  6489. A paused Space stops executing until manually restarted by its owner. This is different from the sleeping
  6490. state in which free Spaces go after 48h of inactivity. Paused time is not billed to your account, no matter the
  6491. hardware you've selected. To restart your Space, use [`restart_space`] and go to your Space settings page.
  6492. For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause).
  6493. Args:
  6494. repo_id (`str`):
  6495. ID of the Space to pause. Example: `"Salesforce/BLIP2"`.
  6496. token (`bool` or `str`, *optional*):
  6497. A valid user access token (string). Defaults to the locally saved
  6498. token, which is the recommended method for authentication (see
  6499. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6500. To disable authentication, pass `False`.
  6501. Returns:
  6502. [`SpaceRuntime`]: Runtime information about your Space including `stage=PAUSED` and requested hardware.
  6503. Raises:
  6504. [`~utils.RepositoryNotFoundError`]:
  6505. If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
  6506. are not authenticated.
  6507. [`~utils.HfHubHTTPError`]:
  6508. 403 Forbidden: only the owner of a Space can pause it. If you want to manage a Space that you don't
  6509. own, either ask the owner by opening a Discussion or duplicate the Space.
  6510. [`~utils.BadRequestError`]:
  6511. If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
  6512. a static Space, you can set it to private.
  6513. """
  6514. r = get_session().post(
  6515. f"{self.endpoint}/api/spaces/{repo_id}/pause", headers=self._build_hf_headers(token=token)
  6516. )
  6517. hf_raise_for_status(r)
  6518. return SpaceRuntime(r.json())
  6519. @validate_hf_hub_args
  6520. def restart_space(
  6521. self, repo_id: str, *, token: Union[bool, str, None] = None, factory_reboot: bool = False
  6522. ) -> SpaceRuntime:
  6523. """Restart your Space.
  6524. This is the only way to programmatically restart a Space if you've put it on Pause (see [`pause_space`]). You
  6525. must be the owner of the Space to restart it. If you are using an upgraded hardware, your account will be
  6526. billed as soon as the Space is restarted. You can trigger a restart no matter the current state of a Space.
  6527. For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause).
  6528. Args:
  6529. repo_id (`str`):
  6530. ID of the Space to restart. Example: `"Salesforce/BLIP2"`.
  6531. token (`bool` or `str`, *optional*):
  6532. A valid user access token (string). Defaults to the locally saved
  6533. token, which is the recommended method for authentication (see
  6534. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6535. To disable authentication, pass `False`.
  6536. factory_reboot (`bool`, *optional*):
  6537. If `True`, the Space will be rebuilt from scratch without caching any requirements.
  6538. Returns:
  6539. [`SpaceRuntime`]: Runtime information about your Space.
  6540. Raises:
  6541. [`~utils.RepositoryNotFoundError`]:
  6542. If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
  6543. are not authenticated.
  6544. [`~utils.HfHubHTTPError`]:
  6545. 403 Forbidden: only the owner of a Space can restart it. If you want to restart a Space that you don't
  6546. own, either ask the owner by opening a Discussion or duplicate the Space.
  6547. [`~utils.BadRequestError`]:
  6548. If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
  6549. a static Space, you can set it to private.
  6550. """
  6551. params = {}
  6552. if factory_reboot:
  6553. params["factory"] = "true"
  6554. r = get_session().post(
  6555. f"{self.endpoint}/api/spaces/{repo_id}/restart", headers=self._build_hf_headers(token=token), params=params
  6556. )
  6557. hf_raise_for_status(r)
  6558. return SpaceRuntime(r.json())
  6559. @validate_hf_hub_args
  6560. def duplicate_space(
  6561. self,
  6562. from_id: str,
  6563. to_id: Optional[str] = None,
  6564. *,
  6565. private: Optional[bool] = None,
  6566. token: Union[bool, str, None] = None,
  6567. exist_ok: bool = False,
  6568. hardware: Optional[SpaceHardware] = None,
  6569. storage: Optional[SpaceStorage] = None,
  6570. sleep_time: Optional[int] = None,
  6571. secrets: Optional[list[dict[str, str]]] = None,
  6572. variables: Optional[list[dict[str, str]]] = None,
  6573. ) -> RepoUrl:
  6574. """Duplicate a Space.
  6575. Programmatically duplicate a Space. The new Space will be created in your account and will be in the same state
  6576. as the original Space (running or paused). You can duplicate a Space no matter the current state of a Space.
  6577. Args:
  6578. from_id (`str`):
  6579. ID of the Space to duplicate. Example: `"pharma/CLIP-Interrogator"`.
  6580. to_id (`str`, *optional*):
  6581. ID of the new Space. Example: `"dog/CLIP-Interrogator"`. If not provided, the new Space will have the same
  6582. name as the original Space, but in your account.
  6583. private (`bool`, *optional*):
  6584. Whether the new Space should be private or not. Defaults to the same privacy as the original Space.
  6585. token (`bool` or `str`, *optional*):
  6586. A valid user access token (string). Defaults to the locally saved
  6587. token, which is the recommended method for authentication (see
  6588. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6589. To disable authentication, pass `False`.
  6590. exist_ok (`bool`, *optional*, defaults to `False`):
  6591. If `True`, do not raise an error if repo already exists.
  6592. hardware (`SpaceHardware` or `str`, *optional*):
  6593. Choice of Hardware. Example: `"t4-medium"`. See [`SpaceHardware`] for a complete list.
  6594. storage (`SpaceStorage` or `str`, *optional*):
  6595. Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
  6596. sleep_time (`int`, *optional*):
  6597. Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
  6598. your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
  6599. the sleep time (value is fixed to 48 hours of inactivity).
  6600. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  6601. secrets (`list[dict[str, str]]`, *optional*):
  6602. A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
  6603. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  6604. variables (`list[dict[str, str]]`, *optional*):
  6605. A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
  6606. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
  6607. Returns:
  6608. [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
  6609. attributes like `endpoint`, `repo_type` and `repo_id`.
  6610. Raises:
  6611. [`~utils.RepositoryNotFoundError`]:
  6612. If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist,
  6613. or because it is set to `private` and you do not have access.
  6614. [`HfHubHTTPError`]:
  6615. If the HuggingFace API returned an error
  6616. Example:
  6617. ```python
  6618. >>> from huggingface_hub import duplicate_space
  6619. # Duplicate a Space to your account
  6620. >>> duplicate_space("multimodalart/dreambooth-training")
  6621. RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)
  6622. # Can set custom destination id and visibility flag.
  6623. >>> duplicate_space("multimodalart/dreambooth-training", to_id="my-dreambooth", private=True)
  6624. RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...)
  6625. ```
  6626. """
  6627. # Parse to_id if provided
  6628. parsed_to_id = RepoUrl(to_id) if to_id is not None else None
  6629. # Infer target repo_id
  6630. to_namespace = ( # set namespace manually or default to username
  6631. parsed_to_id.namespace
  6632. if parsed_to_id is not None and parsed_to_id.namespace is not None
  6633. else self.whoami(token)["name"]
  6634. )
  6635. to_repo_name = parsed_to_id.repo_name if to_id is not None else RepoUrl(from_id).repo_name # type: ignore
  6636. # repository must be a valid repo_id (namespace/repo_name).
  6637. payload: dict[str, Any] = {"repository": f"{to_namespace}/{to_repo_name}"}
  6638. keys = ["private", "hardware", "storageTier", "sleepTimeSeconds", "secrets", "variables"]
  6639. values = [private, hardware, storage, sleep_time, secrets, variables]
  6640. payload.update({k: v for k, v in zip(keys, values) if v is not None})
  6641. if sleep_time is not None and hardware == SpaceHardware.CPU_BASIC:
  6642. warnings.warn(
  6643. "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
  6644. " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
  6645. " you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
  6646. UserWarning,
  6647. )
  6648. r = get_session().post(
  6649. f"{self.endpoint}/api/spaces/{from_id}/duplicate",
  6650. headers=self._build_hf_headers(token=token),
  6651. json=payload,
  6652. )
  6653. try:
  6654. hf_raise_for_status(r)
  6655. except HfHubHTTPError as err:
  6656. if exist_ok and err.response.status_code == 409:
  6657. # Repo already exists and `exist_ok=True`
  6658. pass
  6659. else:
  6660. raise
  6661. return RepoUrl(r.json()["url"], endpoint=self.endpoint)
  6662. @validate_hf_hub_args
  6663. def request_space_storage(
  6664. self,
  6665. repo_id: str,
  6666. storage: SpaceStorage,
  6667. *,
  6668. token: Union[bool, str, None] = None,
  6669. ) -> SpaceRuntime:
  6670. """Request persistent storage for a Space.
  6671. Args:
  6672. repo_id (`str`):
  6673. ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`.
  6674. storage (`str` or [`SpaceStorage`]):
  6675. Storage tier. Either 'small', 'medium', or 'large'.
  6676. token (`bool` or `str`, *optional*):
  6677. A valid user access token (string). Defaults to the locally saved
  6678. token, which is the recommended method for authentication (see
  6679. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6680. To disable authentication, pass `False`.
  6681. Returns:
  6682. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  6683. > [!TIP]
  6684. > It is not possible to decrease persistent storage after its granted. To do so, you must delete it
  6685. > via [`delete_space_storage`].
  6686. """
  6687. payload: dict[str, SpaceStorage] = {"tier": storage}
  6688. r = get_session().post(
  6689. f"{self.endpoint}/api/spaces/{repo_id}/storage",
  6690. headers=self._build_hf_headers(token=token),
  6691. json=payload,
  6692. )
  6693. hf_raise_for_status(r)
  6694. return SpaceRuntime(r.json())
  6695. @validate_hf_hub_args
  6696. def delete_space_storage(
  6697. self,
  6698. repo_id: str,
  6699. *,
  6700. token: Union[bool, str, None] = None,
  6701. ) -> SpaceRuntime:
  6702. """Delete persistent storage for a Space.
  6703. Args:
  6704. repo_id (`str`):
  6705. ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`.
  6706. token (`bool` or `str`, *optional*):
  6707. A valid user access token (string). Defaults to the locally saved
  6708. token, which is the recommended method for authentication (see
  6709. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6710. To disable authentication, pass `False`.
  6711. Returns:
  6712. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  6713. Raises:
  6714. [`BadRequestError`]
  6715. If space has no persistent storage.
  6716. """
  6717. r = get_session().delete(
  6718. f"{self.endpoint}/api/spaces/{repo_id}/storage",
  6719. headers=self._build_hf_headers(token=token),
  6720. )
  6721. hf_raise_for_status(r)
  6722. return SpaceRuntime(r.json())
  6723. #######################
  6724. # Inference Endpoints #
  6725. #######################
  6726. def list_inference_endpoints(
  6727. self, namespace: Optional[str] = None, *, token: Union[bool, str, None] = None
  6728. ) -> list[InferenceEndpoint]:
  6729. """Lists all inference endpoints for the given namespace.
  6730. Args:
  6731. namespace (`str`, *optional*):
  6732. The namespace to list endpoints for. Defaults to the current user. Set to `"*"` to list all endpoints
  6733. from all namespaces (i.e. personal namespace and all orgs the user belongs to).
  6734. token (`bool` or `str`, *optional*):
  6735. A valid user access token (string). Defaults to the locally saved
  6736. token, which is the recommended method for authentication (see
  6737. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6738. To disable authentication, pass `False`.
  6739. Returns:
  6740. list[`InferenceEndpoint`]: A list of all inference endpoints for the given namespace.
  6741. Example:
  6742. ```python
  6743. >>> from huggingface_hub import HfApi
  6744. >>> api = HfApi()
  6745. >>> api.list_inference_endpoints()
  6746. [InferenceEndpoint(name='my-endpoint', ...), ...]
  6747. ```
  6748. """
  6749. # Special case: list all endpoints for all namespaces the user has access to
  6750. if namespace == "*":
  6751. user = self.whoami(token=token)
  6752. # List personal endpoints first
  6753. endpoints: list[InferenceEndpoint] = list_inference_endpoints(namespace=self._get_namespace(token=token))
  6754. # Then list endpoints for all orgs the user belongs to and ignore 401 errors (no billing or no access)
  6755. for org in user.get("orgs", []):
  6756. try:
  6757. endpoints += list_inference_endpoints(namespace=org["name"], token=token)
  6758. except HfHubHTTPError as error:
  6759. if error.response.status_code == 401: # Either no billing or user don't have access)
  6760. logger.debug("Cannot list Inference Endpoints for org '%s': %s", org["name"], error)
  6761. pass
  6762. return endpoints
  6763. # Normal case: list endpoints for a specific namespace
  6764. namespace = namespace or self._get_namespace(token=token)
  6765. response = get_session().get(
  6766. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}",
  6767. headers=self._build_hf_headers(token=token),
  6768. )
  6769. hf_raise_for_status(response)
  6770. return [
  6771. InferenceEndpoint.from_raw(endpoint, namespace=namespace, token=token)
  6772. for endpoint in response.json()["items"]
  6773. ]
  6774. def create_inference_endpoint(
  6775. self,
  6776. name: str,
  6777. *,
  6778. repository: str,
  6779. framework: str,
  6780. accelerator: str,
  6781. instance_size: str,
  6782. instance_type: str,
  6783. region: str,
  6784. vendor: str,
  6785. account_id: Optional[str] = None,
  6786. min_replica: int = 1,
  6787. max_replica: int = 1,
  6788. scaling_metric: Optional[InferenceEndpointScalingMetric] = None,
  6789. scaling_threshold: Optional[float] = None,
  6790. scale_to_zero_timeout: Optional[int] = None,
  6791. revision: Optional[str] = None,
  6792. task: Optional[str] = None,
  6793. custom_image: Optional[dict] = None,
  6794. env: Optional[dict[str, str]] = None,
  6795. secrets: Optional[dict[str, str]] = None,
  6796. type: InferenceEndpointType = InferenceEndpointType.PROTECTED,
  6797. domain: Optional[str] = None,
  6798. path: Optional[str] = None,
  6799. cache_http_responses: Optional[bool] = None,
  6800. tags: Optional[list[str]] = None,
  6801. namespace: Optional[str] = None,
  6802. token: Union[bool, str, None] = None,
  6803. ) -> InferenceEndpoint:
  6804. """Create a new Inference Endpoint.
  6805. Args:
  6806. name (`str`):
  6807. The unique name for the new Inference Endpoint.
  6808. repository (`str`):
  6809. The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
  6810. framework (`str`):
  6811. The machine learning framework used for the model (e.g. `"custom"`).
  6812. accelerator (`str`):
  6813. The hardware accelerator to be used for inference (e.g. `"cpu"`).
  6814. instance_size (`str`):
  6815. The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
  6816. instance_type (`str`):
  6817. The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
  6818. region (`str`):
  6819. The cloud region in which the Inference Endpoint will be created (e.g. `"us-east-1"`).
  6820. vendor (`str`):
  6821. The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. `"aws"`).
  6822. account_id (`str`, *optional*):
  6823. The account ID used to link a VPC to a private Inference Endpoint (if applicable).
  6824. min_replica (`int`, *optional*):
  6825. The minimum number of replicas (instances) to keep running for the Inference Endpoint. To enable
  6826. scaling to zero, set this value to 0 and adjust `scale_to_zero_timeout` accordingly. Defaults to 1.
  6827. max_replica (`int`, *optional*):
  6828. The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to 1.
  6829. scaling_metric (`str` or [`InferenceEndpointScalingMetric `], *optional*):
  6830. The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided. Defaults to
  6831. None (meaning: let the HF Endpoints service specify the metric).
  6832. scaling_threshold (`float`, *optional*):
  6833. The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.
  6834. Defaults to None (meaning: let the HF Endpoints service specify the threshold).
  6835. scale_to_zero_timeout (`int`, *optional*):
  6836. The duration in minutes before an inactive endpoint is scaled to zero, or no scaling to zero if
  6837. set to None and `min_replica` is not 0. Defaults to None.
  6838. revision (`str`, *optional*):
  6839. The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
  6840. task (`str`, *optional*):
  6841. The task on which to deploy the model (e.g. `"text-classification"`).
  6842. custom_image (`dict`, *optional*):
  6843. A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
  6844. Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
  6845. env (`dict[str, str]`, *optional*):
  6846. Non-secret environment variables to inject in the container environment.
  6847. secrets (`dict[str, str]`, *optional*):
  6848. Secret values to inject in the container environment.
  6849. type ([`InferenceEndpointType]`, *optional*):
  6850. The type of the Inference Endpoint, which can be `"protected"` (default), `"public"` or `"private"`.
  6851. domain (`str`, *optional*):
  6852. The custom domain for the Inference Endpoint deployment, if setup the inference endpoint will be available at this domain (e.g. `"my-new-domain.cool-website.woof"`).
  6853. path (`str`, *optional*):
  6854. The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`).
  6855. cache_http_responses (`bool`, *optional*):
  6856. Whether to cache HTTP responses from the Inference Endpoint. Defaults to `False`.
  6857. tags (`list[str]`, *optional*):
  6858. A list of tags to associate with the Inference Endpoint.
  6859. namespace (`str`, *optional*):
  6860. The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.
  6861. token (`bool` or `str`, *optional*):
  6862. A valid user access token (string). Defaults to the locally saved
  6863. token, which is the recommended method for authentication (see
  6864. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6865. To disable authentication, pass `False`.
  6866. Returns:
  6867. [`InferenceEndpoint`]: information about the updated Inference Endpoint.
  6868. Example:
  6869. ```python
  6870. >>> from huggingface_hub import HfApi
  6871. >>> api = HfApi()
  6872. >>> endpoint = api.create_inference_endpoint(
  6873. ... "my-endpoint-name",
  6874. ... repository="gpt2",
  6875. ... framework="pytorch",
  6876. ... task="text-generation",
  6877. ... accelerator="cpu",
  6878. ... vendor="aws",
  6879. ... region="us-east-1",
  6880. ... type="protected",
  6881. ... instance_size="x2",
  6882. ... instance_type="intel-icl",
  6883. ... )
  6884. >>> endpoint
  6885. InferenceEndpoint(name='my-endpoint-name', status="pending",...)
  6886. # Run inference on the endpoint
  6887. >>> endpoint.client.text_generation(...)
  6888. "..."
  6889. ```
  6890. ```python
  6891. # Start an Inference Endpoint running Zephyr-7b-beta on TGI
  6892. >>> from huggingface_hub import HfApi
  6893. >>> api = HfApi()
  6894. >>> endpoint = api.create_inference_endpoint(
  6895. ... "aws-zephyr-7b-beta-0486",
  6896. ... repository="HuggingFaceH4/zephyr-7b-beta",
  6897. ... framework="pytorch",
  6898. ... task="text-generation",
  6899. ... accelerator="gpu",
  6900. ... vendor="aws",
  6901. ... region="us-east-1",
  6902. ... type="protected",
  6903. ... instance_size="x1",
  6904. ... instance_type="nvidia-a10g",
  6905. ... env={
  6906. ... "MAX_BATCH_PREFILL_TOKENS": "2048",
  6907. ... "MAX_INPUT_LENGTH": "1024",
  6908. ... "MAX_TOTAL_TOKENS": "1512",
  6909. ... "MODEL_ID": "/repository"
  6910. ... },
  6911. ... custom_image={
  6912. ... "health_route": "/health",
  6913. ... "url": "ghcr.io/huggingface/text-generation-inference:1.1.0",
  6914. ... },
  6915. ... secrets={"MY_SECRET_KEY": "secret_value"},
  6916. ... tags=["dev", "text-generation"],
  6917. ... )
  6918. ```
  6919. ```python
  6920. # Start an Inference Endpoint running ProsusAI/finbert while scaling to zero in 15 minutes
  6921. >>> from huggingface_hub import HfApi
  6922. >>> api = HfApi()
  6923. >>> endpoint = api.create_inference_endpoint(
  6924. ... "finbert-classifier",
  6925. ... repository="ProsusAI/finbert",
  6926. ... framework="pytorch",
  6927. ... task="text-classification",
  6928. ... min_replica=0,
  6929. ... scale_to_zero_timeout=15,
  6930. ... accelerator="cpu",
  6931. ... vendor="aws",
  6932. ... region="us-east-1",
  6933. ... type="protected",
  6934. ... instance_size="x2",
  6935. ... instance_type="intel-icl",
  6936. ... )
  6937. >>> endpoint.wait(timeout=300)
  6938. # Run inference on the endpoint
  6939. >>> endpoint.client.text_generation(...)
  6940. TextClassificationOutputElement(label='positive', score=0.8983615040779114)
  6941. ```
  6942. """
  6943. namespace = namespace or self._get_namespace(token=token)
  6944. if custom_image is not None:
  6945. image = (
  6946. custom_image
  6947. if next(iter(custom_image)) in constants.INFERENCE_ENDPOINT_IMAGE_KEYS
  6948. else {"custom": custom_image}
  6949. )
  6950. else:
  6951. image = {"huggingface": {}}
  6952. payload: dict = {
  6953. "accountId": account_id,
  6954. "compute": {
  6955. "accelerator": accelerator,
  6956. "instanceSize": instance_size,
  6957. "instanceType": instance_type,
  6958. "scaling": {
  6959. "maxReplica": max_replica,
  6960. "minReplica": min_replica,
  6961. "scaleToZeroTimeout": scale_to_zero_timeout,
  6962. },
  6963. },
  6964. "model": {
  6965. "framework": framework,
  6966. "repository": repository,
  6967. "revision": revision,
  6968. "task": task,
  6969. "image": image,
  6970. },
  6971. "name": name,
  6972. "provider": {
  6973. "region": region,
  6974. "vendor": vendor,
  6975. },
  6976. "type": type,
  6977. }
  6978. if scaling_metric:
  6979. payload["compute"]["scaling"]["measure"] = {scaling_metric: scaling_threshold} # type: ignore
  6980. if env:
  6981. payload["model"]["env"] = env
  6982. if secrets:
  6983. payload["model"]["secrets"] = secrets
  6984. if domain is not None or path is not None:
  6985. payload["route"] = {}
  6986. if domain is not None:
  6987. payload["route"]["domain"] = domain
  6988. if path is not None:
  6989. payload["route"]["path"] = path
  6990. if cache_http_responses is not None:
  6991. payload["cacheHttpResponses"] = cache_http_responses
  6992. if tags is not None:
  6993. payload["tags"] = tags
  6994. response = get_session().post(
  6995. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}",
  6996. headers=self._build_hf_headers(token=token),
  6997. json=payload,
  6998. )
  6999. hf_raise_for_status(response)
  7000. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  7001. @experimental
  7002. @validate_hf_hub_args
  7003. def create_inference_endpoint_from_catalog(
  7004. self,
  7005. repo_id: str,
  7006. *,
  7007. name: Optional[str] = None,
  7008. token: Union[bool, str, None] = None,
  7009. namespace: Optional[str] = None,
  7010. ) -> InferenceEndpoint:
  7011. """Create a new Inference Endpoint from a model in the Hugging Face Inference Catalog.
  7012. The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference
  7013. and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list
  7014. of available models in the catalog.
  7015. Args:
  7016. repo_id (`str`):
  7017. The ID of the model in the catalog to deploy as an Inference Endpoint.
  7018. name (`str`, *optional*):
  7019. The unique name for the new Inference Endpoint. If not provided, a random name will be generated.
  7020. token (`bool` or `str`, *optional*):
  7021. A valid user access token (string). Defaults to the locally saved
  7022. token, which is the recommended method for authentication (see
  7023. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7024. namespace (`str`, *optional*):
  7025. The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.
  7026. Returns:
  7027. [`InferenceEndpoint`]: information about the new Inference Endpoint.
  7028. > [!WARNING]
  7029. > `create_inference_endpoint_from_catalog` is experimental. Its API is subject to change in the future. Please provide feedback
  7030. > if you have any suggestions or requests.
  7031. """
  7032. token = token or self.token or get_token()
  7033. payload: dict = {
  7034. "namespace": namespace or self._get_namespace(token=token),
  7035. "repoId": repo_id,
  7036. }
  7037. if name is not None:
  7038. payload["endpointName"] = name
  7039. response = get_session().post(
  7040. f"{constants.INFERENCE_CATALOG_ENDPOINT}/deploy",
  7041. headers=self._build_hf_headers(token=token),
  7042. json=payload,
  7043. )
  7044. hf_raise_for_status(response)
  7045. data = response.json()["endpoint"]
  7046. return InferenceEndpoint.from_raw(data, namespace=data["name"], token=token)
  7047. @experimental
  7048. @validate_hf_hub_args
  7049. def list_inference_catalog(self, *, token: Union[bool, str, None] = None) -> list[str]:
  7050. """List models available in the Hugging Face Inference Catalog.
  7051. The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference
  7052. and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list
  7053. of available models in the catalog.
  7054. Use [`create_inference_endpoint_from_catalog`] to deploy a model from the catalog.
  7055. Args:
  7056. token (`bool` or `str`, *optional*):
  7057. A valid user access token (string). Defaults to the locally saved
  7058. token, which is the recommended method for authentication (see
  7059. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7060. Returns:
  7061. List[`str`]: A list of model IDs available in the catalog.
  7062. > [!WARNING]
  7063. > `list_inference_catalog` is experimental. Its API is subject to change in the future. Please provide feedback
  7064. > if you have any suggestions or requests.
  7065. """
  7066. response = get_session().get(
  7067. f"{constants.INFERENCE_CATALOG_ENDPOINT}/repo-list",
  7068. headers=self._build_hf_headers(token=token),
  7069. )
  7070. hf_raise_for_status(response)
  7071. return response.json()["models"]
  7072. def get_inference_endpoint(
  7073. self, name: str, *, namespace: Optional[str] = None, token: Union[bool, str, None] = None
  7074. ) -> InferenceEndpoint:
  7075. """Get information about an Inference Endpoint.
  7076. Args:
  7077. name (`str`):
  7078. The name of the Inference Endpoint to retrieve information about.
  7079. namespace (`str`, *optional*):
  7080. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  7081. token (`bool` or `str`, *optional*):
  7082. A valid user access token (string). Defaults to the locally saved
  7083. token, which is the recommended method for authentication (see
  7084. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7085. To disable authentication, pass `False`.
  7086. Returns:
  7087. [`InferenceEndpoint`]: information about the requested Inference Endpoint.
  7088. Example:
  7089. ```python
  7090. >>> from huggingface_hub import HfApi
  7091. >>> api = HfApi()
  7092. >>> endpoint = api.get_inference_endpoint("my-text-to-image")
  7093. >>> endpoint
  7094. InferenceEndpoint(name='my-text-to-image', ...)
  7095. # Get status
  7096. >>> endpoint.status
  7097. 'running'
  7098. >>> endpoint.url
  7099. 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
  7100. # Run inference
  7101. >>> endpoint.client.text_to_image(...)
  7102. ```
  7103. """
  7104. namespace = namespace or self._get_namespace(token=token)
  7105. response = get_session().get(
  7106. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}",
  7107. headers=self._build_hf_headers(token=token),
  7108. )
  7109. hf_raise_for_status(response)
  7110. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  7111. def update_inference_endpoint(
  7112. self,
  7113. name: str,
  7114. *,
  7115. # Compute update
  7116. accelerator: Optional[str] = None,
  7117. instance_size: Optional[str] = None,
  7118. instance_type: Optional[str] = None,
  7119. min_replica: Optional[int] = None,
  7120. max_replica: Optional[int] = None,
  7121. scale_to_zero_timeout: Optional[int] = None,
  7122. scaling_metric: Optional[InferenceEndpointScalingMetric] = None,
  7123. scaling_threshold: Optional[float] = None,
  7124. # Model update
  7125. repository: Optional[str] = None,
  7126. framework: Optional[str] = None,
  7127. revision: Optional[str] = None,
  7128. task: Optional[str] = None,
  7129. custom_image: Optional[dict] = None,
  7130. env: Optional[dict[str, str]] = None,
  7131. secrets: Optional[dict[str, str]] = None,
  7132. # Route update
  7133. domain: Optional[str] = None,
  7134. path: Optional[str] = None,
  7135. # Other
  7136. cache_http_responses: Optional[bool] = None,
  7137. tags: Optional[list[str]] = None,
  7138. namespace: Optional[str] = None,
  7139. token: Union[bool, str, None] = None,
  7140. ) -> InferenceEndpoint:
  7141. """Update an Inference Endpoint.
  7142. This method allows the update of either the compute configuration, the deployed model, the route, or any combination.
  7143. All arguments are optional but at least one must be provided.
  7144. For convenience, you can also update an Inference Endpoint using [`InferenceEndpoint.update`].
  7145. Args:
  7146. name (`str`):
  7147. The name of the Inference Endpoint to update.
  7148. accelerator (`str`, *optional*):
  7149. The hardware accelerator to be used for inference (e.g. `"cpu"`).
  7150. instance_size (`str`, *optional*):
  7151. The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
  7152. instance_type (`str`, *optional*):
  7153. The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
  7154. min_replica (`int`, *optional*):
  7155. The minimum number of replicas (instances) to keep running for the Inference Endpoint.
  7156. max_replica (`int`, *optional*):
  7157. The maximum number of replicas (instances) to scale to for the Inference Endpoint.
  7158. scale_to_zero_timeout (`int`, *optional*):
  7159. The duration in minutes before an inactive endpoint is scaled to zero.
  7160. scaling_metric (`str` or [`InferenceEndpointScalingMetric `], *optional*):
  7161. The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided.
  7162. Defaults to None.
  7163. scaling_threshold (`float`, *optional*):
  7164. The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.
  7165. Defaults to None.
  7166. repository (`str`, *optional*):
  7167. The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
  7168. framework (`str`, *optional*):
  7169. The machine learning framework used for the model (e.g. `"custom"`).
  7170. revision (`str`, *optional*):
  7171. The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
  7172. task (`str`, *optional*):
  7173. The task on which to deploy the model (e.g. `"text-classification"`).
  7174. custom_image (`dict`, *optional*):
  7175. A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
  7176. Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
  7177. env (`dict[str, str]`, *optional*):
  7178. Non-secret environment variables to inject in the container environment
  7179. secrets (`dict[str, str]`, *optional*):
  7180. Secret values to inject in the container environment.
  7181. domain (`str`, *optional*):
  7182. The custom domain for the Inference Endpoint deployment, if setup the inference endpoint will be available at this domain (e.g. `"my-new-domain.cool-website.woof"`).
  7183. path (`str`, *optional*):
  7184. The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`).
  7185. cache_http_responses (`bool`, *optional*):
  7186. Whether to cache HTTP responses from the Inference Endpoint.
  7187. tags (`list[str]`, *optional*):
  7188. A list of tags to associate with the Inference Endpoint.
  7189. namespace (`str`, *optional*):
  7190. The namespace where the Inference Endpoint will be updated. Defaults to the current user's namespace.
  7191. token (`bool` or `str`, *optional*):
  7192. A valid user access token (string). Defaults to the locally saved
  7193. token, which is the recommended method for authentication (see
  7194. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7195. To disable authentication, pass `False`.
  7196. Returns:
  7197. [`InferenceEndpoint`]: information about the updated Inference Endpoint.
  7198. """
  7199. namespace = namespace or self._get_namespace(token=token)
  7200. # Populate only the fields that are not None
  7201. payload: dict = defaultdict(lambda: defaultdict(dict))
  7202. if accelerator is not None:
  7203. payload["compute"]["accelerator"] = accelerator
  7204. if instance_size is not None:
  7205. payload["compute"]["instanceSize"] = instance_size
  7206. if instance_type is not None:
  7207. payload["compute"]["instanceType"] = instance_type
  7208. if max_replica is not None:
  7209. payload["compute"]["scaling"]["maxReplica"] = max_replica
  7210. if min_replica is not None:
  7211. payload["compute"]["scaling"]["minReplica"] = min_replica
  7212. if scale_to_zero_timeout is not None:
  7213. payload["compute"]["scaling"]["scaleToZeroTimeout"] = scale_to_zero_timeout
  7214. if scaling_metric:
  7215. payload["compute"]["scaling"]["measure"] = {scaling_metric: scaling_threshold}
  7216. if repository is not None:
  7217. payload["model"]["repository"] = repository
  7218. if framework is not None:
  7219. payload["model"]["framework"] = framework
  7220. if revision is not None:
  7221. payload["model"]["revision"] = revision
  7222. if task is not None:
  7223. payload["model"]["task"] = task
  7224. if custom_image is not None:
  7225. payload["model"]["image"] = {"custom": custom_image}
  7226. if env is not None:
  7227. payload["model"]["env"] = env
  7228. if secrets is not None:
  7229. payload["model"]["secrets"] = secrets
  7230. if domain is not None:
  7231. payload["route"]["domain"] = domain
  7232. if path is not None:
  7233. payload["route"]["path"] = path
  7234. if cache_http_responses is not None:
  7235. payload["cacheHttpResponses"] = cache_http_responses
  7236. if tags is not None:
  7237. payload["tags"] = tags
  7238. response = get_session().put(
  7239. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}",
  7240. headers=self._build_hf_headers(token=token),
  7241. json=payload,
  7242. )
  7243. hf_raise_for_status(response)
  7244. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  7245. def delete_inference_endpoint(
  7246. self, name: str, *, namespace: Optional[str] = None, token: Union[bool, str, None] = None
  7247. ) -> None:
  7248. """Delete an Inference Endpoint.
  7249. This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
  7250. to pause it with [`pause_inference_endpoint`] or scale it to zero with [`scale_to_zero_inference_endpoint`].
  7251. For convenience, you can also delete an Inference Endpoint using [`InferenceEndpoint.delete`].
  7252. Args:
  7253. name (`str`):
  7254. The name of the Inference Endpoint to delete.
  7255. namespace (`str`, *optional*):
  7256. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  7257. token (`bool` or `str`, *optional*):
  7258. A valid user access token (string). Defaults to the locally saved
  7259. token, which is the recommended method for authentication (see
  7260. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7261. To disable authentication, pass `False`.
  7262. """
  7263. namespace = namespace or self._get_namespace(token=token)
  7264. response = get_session().delete(
  7265. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}",
  7266. headers=self._build_hf_headers(token=token),
  7267. )
  7268. hf_raise_for_status(response)
  7269. def pause_inference_endpoint(
  7270. self, name: str, *, namespace: Optional[str] = None, token: Union[bool, str, None] = None
  7271. ) -> InferenceEndpoint:
  7272. """Pause an Inference Endpoint.
  7273. A paused Inference Endpoint will not be charged. It can be resumed at any time using [`resume_inference_endpoint`].
  7274. This is different than scaling the Inference Endpoint to zero with [`scale_to_zero_inference_endpoint`], which
  7275. would be automatically restarted when a request is made to it.
  7276. For convenience, you can also pause an Inference Endpoint using [`pause_inference_endpoint`].
  7277. Args:
  7278. name (`str`):
  7279. The name of the Inference Endpoint to pause.
  7280. namespace (`str`, *optional*):
  7281. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  7282. token (`bool` or `str`, *optional*):
  7283. A valid user access token (string). Defaults to the locally saved
  7284. token, which is the recommended method for authentication (see
  7285. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7286. To disable authentication, pass `False`.
  7287. Returns:
  7288. [`InferenceEndpoint`]: information about the paused Inference Endpoint.
  7289. """
  7290. namespace = namespace or self._get_namespace(token=token)
  7291. response = get_session().post(
  7292. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/pause",
  7293. headers=self._build_hf_headers(token=token),
  7294. )
  7295. hf_raise_for_status(response)
  7296. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  7297. def resume_inference_endpoint(
  7298. self,
  7299. name: str,
  7300. *,
  7301. namespace: Optional[str] = None,
  7302. running_ok: bool = True,
  7303. token: Union[bool, str, None] = None,
  7304. ) -> InferenceEndpoint:
  7305. """Resume an Inference Endpoint.
  7306. For convenience, you can also resume an Inference Endpoint using [`InferenceEndpoint.resume`].
  7307. Args:
  7308. name (`str`):
  7309. The name of the Inference Endpoint to resume.
  7310. namespace (`str`, *optional*):
  7311. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  7312. running_ok (`bool`, *optional*):
  7313. If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to
  7314. `True`.
  7315. token (`bool` or `str`, *optional*):
  7316. A valid user access token (string). Defaults to the locally saved
  7317. token, which is the recommended method for authentication (see
  7318. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7319. To disable authentication, pass `False`.
  7320. Returns:
  7321. [`InferenceEndpoint`]: information about the resumed Inference Endpoint.
  7322. """
  7323. namespace = namespace or self._get_namespace(token=token)
  7324. response = get_session().post(
  7325. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/resume",
  7326. headers=self._build_hf_headers(token=token),
  7327. )
  7328. try:
  7329. hf_raise_for_status(response)
  7330. except HfHubHTTPError as error:
  7331. # If already running (and it's ok), then fetch current status and return
  7332. if running_ok and error.response.status_code == 400 and "already running" in error.response.text:
  7333. return self.get_inference_endpoint(name, namespace=namespace, token=token)
  7334. # Otherwise, raise the error
  7335. raise
  7336. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  7337. def scale_to_zero_inference_endpoint(
  7338. self, name: str, *, namespace: Optional[str] = None, token: Union[bool, str, None] = None
  7339. ) -> InferenceEndpoint:
  7340. """Scale Inference Endpoint to zero.
  7341. An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a
  7342. cold start delay. This is different than pausing the Inference Endpoint with [`pause_inference_endpoint`], which
  7343. would require a manual resume with [`resume_inference_endpoint`].
  7344. For convenience, you can also scale an Inference Endpoint to zero using [`InferenceEndpoint.scale_to_zero`].
  7345. Args:
  7346. name (`str`):
  7347. The name of the Inference Endpoint to scale to zero.
  7348. namespace (`str`, *optional*):
  7349. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  7350. token (`bool` or `str`, *optional*):
  7351. A valid user access token (string). Defaults to the locally saved
  7352. token, which is the recommended method for authentication (see
  7353. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7354. To disable authentication, pass `False`.
  7355. Returns:
  7356. [`InferenceEndpoint`]: information about the scaled-to-zero Inference Endpoint.
  7357. """
  7358. namespace = namespace or self._get_namespace(token=token)
  7359. response = get_session().post(
  7360. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/scale-to-zero",
  7361. headers=self._build_hf_headers(token=token),
  7362. )
  7363. hf_raise_for_status(response)
  7364. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  7365. def _get_namespace(self, token: Union[bool, str, None] = None) -> str:
  7366. """Get the default namespace for the current user."""
  7367. me = self.whoami(token=token)
  7368. if me["type"] == "user":
  7369. return me["name"]
  7370. else:
  7371. raise ValueError(
  7372. "Cannot determine default namespace. You must provide a 'namespace' as input or be logged in as a"
  7373. " user."
  7374. )
  7375. ########################
  7376. # Collection Endpoints #
  7377. ########################
  7378. @validate_hf_hub_args
  7379. def list_collections(
  7380. self,
  7381. *,
  7382. owner: Union[list[str], str, None] = None,
  7383. item: Union[list[str], str, None] = None,
  7384. sort: Optional[Literal["lastModified", "trending", "upvotes"]] = None,
  7385. limit: Optional[int] = None,
  7386. token: Union[bool, str, None] = None,
  7387. ) -> Iterable[Collection]:
  7388. """List collections on the Huggingface Hub, given some filters.
  7389. > [!WARNING]
  7390. > When listing collections, the item list per collection is truncated to 4 items maximum. To retrieve all items
  7391. > from a collection, you must use [`get_collection`].
  7392. Args:
  7393. owner (`list[str]` or `str`, *optional*):
  7394. Filter by owner's username.
  7395. item (`list[str]` or `str`, *optional*):
  7396. Filter collections containing a particular items. Example: `"models/teknium/OpenHermes-2.5-Mistral-7B"`, `"datasets/squad"` or `"papers/2311.12983"`.
  7397. sort (`Literal["lastModified", "trending", "upvotes"]`, *optional*):
  7398. Sort collections by last modified, trending or upvotes.
  7399. limit (`int`, *optional*):
  7400. Maximum number of collections to be returned.
  7401. token (`bool` or `str`, *optional*):
  7402. A valid user access token (string). Defaults to the locally saved
  7403. token, which is the recommended method for authentication (see
  7404. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7405. To disable authentication, pass `False`.
  7406. Returns:
  7407. `Iterable[Collection]`: an iterable of [`Collection`] objects.
  7408. """
  7409. # Construct the API endpoint
  7410. path = f"{self.endpoint}/api/collections"
  7411. headers = self._build_hf_headers(token=token)
  7412. params: dict = {}
  7413. if owner is not None:
  7414. params.update({"owner": owner})
  7415. if item is not None:
  7416. params.update({"item": item})
  7417. if sort is not None:
  7418. params.update({"sort": sort})
  7419. if limit is not None:
  7420. params.update({"limit": limit})
  7421. # Paginate over the results until limit is reached
  7422. items = paginate(path, headers=headers, params=params)
  7423. if limit is not None:
  7424. items = islice(items, limit) # Do not iterate over all pages
  7425. # Parse as Collection and return
  7426. for position, collection_data in enumerate(items):
  7427. yield Collection(position=position, **collection_data)
  7428. def get_collection(self, collection_slug: str, *, token: Union[bool, str, None] = None) -> Collection:
  7429. """Gets information about a Collection on the Hub.
  7430. Args:
  7431. collection_slug (`str`):
  7432. Slug of the collection of the Hub. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  7433. token (`bool` or `str`, *optional*):
  7434. A valid user access token (string). Defaults to the locally saved
  7435. token, which is the recommended method for authentication (see
  7436. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7437. To disable authentication, pass `False`.
  7438. Returns: [`Collection`]
  7439. Example:
  7440. ```py
  7441. >>> from huggingface_hub import get_collection
  7442. >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
  7443. >>> collection.title
  7444. 'Recent models'
  7445. >>> len(collection.items)
  7446. 37
  7447. >>> collection.items[0]
  7448. CollectionItem(
  7449. item_object_id='651446103cd773a050bf64c2',
  7450. item_id='TheBloke/U-Amethyst-20B-AWQ',
  7451. item_type='model',
  7452. position=88,
  7453. note=None
  7454. )
  7455. ```
  7456. """
  7457. r = get_session().get(
  7458. f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token)
  7459. )
  7460. hf_raise_for_status(r)
  7461. return Collection(**{**r.json(), "endpoint": self.endpoint})
  7462. def create_collection(
  7463. self,
  7464. title: str,
  7465. *,
  7466. namespace: Optional[str] = None,
  7467. description: Optional[str] = None,
  7468. private: bool = False,
  7469. exists_ok: bool = False,
  7470. token: Union[bool, str, None] = None,
  7471. ) -> Collection:
  7472. """Create a new Collection on the Hub.
  7473. Args:
  7474. title (`str`):
  7475. Title of the collection to create. Example: `"Recent models"`.
  7476. namespace (`str`, *optional*):
  7477. Namespace of the collection to create (username or org). Will default to the owner name.
  7478. description (`str`, *optional*):
  7479. Description of the collection to create.
  7480. private (`bool`, *optional*):
  7481. Whether the collection should be private or not. Defaults to `False` (i.e. public collection).
  7482. exists_ok (`bool`, *optional*):
  7483. If `True`, do not raise an error if collection already exists.
  7484. token (`bool` or `str`, *optional*):
  7485. A valid user access token (string). Defaults to the locally saved
  7486. token, which is the recommended method for authentication (see
  7487. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7488. To disable authentication, pass `False`.
  7489. Returns: [`Collection`]
  7490. Example:
  7491. ```py
  7492. >>> from huggingface_hub import create_collection
  7493. >>> collection = create_collection(
  7494. ... title="ICCV 2023",
  7495. ... description="Portfolio of models, papers and demos I presented at ICCV 2023",
  7496. ... )
  7497. >>> collection.slug
  7498. "username/iccv-2023-64f9a55bb3115b4f513ec026"
  7499. ```
  7500. """
  7501. if namespace is None:
  7502. namespace = self.whoami(token)["name"]
  7503. payload = {
  7504. "title": title,
  7505. "namespace": namespace,
  7506. "private": private,
  7507. }
  7508. if description is not None:
  7509. payload["description"] = description
  7510. r = get_session().post(
  7511. f"{self.endpoint}/api/collections", headers=self._build_hf_headers(token=token), json=payload
  7512. )
  7513. try:
  7514. hf_raise_for_status(r)
  7515. except HfHubHTTPError as err:
  7516. if exists_ok and err.response.status_code == 409:
  7517. # Collection already exists and `exists_ok=True`
  7518. slug = r.json()["slug"]
  7519. return self.get_collection(slug, token=token)
  7520. else:
  7521. raise
  7522. return Collection(**{**r.json(), "endpoint": self.endpoint})
  7523. def update_collection_metadata(
  7524. self,
  7525. collection_slug: str,
  7526. *,
  7527. title: Optional[str] = None,
  7528. description: Optional[str] = None,
  7529. position: Optional[int] = None,
  7530. private: Optional[bool] = None,
  7531. theme: Optional[str] = None,
  7532. token: Union[bool, str, None] = None,
  7533. ) -> Collection:
  7534. """Update metadata of a collection on the Hub.
  7535. All arguments are optional. Only provided metadata will be updated.
  7536. Args:
  7537. collection_slug (`str`):
  7538. Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  7539. title (`str`):
  7540. Title of the collection to update.
  7541. description (`str`, *optional*):
  7542. Description of the collection to update.
  7543. position (`int`, *optional*):
  7544. New position of the collection in the list of collections of the user.
  7545. private (`bool`, *optional*):
  7546. Whether the collection should be private or not.
  7547. theme (`str`, *optional*):
  7548. Theme of the collection on the Hub.
  7549. token (`bool` or `str`, *optional*):
  7550. A valid user access token (string). Defaults to the locally saved
  7551. token, which is the recommended method for authentication (see
  7552. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7553. To disable authentication, pass `False`.
  7554. Returns: [`Collection`]
  7555. Example:
  7556. ```py
  7557. >>> from huggingface_hub import update_collection_metadata
  7558. >>> collection = update_collection_metadata(
  7559. ... collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026",
  7560. ... title="ICCV Oct. 2023"
  7561. ... description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023",
  7562. ... private=False,
  7563. ... theme="pink",
  7564. ... )
  7565. >>> collection.slug
  7566. "username/iccv-oct-2023-64f9a55bb3115b4f513ec026"
  7567. # ^collection slug got updated but not the trailing ID
  7568. ```
  7569. """
  7570. payload = {
  7571. "position": position,
  7572. "private": private,
  7573. "theme": theme,
  7574. "title": title,
  7575. "description": description,
  7576. }
  7577. r = get_session().patch(
  7578. f"{self.endpoint}/api/collections/{collection_slug}",
  7579. headers=self._build_hf_headers(token=token),
  7580. # Only send not-none values to the API
  7581. json={key: value for key, value in payload.items() if value is not None},
  7582. )
  7583. hf_raise_for_status(r)
  7584. return Collection(**{**r.json()["data"], "endpoint": self.endpoint})
  7585. def delete_collection(
  7586. self, collection_slug: str, *, missing_ok: bool = False, token: Union[bool, str, None] = None
  7587. ) -> None:
  7588. """Delete a collection on the Hub.
  7589. Args:
  7590. collection_slug (`str`):
  7591. Slug of the collection to delete. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  7592. missing_ok (`bool`, *optional*):
  7593. If `True`, do not raise an error if collection doesn't exists.
  7594. token (`bool` or `str`, *optional*):
  7595. A valid user access token (string). Defaults to the locally saved
  7596. token, which is the recommended method for authentication (see
  7597. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7598. To disable authentication, pass `False`.
  7599. Example:
  7600. ```py
  7601. >>> from huggingface_hub import delete_collection
  7602. >>> collection = delete_collection("username/useless-collection-64f9a55bb3115b4f513ec026", missing_ok=True)
  7603. ```
  7604. > [!WARNING]
  7605. > This is a non-revertible action. A deleted collection cannot be restored.
  7606. """
  7607. r = get_session().delete(
  7608. f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token)
  7609. )
  7610. try:
  7611. hf_raise_for_status(r)
  7612. except HfHubHTTPError as err:
  7613. if missing_ok and err.response.status_code == 404:
  7614. # Collection doesn't exists and `missing_ok=True`
  7615. return
  7616. else:
  7617. raise
  7618. def add_collection_item(
  7619. self,
  7620. collection_slug: str,
  7621. item_id: str,
  7622. item_type: CollectionItemType_T,
  7623. *,
  7624. note: Optional[str] = None,
  7625. exists_ok: bool = False,
  7626. token: Union[bool, str, None] = None,
  7627. ) -> Collection:
  7628. """Add an item to a collection on the Hub.
  7629. Args:
  7630. collection_slug (`str`):
  7631. Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  7632. item_id (`str`):
  7633. Id of the item to add to the collection. Use the repo_id for repos/spaces/datasets,
  7634. the paper id for papers, or the slug of another collection (e.g. `"moonshotai/kimi-k2"`).
  7635. item_type (`str`):
  7636. Type of the item to add. Can be one of `"model"`, `"dataset"`, `"space"`, `"paper"` or `"collection"`.
  7637. note (`str`, *optional*):
  7638. A note to attach to the item in the collection. The maximum size for a note is 500 characters.
  7639. exists_ok (`bool`, *optional*):
  7640. If `True`, do not raise an error if item already exists.
  7641. token (`bool` or `str`, *optional*):
  7642. A valid user access token (string). Defaults to the locally saved
  7643. token, which is the recommended method for authentication (see
  7644. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7645. To disable authentication, pass `False`.
  7646. Returns: [`Collection`]
  7647. Raises:
  7648. [`HfHubHTTPError`]:
  7649. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  7650. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  7651. [`HfHubHTTPError`]:
  7652. HTTP 404 if the item you try to add to the collection does not exist on the Hub.
  7653. [`HfHubHTTPError`]:
  7654. HTTP 409 if the item you try to add to the collection is already in the collection (and exists_ok=False)
  7655. Example:
  7656. ```py
  7657. >>> from huggingface_hub import add_collection_item
  7658. >>> collection = add_collection_item(
  7659. ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
  7660. ... item_id="pierre-loic/climate-news-articles",
  7661. ... item_type="dataset"
  7662. ... )
  7663. >>> collection.items[-1].item_id
  7664. "pierre-loic/climate-news-articles"
  7665. # ^item got added to the collection on last position
  7666. # Add item with a note
  7667. >>> add_collection_item(
  7668. ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
  7669. ... item_id="datasets/climate_fever",
  7670. ... item_type="dataset"
  7671. ... note="This dataset adopts the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet."
  7672. ... )
  7673. (...)
  7674. ```
  7675. """
  7676. payload: dict[str, Any] = {"item": {"id": item_id, "type": item_type}}
  7677. if note is not None:
  7678. payload["note"] = note
  7679. r = get_session().post(
  7680. f"{self.endpoint}/api/collections/{collection_slug}/items",
  7681. headers=self._build_hf_headers(token=token),
  7682. json=payload,
  7683. )
  7684. try:
  7685. hf_raise_for_status(r)
  7686. except HfHubHTTPError as err:
  7687. if exists_ok and err.response.status_code == 409:
  7688. # Item already exists and `exists_ok=True`
  7689. return self.get_collection(collection_slug, token=token)
  7690. else:
  7691. raise
  7692. return Collection(**{**r.json(), "endpoint": self.endpoint})
  7693. def update_collection_item(
  7694. self,
  7695. collection_slug: str,
  7696. item_object_id: str,
  7697. *,
  7698. note: Optional[str] = None,
  7699. position: Optional[int] = None,
  7700. token: Union[bool, str, None] = None,
  7701. ) -> None:
  7702. """Update an item in a collection.
  7703. Args:
  7704. collection_slug (`str`):
  7705. Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  7706. item_object_id (`str`):
  7707. ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
  7708. It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`.
  7709. note (`str`, *optional*):
  7710. A note to attach to the item in the collection. The maximum size for a note is 500 characters.
  7711. position (`int`, *optional*):
  7712. New position of the item in the collection.
  7713. token (`bool` or `str`, *optional*):
  7714. A valid user access token (string). Defaults to the locally saved
  7715. token, which is the recommended method for authentication (see
  7716. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7717. To disable authentication, pass `False`.
  7718. Example:
  7719. ```py
  7720. >>> from huggingface_hub import get_collection, update_collection_item
  7721. # Get collection first
  7722. >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
  7723. # Update item based on its ID (add note + update position)
  7724. >>> update_collection_item(
  7725. ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
  7726. ... item_object_id=collection.items[-1].item_object_id,
  7727. ... note="Newly updated model!"
  7728. ... position=0,
  7729. ... )
  7730. ```
  7731. """
  7732. payload = {"position": position, "note": note}
  7733. r = get_session().patch(
  7734. f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}",
  7735. headers=self._build_hf_headers(token=token),
  7736. # Only send not-none values to the API
  7737. json={key: value for key, value in payload.items() if value is not None},
  7738. )
  7739. hf_raise_for_status(r)
  7740. def delete_collection_item(
  7741. self,
  7742. collection_slug: str,
  7743. item_object_id: str,
  7744. *,
  7745. missing_ok: bool = False,
  7746. token: Union[bool, str, None] = None,
  7747. ) -> None:
  7748. """Delete an item from a collection.
  7749. Args:
  7750. collection_slug (`str`):
  7751. Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  7752. item_object_id (`str`):
  7753. ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
  7754. It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`.
  7755. missing_ok (`bool`, *optional*):
  7756. If `True`, do not raise an error if item doesn't exists.
  7757. token (`bool` or `str`, *optional*):
  7758. A valid user access token (string). Defaults to the locally saved
  7759. token, which is the recommended method for authentication (see
  7760. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7761. To disable authentication, pass `False`.
  7762. Example:
  7763. ```py
  7764. >>> from huggingface_hub import get_collection, delete_collection_item
  7765. # Get collection first
  7766. >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
  7767. # Delete item based on its ID
  7768. >>> delete_collection_item(
  7769. ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
  7770. ... item_object_id=collection.items[-1].item_object_id,
  7771. ... )
  7772. ```
  7773. """
  7774. r = get_session().delete(
  7775. f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}",
  7776. headers=self._build_hf_headers(token=token),
  7777. )
  7778. try:
  7779. hf_raise_for_status(r)
  7780. except HfHubHTTPError as err:
  7781. if missing_ok and err.response.status_code == 404:
  7782. # Item already deleted and `missing_ok=True`
  7783. return
  7784. else:
  7785. raise
  7786. ##########################
  7787. # Manage access requests #
  7788. ##########################
  7789. @validate_hf_hub_args
  7790. def list_pending_access_requests(
  7791. self, repo_id: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  7792. ) -> Iterable[AccessRequest]:
  7793. """
  7794. Get pending access requests for a given gated repo.
  7795. A pending request means the user has requested access to the repo but the request has not been processed yet.
  7796. If the approval mode is automatic, this list should be empty. Pending requests can be accepted or rejected
  7797. using [`accept_access_request`] and [`reject_access_request`].
  7798. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  7799. Args:
  7800. repo_id (`str`):
  7801. The id of the repo to get access requests for.
  7802. repo_type (`str`, *optional*):
  7803. The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
  7804. Defaults to `model`.
  7805. token (`bool` or `str`, *optional*):
  7806. A valid user access token (string). Defaults to the locally saved
  7807. token, which is the recommended method for authentication (see
  7808. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7809. To disable authentication, pass `False`.
  7810. Returns:
  7811. `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
  7812. `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
  7813. be populated with user's answers.
  7814. Raises:
  7815. [`HfHubHTTPError`]:
  7816. HTTP 400 if the repo is not gated.
  7817. [`HfHubHTTPError`]:
  7818. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  7819. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  7820. Example:
  7821. ```py
  7822. >>> from huggingface_hub import list_pending_access_requests, accept_access_request
  7823. # List pending requests
  7824. >>> requests = list(list_pending_access_requests("meta-llama/Llama-2-7b"))
  7825. >>> len(requests)
  7826. 411
  7827. >>> requests[0]
  7828. [
  7829. AccessRequest(
  7830. username='clem',
  7831. fullname='Clem 🤗',
  7832. email='***',
  7833. timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
  7834. status='pending',
  7835. fields=None,
  7836. ),
  7837. ...
  7838. ]
  7839. # Accept Clem's request
  7840. >>> accept_access_request("meta-llama/Llama-2-7b", "clem")
  7841. ```
  7842. """
  7843. yield from self._list_access_requests(repo_id, "pending", repo_type=repo_type, token=token)
  7844. @validate_hf_hub_args
  7845. def list_accepted_access_requests(
  7846. self, repo_id: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  7847. ) -> Iterable[AccessRequest]:
  7848. """
  7849. Get accepted access requests for a given gated repo.
  7850. An accepted request means the user has requested access to the repo and the request has been accepted. The user
  7851. can download any file of the repo. If the approval mode is automatic, this list should contains by default all
  7852. requests. Accepted requests can be cancelled or rejected at any time using [`cancel_access_request`] and
  7853. [`reject_access_request`]. A cancelled request will go back to the pending list while a rejected request will
  7854. go to the rejected list. In both cases, the user will lose access to the repo.
  7855. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  7856. Args:
  7857. repo_id (`str`):
  7858. The id of the repo to get access requests for.
  7859. repo_type (`str`, *optional*):
  7860. The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
  7861. Defaults to `model`.
  7862. token (`bool` or `str`, *optional*):
  7863. A valid user access token (string). Defaults to the locally saved
  7864. token, which is the recommended method for authentication (see
  7865. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7866. To disable authentication, pass `False`.
  7867. Returns:
  7868. `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
  7869. `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
  7870. be populated with user's answers.
  7871. Raises:
  7872. [`HfHubHTTPError`]:
  7873. HTTP 400 if the repo is not gated.
  7874. [`HfHubHTTPError`]:
  7875. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  7876. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  7877. Example:
  7878. ```py
  7879. >>> from huggingface_hub import list_accepted_access_requests
  7880. >>> requests = list(list_accepted_access_requests("meta-llama/Llama-2-7b"))
  7881. >>> len(requests)
  7882. 411
  7883. >>> requests[0]
  7884. [
  7885. AccessRequest(
  7886. username='clem',
  7887. fullname='Clem 🤗',
  7888. email='***',
  7889. timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
  7890. status='accepted',
  7891. fields=None,
  7892. ),
  7893. ...
  7894. ]
  7895. ```
  7896. """
  7897. yield from self._list_access_requests(repo_id, "accepted", repo_type=repo_type, token=token)
  7898. @validate_hf_hub_args
  7899. def list_rejected_access_requests(
  7900. self, repo_id: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  7901. ) -> Iterable[AccessRequest]:
  7902. """
  7903. Get rejected access requests for a given gated repo.
  7904. A rejected request means the user has requested access to the repo and the request has been explicitly rejected
  7905. by a repo owner (either you or another user from your organization). The user cannot download any file of the
  7906. repo. Rejected requests can be accepted or cancelled at any time using [`accept_access_request`] and
  7907. [`cancel_access_request`]. A cancelled request will go back to the pending list while an accepted request will
  7908. go to the accepted list.
  7909. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  7910. Args:
  7911. repo_id (`str`):
  7912. The id of the repo to get access requests for.
  7913. repo_type (`str`, *optional*):
  7914. The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
  7915. Defaults to `model`.
  7916. token (`bool` or `str`, *optional*):
  7917. A valid user access token (string). Defaults to the locally saved
  7918. token, which is the recommended method for authentication (see
  7919. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7920. To disable authentication, pass `False`.
  7921. Returns:
  7922. `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
  7923. `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
  7924. be populated with user's answers.
  7925. Raises:
  7926. [`HfHubHTTPError`]:
  7927. HTTP 400 if the repo is not gated.
  7928. [`HfHubHTTPError`]:
  7929. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  7930. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  7931. Example:
  7932. ```py
  7933. >>> from huggingface_hub import list_rejected_access_requests
  7934. >>> requests = list(list_rejected_access_requests("meta-llama/Llama-2-7b"))
  7935. >>> len(requests)
  7936. 411
  7937. >>> requests[0]
  7938. [
  7939. AccessRequest(
  7940. username='clem',
  7941. fullname='Clem 🤗',
  7942. email='***',
  7943. timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
  7944. status='rejected',
  7945. fields=None,
  7946. ),
  7947. ...
  7948. ]
  7949. ```
  7950. """
  7951. yield from self._list_access_requests(repo_id, "rejected", repo_type=repo_type, token=token)
  7952. def _list_access_requests(
  7953. self,
  7954. repo_id: str,
  7955. status: Literal["accepted", "rejected", "pending"],
  7956. repo_type: Optional[str] = None,
  7957. token: Union[bool, str, None] = None,
  7958. ) -> Iterable[AccessRequest]:
  7959. if repo_type not in constants.REPO_TYPES:
  7960. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  7961. if repo_type is None:
  7962. repo_type = constants.REPO_TYPE_MODEL
  7963. for request in paginate(
  7964. f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/{status}",
  7965. params={},
  7966. headers=self._build_hf_headers(token=token),
  7967. ):
  7968. yield AccessRequest(
  7969. username=request["user"]["user"],
  7970. fullname=request["user"]["fullname"],
  7971. email=request["user"].get("email"),
  7972. status=request["status"],
  7973. timestamp=parse_datetime(request["timestamp"]),
  7974. fields=request.get("fields"), # only if custom fields in form
  7975. )
  7976. @validate_hf_hub_args
  7977. def cancel_access_request(
  7978. self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  7979. ) -> None:
  7980. """
  7981. Cancel an access request from a user for a given gated repo.
  7982. A cancelled request will go back to the pending list and the user will lose access to the repo.
  7983. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  7984. Args:
  7985. repo_id (`str`):
  7986. The id of the repo to cancel access request for.
  7987. user (`str`):
  7988. The username of the user which access request should be cancelled.
  7989. repo_type (`str`, *optional*):
  7990. The type of the repo to cancel access request for. Must be one of `model`, `dataset` or `space`.
  7991. Defaults to `model`.
  7992. token (`bool` or `str`, *optional*):
  7993. A valid user access token (string). Defaults to the locally saved
  7994. token, which is the recommended method for authentication (see
  7995. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7996. To disable authentication, pass `False`.
  7997. Raises:
  7998. [`HfHubHTTPError`]:
  7999. HTTP 400 if the repo is not gated.
  8000. [`HfHubHTTPError`]:
  8001. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  8002. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  8003. [`HfHubHTTPError`]:
  8004. HTTP 404 if the user does not exist on the Hub.
  8005. [`HfHubHTTPError`]:
  8006. HTTP 404 if the user access request cannot be found.
  8007. [`HfHubHTTPError`]:
  8008. HTTP 404 if the user access request is already in the pending list.
  8009. """
  8010. self._handle_access_request(repo_id, user, "pending", repo_type=repo_type, token=token)
  8011. @validate_hf_hub_args
  8012. def accept_access_request(
  8013. self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  8014. ) -> None:
  8015. """
  8016. Accept an access request from a user for a given gated repo.
  8017. Once the request is accepted, the user will be able to download any file of the repo and access the community
  8018. tab. If the approval mode is automatic, you don't have to accept requests manually. An accepted request can be
  8019. cancelled or rejected at any time using [`cancel_access_request`] and [`reject_access_request`].
  8020. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  8021. Args:
  8022. repo_id (`str`):
  8023. The id of the repo to accept access request for.
  8024. user (`str`):
  8025. The username of the user which access request should be accepted.
  8026. repo_type (`str`, *optional*):
  8027. The type of the repo to accept access request for. Must be one of `model`, `dataset` or `space`.
  8028. Defaults to `model`.
  8029. token (`bool` or `str`, *optional*):
  8030. A valid user access token (string). Defaults to the locally saved
  8031. token, which is the recommended method for authentication (see
  8032. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8033. To disable authentication, pass `False`.
  8034. Raises:
  8035. [`HfHubHTTPError`]:
  8036. HTTP 400 if the repo is not gated.
  8037. [`HfHubHTTPError`]:
  8038. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  8039. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  8040. [`HfHubHTTPError`]:
  8041. HTTP 404 if the user does not exist on the Hub.
  8042. [`HfHubHTTPError`]:
  8043. HTTP 404 if the user access request cannot be found.
  8044. [`HfHubHTTPError`]:
  8045. HTTP 404 if the user access request is already in the accepted list.
  8046. """
  8047. self._handle_access_request(repo_id, user, "accepted", repo_type=repo_type, token=token)
  8048. @validate_hf_hub_args
  8049. def reject_access_request(
  8050. self,
  8051. repo_id: str,
  8052. user: str,
  8053. *,
  8054. repo_type: Optional[str] = None,
  8055. rejection_reason: Optional[str],
  8056. token: Union[bool, str, None] = None,
  8057. ) -> None:
  8058. """
  8059. Reject an access request from a user for a given gated repo.
  8060. A rejected request will go to the rejected list. The user cannot download any file of the repo. Rejected
  8061. requests can be accepted or cancelled at any time using [`accept_access_request`] and [`cancel_access_request`].
  8062. A cancelled request will go back to the pending list while an accepted request will go to the accepted list.
  8063. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  8064. Args:
  8065. repo_id (`str`):
  8066. The id of the repo to reject access request for.
  8067. user (`str`):
  8068. The username of the user which access request should be rejected.
  8069. repo_type (`str`, *optional*):
  8070. The type of the repo to reject access request for. Must be one of `model`, `dataset` or `space`.
  8071. Defaults to `model`.
  8072. rejection_reason (`str`, *optional*):
  8073. Optional rejection reason that will be visible to the user (max 200 characters).
  8074. token (`bool` or `str`, *optional*):
  8075. A valid user access token (string). Defaults to the locally saved
  8076. token, which is the recommended method for authentication (see
  8077. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8078. To disable authentication, pass `False`.
  8079. Raises:
  8080. [`HfHubHTTPError`]:
  8081. HTTP 400 if the repo is not gated.
  8082. [`HfHubHTTPError`]:
  8083. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  8084. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  8085. [`HfHubHTTPError`]:
  8086. HTTP 404 if the user does not exist on the Hub.
  8087. [`HfHubHTTPError`]:
  8088. HTTP 404 if the user access request cannot be found.
  8089. [`HfHubHTTPError`]:
  8090. HTTP 404 if the user access request is already in the rejected list.
  8091. """
  8092. self._handle_access_request(
  8093. repo_id, user, "rejected", repo_type=repo_type, rejection_reason=rejection_reason, token=token
  8094. )
  8095. @validate_hf_hub_args
  8096. def _handle_access_request(
  8097. self,
  8098. repo_id: str,
  8099. user: str,
  8100. status: Literal["accepted", "rejected", "pending"],
  8101. repo_type: Optional[str] = None,
  8102. rejection_reason: Optional[str] = None,
  8103. token: Union[bool, str, None] = None,
  8104. ) -> None:
  8105. if repo_type not in constants.REPO_TYPES:
  8106. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  8107. if repo_type is None:
  8108. repo_type = constants.REPO_TYPE_MODEL
  8109. payload = {"user": user, "status": status}
  8110. if rejection_reason is not None:
  8111. if status != "rejected":
  8112. raise ValueError("`rejection_reason` can only be passed when rejecting an access request.")
  8113. payload["rejectionReason"] = rejection_reason
  8114. response = get_session().post(
  8115. f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/handle",
  8116. headers=self._build_hf_headers(token=token),
  8117. json=payload,
  8118. )
  8119. hf_raise_for_status(response)
  8120. @validate_hf_hub_args
  8121. def grant_access(
  8122. self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  8123. ) -> None:
  8124. """
  8125. Grant access to a user for a given gated repo.
  8126. Granting access don't require for the user to send an access request by themselves. The user is automatically
  8127. added to the accepted list meaning they can download the files You can revoke the granted access at any time
  8128. using [`cancel_access_request`] or [`reject_access_request`].
  8129. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  8130. Args:
  8131. repo_id (`str`):
  8132. The id of the repo to grant access to.
  8133. user (`str`):
  8134. The username of the user to grant access.
  8135. repo_type (`str`, *optional*):
  8136. The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`.
  8137. Defaults to `model`.
  8138. token (`bool` or `str`, *optional*):
  8139. A valid user access token (string). Defaults to the locally saved
  8140. token, which is the recommended method for authentication (see
  8141. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8142. To disable authentication, pass `False`.
  8143. Raises:
  8144. [`HfHubHTTPError`]:
  8145. HTTP 400 if the repo is not gated.
  8146. [`HfHubHTTPError`]:
  8147. HTTP 400 if the user already has access to the repo.
  8148. [`HfHubHTTPError`]:
  8149. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  8150. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  8151. [`HfHubHTTPError`]:
  8152. HTTP 404 if the user does not exist on the Hub.
  8153. """
  8154. if repo_type not in constants.REPO_TYPES:
  8155. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  8156. if repo_type is None:
  8157. repo_type = constants.REPO_TYPE_MODEL
  8158. response = get_session().post(
  8159. f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/grant",
  8160. headers=self._build_hf_headers(token=token),
  8161. json={"user": user},
  8162. )
  8163. hf_raise_for_status(response)
  8164. return response.json()
  8165. ###################
  8166. # Manage webhooks #
  8167. ###################
  8168. @validate_hf_hub_args
  8169. def get_webhook(self, webhook_id: str, *, token: Union[bool, str, None] = None) -> WebhookInfo:
  8170. """Get a webhook by its id.
  8171. Args:
  8172. webhook_id (`str`):
  8173. The unique identifier of the webhook to get.
  8174. token (`bool` or `str`, *optional*):
  8175. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8176. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8177. To disable authentication, pass `False`.
  8178. Returns:
  8179. [`WebhookInfo`]:
  8180. Info about the webhook.
  8181. Example:
  8182. ```python
  8183. >>> from huggingface_hub import get_webhook
  8184. >>> webhook = get_webhook("654bbbc16f2ec14d77f109cc")
  8185. >>> print(webhook)
  8186. WebhookInfo(
  8187. id="654bbbc16f2ec14d77f109cc",
  8188. job=None,
  8189. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8190. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8191. secret="my-secret",
  8192. domains=["repo", "discussion"],
  8193. disabled=False,
  8194. )
  8195. ```
  8196. """
  8197. response = get_session().get(
  8198. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}",
  8199. headers=self._build_hf_headers(token=token),
  8200. )
  8201. hf_raise_for_status(response)
  8202. webhook_data = response.json()["webhook"]
  8203. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  8204. webhook = WebhookInfo(
  8205. id=webhook_data["id"],
  8206. url=webhook_data.get("url"),
  8207. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  8208. watched=watched_items,
  8209. domains=webhook_data["domains"],
  8210. secret=webhook_data.get("secret"),
  8211. disabled=webhook_data["disabled"],
  8212. )
  8213. return webhook
  8214. @validate_hf_hub_args
  8215. def list_webhooks(self, *, token: Union[bool, str, None] = None) -> list[WebhookInfo]:
  8216. """List all configured webhooks.
  8217. Args:
  8218. token (`bool` or `str`, *optional*):
  8219. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8220. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8221. To disable authentication, pass `False`.
  8222. Returns:
  8223. `list[WebhookInfo]`:
  8224. List of webhook info objects.
  8225. Example:
  8226. ```python
  8227. >>> from huggingface_hub import list_webhooks
  8228. >>> webhooks = list_webhooks()
  8229. >>> len(webhooks)
  8230. 2
  8231. >>> webhooks[0]
  8232. WebhookInfo(
  8233. id="654bbbc16f2ec14d77f109cc",
  8234. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8235. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8236. secret="my-secret",
  8237. domains=["repo", "discussion"],
  8238. disabled=False,
  8239. )
  8240. ```
  8241. """
  8242. response = get_session().get(
  8243. f"{constants.ENDPOINT}/api/settings/webhooks",
  8244. headers=self._build_hf_headers(token=token),
  8245. )
  8246. hf_raise_for_status(response)
  8247. webhooks_data = response.json()
  8248. return [
  8249. WebhookInfo(
  8250. id=webhook["id"],
  8251. url=webhook.get("url"),
  8252. job=JobSpec(**webhook["job"]) if webhook.get("job") else None,
  8253. watched=[WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook["watched"]],
  8254. domains=webhook["domains"],
  8255. secret=webhook.get("secret"),
  8256. disabled=webhook["disabled"],
  8257. )
  8258. for webhook in webhooks_data
  8259. ]
  8260. @validate_hf_hub_args
  8261. def create_webhook(
  8262. self,
  8263. *,
  8264. url: Optional[str] = None,
  8265. job_id: Optional[str] = None,
  8266. watched: list[Union[dict, WebhookWatchedItem]],
  8267. domains: Optional[list[constants.WEBHOOK_DOMAIN_T]] = None,
  8268. secret: Optional[str] = None,
  8269. token: Union[bool, str, None] = None,
  8270. ) -> WebhookInfo:
  8271. """Create a new webhook.
  8272. The webhook can either send a payload to a URL, or trigger a Job to run on Hugging Face infrastructure.
  8273. This function should be called with one of `url` or `job_id`, but not both.
  8274. Args:
  8275. url (`str`):
  8276. URL to send the payload to.
  8277. job_id (`str`):
  8278. ID of the source Job to trigger with the webhook payload in the environment variable WEBHOOK_PAYLOAD.
  8279. Additional environment variables are available for convenience: WEBHOOK_REPO_ID, WEBHOOK_REPO_TYPE and WEBHOOK_SECRET.
  8280. watched (`list[WebhookWatchedItem]`):
  8281. List of [`WebhookWatchedItem`] to be watched by the webhook. It can be users, orgs, models, datasets or spaces.
  8282. Watched items can also be provided as plain dictionaries.
  8283. domains (`list[Literal["repo", "discussion"]]`, optional):
  8284. List of domains to watch. It can be "repo", "discussion" or both.
  8285. secret (`str`, optional):
  8286. A secret to sign the payload with.
  8287. token (`bool` or `str`, *optional*):
  8288. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8289. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8290. To disable authentication, pass `False`.
  8291. Returns:
  8292. [`WebhookInfo`]:
  8293. Info about the newly created webhook.
  8294. Example:
  8295. Create a webhook that sends a payload to a URL
  8296. ```python
  8297. >>> from huggingface_hub import create_webhook
  8298. >>> payload = create_webhook(
  8299. ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
  8300. ... url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8301. ... domains=["repo", "discussion"],
  8302. ... secret="my-secret",
  8303. ... )
  8304. >>> print(payload)
  8305. WebhookInfo(
  8306. id="654bbbc16f2ec14d77f109cc",
  8307. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8308. job=None,
  8309. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8310. domains=["repo", "discussion"],
  8311. secret="my-secret",
  8312. disabled=False,
  8313. )
  8314. ```
  8315. Run a Job and then create a webhook that triggers this Job
  8316. ```python
  8317. >>> from huggingface_hub import create_webhook, run_job
  8318. >>> job = run_job(
  8319. ... image="ubuntu",
  8320. ... command=["bash", "-c", r"echo An event occured in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD"],
  8321. ... )
  8322. >>> payload = create_webhook(
  8323. ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
  8324. ... job_id=job.id,
  8325. ... domains=["repo", "discussion"],
  8326. ... secret="my-secret",
  8327. ... )
  8328. >>> print(payload)
  8329. WebhookInfo(
  8330. id="654bbbc16f2ec14d77f109cc",
  8331. url=None,
  8332. job=JobSpec(
  8333. docker_image='ubuntu',
  8334. space_id=None,
  8335. command=['bash', '-c', 'echo An event occured in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD'],
  8336. arguments=[],
  8337. environment={},
  8338. secrets=[],
  8339. flavor='cpu-basic',
  8340. timeout=None,
  8341. tags=None,
  8342. arch=None
  8343. ),
  8344. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8345. domains=["repo", "discussion"],
  8346. secret="my-secret",
  8347. disabled=False,
  8348. )
  8349. ```
  8350. """
  8351. watched_dicts = [asdict(item) if isinstance(item, WebhookWatchedItem) else item for item in watched]
  8352. post_webhooks_json = {"watched": watched_dicts, "domains": domains, "secret": secret}
  8353. if url is not None and job_id is not None:
  8354. raise ValueError("Set `url` or `job_id` but not both.")
  8355. elif url is not None:
  8356. post_webhooks_json["url"] = url
  8357. elif job_id is not None:
  8358. post_webhooks_json["jobSourceId"] = job_id
  8359. else:
  8360. raise ValueError("Missing argument for webhook: `url` or `job_id`.")
  8361. response = get_session().post(
  8362. f"{constants.ENDPOINT}/api/settings/webhooks",
  8363. json=post_webhooks_json,
  8364. headers=self._build_hf_headers(token=token),
  8365. )
  8366. hf_raise_for_status(response)
  8367. webhook_data = response.json()["webhook"]
  8368. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  8369. webhook = WebhookInfo(
  8370. id=webhook_data["id"],
  8371. url=webhook_data.get("url"),
  8372. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  8373. watched=watched_items,
  8374. domains=webhook_data["domains"],
  8375. secret=webhook_data.get("secret"),
  8376. disabled=webhook_data["disabled"],
  8377. )
  8378. return webhook
  8379. @validate_hf_hub_args
  8380. def update_webhook(
  8381. self,
  8382. webhook_id: str,
  8383. *,
  8384. url: Optional[str] = None,
  8385. watched: Optional[list[Union[dict, WebhookWatchedItem]]] = None,
  8386. domains: Optional[list[constants.WEBHOOK_DOMAIN_T]] = None,
  8387. secret: Optional[str] = None,
  8388. token: Union[bool, str, None] = None,
  8389. ) -> WebhookInfo:
  8390. """Update an existing webhook.
  8391. Args:
  8392. webhook_id (`str`):
  8393. The unique identifier of the webhook to be updated.
  8394. url (`str`, optional):
  8395. The URL to which the payload will be sent.
  8396. watched (`list[WebhookWatchedItem]`, optional):
  8397. List of items to watch. It can be users, orgs, models, datasets, or spaces.
  8398. Refer to [`WebhookWatchedItem`] for more details. Watched items can also be provided as plain dictionaries.
  8399. domains (`list[Literal["repo", "discussion"]]`, optional):
  8400. The domains to watch. This can include "repo", "discussion", or both.
  8401. secret (`str`, optional):
  8402. A secret to sign the payload with, providing an additional layer of security.
  8403. token (`bool` or `str`, *optional*):
  8404. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8405. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8406. To disable authentication, pass `False`.
  8407. Returns:
  8408. [`WebhookInfo`]:
  8409. Info about the updated webhook.
  8410. Example:
  8411. ```python
  8412. >>> from huggingface_hub import update_webhook
  8413. >>> updated_payload = update_webhook(
  8414. ... webhook_id="654bbbc16f2ec14d77f109cc",
  8415. ... url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8416. ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
  8417. ... domains=["repo"],
  8418. ... secret="my-secret",
  8419. ... )
  8420. >>> print(updated_payload)
  8421. WebhookInfo(
  8422. id="654bbbc16f2ec14d77f109cc",
  8423. job=None,
  8424. url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8425. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8426. domains=["repo"],
  8427. secret="my-secret",
  8428. disabled=False,
  8429. ```
  8430. """
  8431. if watched is None:
  8432. watched = []
  8433. watched_dicts = [asdict(item) if isinstance(item, WebhookWatchedItem) else item for item in watched]
  8434. response = get_session().post(
  8435. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}",
  8436. json={"watched": watched_dicts, "url": url, "domains": domains, "secret": secret},
  8437. headers=self._build_hf_headers(token=token),
  8438. )
  8439. hf_raise_for_status(response)
  8440. webhook_data = response.json()["webhook"]
  8441. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  8442. webhook = WebhookInfo(
  8443. id=webhook_data["id"],
  8444. url=webhook_data.get("url"),
  8445. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  8446. watched=watched_items,
  8447. domains=webhook_data["domains"],
  8448. secret=webhook_data.get("secret"),
  8449. disabled=webhook_data["disabled"],
  8450. )
  8451. return webhook
  8452. @validate_hf_hub_args
  8453. def enable_webhook(self, webhook_id: str, *, token: Union[bool, str, None] = None) -> WebhookInfo:
  8454. """Enable a webhook (makes it "active").
  8455. Args:
  8456. webhook_id (`str`):
  8457. The unique identifier of the webhook to enable.
  8458. token (`bool` or `str`, *optional*):
  8459. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8460. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8461. To disable authentication, pass `False`.
  8462. Returns:
  8463. [`WebhookInfo`]:
  8464. Info about the enabled webhook.
  8465. Example:
  8466. ```python
  8467. >>> from huggingface_hub import enable_webhook
  8468. >>> enabled_webhook = enable_webhook("654bbbc16f2ec14d77f109cc")
  8469. >>> enabled_webhook
  8470. WebhookInfo(
  8471. id="654bbbc16f2ec14d77f109cc",
  8472. job=None,
  8473. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8474. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8475. domains=["repo", "discussion"],
  8476. secret="my-secret",
  8477. disabled=False,
  8478. )
  8479. ```
  8480. """
  8481. response = get_session().post(
  8482. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}/enable",
  8483. headers=self._build_hf_headers(token=token),
  8484. )
  8485. hf_raise_for_status(response)
  8486. webhook_data = response.json()["webhook"]
  8487. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  8488. webhook = WebhookInfo(
  8489. id=webhook_data["id"],
  8490. url=webhook_data.get("url"),
  8491. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  8492. watched=watched_items,
  8493. domains=webhook_data["domains"],
  8494. secret=webhook_data.get("secret"),
  8495. disabled=webhook_data["disabled"],
  8496. )
  8497. return webhook
  8498. @validate_hf_hub_args
  8499. def disable_webhook(self, webhook_id: str, *, token: Union[bool, str, None] = None) -> WebhookInfo:
  8500. """Disable a webhook (makes it "disabled").
  8501. Args:
  8502. webhook_id (`str`):
  8503. The unique identifier of the webhook to disable.
  8504. token (`bool` or `str`, *optional*):
  8505. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8506. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8507. To disable authentication, pass `False`.
  8508. Returns:
  8509. [`WebhookInfo`]:
  8510. Info about the disabled webhook.
  8511. Example:
  8512. ```python
  8513. >>> from huggingface_hub import disable_webhook
  8514. >>> disabled_webhook = disable_webhook("654bbbc16f2ec14d77f109cc")
  8515. >>> disabled_webhook
  8516. WebhookInfo(
  8517. id="654bbbc16f2ec14d77f109cc",
  8518. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8519. jon=None,
  8520. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8521. domains=["repo", "discussion"],
  8522. secret="my-secret",
  8523. disabled=True,
  8524. )
  8525. ```
  8526. """
  8527. response = get_session().post(
  8528. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}/disable",
  8529. headers=self._build_hf_headers(token=token),
  8530. )
  8531. hf_raise_for_status(response)
  8532. webhook_data = response.json()["webhook"]
  8533. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  8534. webhook = WebhookInfo(
  8535. id=webhook_data["id"],
  8536. url=webhook_data.get("url"),
  8537. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  8538. watched=watched_items,
  8539. domains=webhook_data["domains"],
  8540. secret=webhook_data.get("secret"),
  8541. disabled=webhook_data["disabled"],
  8542. )
  8543. return webhook
  8544. @validate_hf_hub_args
  8545. def delete_webhook(self, webhook_id: str, *, token: Union[bool, str, None] = None) -> None:
  8546. """Delete a webhook.
  8547. Args:
  8548. webhook_id (`str`):
  8549. The unique identifier of the webhook to delete.
  8550. token (`bool` or `str`, *optional*):
  8551. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8552. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8553. To disable authentication, pass `False`.
  8554. Returns:
  8555. `None`
  8556. Example:
  8557. ```python
  8558. >>> from huggingface_hub import delete_webhook
  8559. >>> delete_webhook("654bbbc16f2ec14d77f109cc")
  8560. ```
  8561. """
  8562. response = get_session().delete(
  8563. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}",
  8564. headers=self._build_hf_headers(token=token),
  8565. )
  8566. hf_raise_for_status(response)
  8567. #############
  8568. # Internals #
  8569. #############
  8570. def _build_hf_headers(
  8571. self,
  8572. token: Union[bool, str, None] = None,
  8573. library_name: Optional[str] = None,
  8574. library_version: Optional[str] = None,
  8575. user_agent: Union[dict, str, None] = None,
  8576. ) -> dict[str, str]:
  8577. """
  8578. Alias for [`build_hf_headers`] that uses the token from [`HfApi`] client
  8579. when `token` is not provided.
  8580. """
  8581. if token is None:
  8582. # Cannot do `token = token or self.token` as token can be `False`.
  8583. token = self.token
  8584. return build_hf_headers(
  8585. token=token,
  8586. library_name=library_name or self.library_name,
  8587. library_version=library_version or self.library_version,
  8588. user_agent=user_agent or self.user_agent,
  8589. headers=self.headers,
  8590. )
  8591. def _prepare_folder_deletions(
  8592. self,
  8593. repo_id: str,
  8594. repo_type: Optional[str],
  8595. revision: Optional[str],
  8596. path_in_repo: str,
  8597. delete_patterns: Optional[Union[list[str], str]],
  8598. token: Union[bool, str, None] = None,
  8599. ) -> list[CommitOperationDelete]:
  8600. """Generate the list of Delete operations for a commit to delete files from a repo.
  8601. List remote files and match them against the `delete_patterns` constraints. Returns a list of [`CommitOperationDelete`]
  8602. with the matching items.
  8603. Note: `.gitattributes` file is essential to make a repo work properly on the Hub. This file will always be
  8604. kept even if it matches the `delete_patterns` constraints.
  8605. """
  8606. if delete_patterns is None:
  8607. # If no delete patterns, no need to list and filter remote files
  8608. return []
  8609. # List remote files
  8610. filenames = self.list_repo_files(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token)
  8611. # Compute relative path in repo
  8612. if path_in_repo and path_in_repo not in (".", "./"):
  8613. path_in_repo = path_in_repo.strip("/") + "/" # harmonize
  8614. relpath_to_abspath = {
  8615. file[len(path_in_repo) :]: file for file in filenames if file.startswith(path_in_repo)
  8616. }
  8617. else:
  8618. relpath_to_abspath = {file: file for file in filenames}
  8619. # Apply filter on relative paths and return
  8620. return [
  8621. CommitOperationDelete(path_in_repo=relpath_to_abspath[relpath], is_folder=False)
  8622. for relpath in filter_repo_objects(relpath_to_abspath.keys(), allow_patterns=delete_patterns)
  8623. if relpath_to_abspath[relpath] != ".gitattributes"
  8624. ]
  8625. def _prepare_upload_folder_additions(
  8626. self,
  8627. folder_path: Union[str, Path],
  8628. path_in_repo: str,
  8629. allow_patterns: Optional[Union[list[str], str]] = None,
  8630. ignore_patterns: Optional[Union[list[str], str]] = None,
  8631. repo_type: Optional[str] = None,
  8632. token: Union[bool, str, None] = None,
  8633. ) -> list[CommitOperationAdd]:
  8634. """Generate the list of Add operations for a commit to upload a folder.
  8635. Files not matching the `allow_patterns` (allowlist) and `ignore_patterns` (denylist)
  8636. constraints are discarded.
  8637. """
  8638. folder_path = Path(folder_path).expanduser().resolve()
  8639. if not folder_path.is_dir():
  8640. raise ValueError(f"Provided path: '{folder_path}' is not a directory")
  8641. # List files from folder
  8642. relpath_to_abspath = {
  8643. path.relative_to(folder_path).as_posix(): path
  8644. for path in sorted(folder_path.glob("**/*")) # sorted to be deterministic
  8645. if path.is_file()
  8646. }
  8647. # Filter files
  8648. # Patterns are applied on the path relative to `folder_path`. `path_in_repo` is prefixed after the filtering.
  8649. filtered_repo_objects = list(
  8650. filter_repo_objects(
  8651. relpath_to_abspath.keys(), allow_patterns=allow_patterns, ignore_patterns=ignore_patterns
  8652. )
  8653. )
  8654. prefix = f"{path_in_repo.strip('/')}/" if path_in_repo else ""
  8655. # If updating a README.md file, make sure the metadata format is valid
  8656. # It's better to fail early than to fail after all the files have been hashed.
  8657. if "README.md" in filtered_repo_objects:
  8658. self._validate_yaml(
  8659. content=relpath_to_abspath["README.md"].read_text(encoding="utf8"),
  8660. repo_type=repo_type,
  8661. token=token,
  8662. )
  8663. if len(filtered_repo_objects) > 30:
  8664. log = logger.warning if len(filtered_repo_objects) > 200 else logger.info
  8665. log(
  8666. "It seems you are trying to upload a large folder at once. This might take some time and then fail if "
  8667. "the folder is too large. For such cases, it is recommended to upload in smaller batches or to use "
  8668. "`HfApi().upload_large_folder(...)`/`hf upload-large-folder` instead. For more details, "
  8669. "check out https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#upload-a-large-folder."
  8670. )
  8671. logger.info(f"Start hashing {len(filtered_repo_objects)} files.")
  8672. operations = [
  8673. CommitOperationAdd(
  8674. path_or_fileobj=relpath_to_abspath[relpath], # absolute path on disk
  8675. path_in_repo=prefix + relpath, # "absolute" path in repo
  8676. )
  8677. for relpath in filtered_repo_objects
  8678. ]
  8679. logger.info(f"Finished hashing {len(filtered_repo_objects)} files.")
  8680. return operations
  8681. def _validate_yaml(self, content: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None):
  8682. """
  8683. Validate YAML from `README.md`, used before file hashing and upload.
  8684. Args:
  8685. content (`str`):
  8686. Content of `README.md` to validate.
  8687. repo_type (`str`, *optional*):
  8688. The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`.
  8689. Defaults to `model`.
  8690. token (`bool` or `str`, *optional*):
  8691. A valid user access token (string). Defaults to the locally saved
  8692. token, which is the recommended method for authentication (see
  8693. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8694. To disable authentication, pass `False`.
  8695. Raises:
  8696. - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  8697. if YAML is invalid
  8698. """
  8699. repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL
  8700. headers = self._build_hf_headers(token=token)
  8701. response = get_session().post(
  8702. f"{self.endpoint}/api/validate-yaml",
  8703. json={"content": content, "repoType": repo_type},
  8704. headers=headers,
  8705. )
  8706. # Handle warnings (example: empty metadata)
  8707. response_content = response.json()
  8708. message = "\n".join([f"- {warning.get('message')}" for warning in response_content.get("warnings", [])])
  8709. if message:
  8710. warnings.warn(f"Warnings while validating metadata in README.md:\n{message}")
  8711. # Raise on errors
  8712. try:
  8713. hf_raise_for_status(response)
  8714. except BadRequestError as e:
  8715. errors = response_content.get("errors", [])
  8716. message = "\n".join([f"- {error.get('message')}" for error in errors])
  8717. raise ValueError(f"Invalid metadata in README.md.\n{message}") from e
  8718. def get_user_overview(self, username: str, token: Union[bool, str, None] = None) -> User:
  8719. """
  8720. Get an overview of a user on the Hub.
  8721. Args:
  8722. username (`str`):
  8723. Username of the user to get an overview of.
  8724. token (`bool` or `str`, *optional*):
  8725. A valid user access token (string). Defaults to the locally saved
  8726. token, which is the recommended method for authentication (see
  8727. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8728. To disable authentication, pass `False`.
  8729. Returns:
  8730. `User`: A [`User`] object with the user's overview.
  8731. Raises:
  8732. [`HfHubHTTPError`]:
  8733. HTTP 404 If the user does not exist on the Hub.
  8734. """
  8735. r = get_session().get(
  8736. f"{constants.ENDPOINT}/api/users/{username}/overview", headers=self._build_hf_headers(token=token)
  8737. )
  8738. hf_raise_for_status(r)
  8739. return User(**r.json())
  8740. @validate_hf_hub_args
  8741. def get_organization_overview(self, organization: str, token: Union[bool, str, None] = None) -> Organization:
  8742. """
  8743. Get an overview of an organization on the Hub.
  8744. Args:
  8745. organization (`str`):
  8746. Name of the organization to get an overview of.
  8747. token (`bool` or `str`, *optional*):
  8748. A valid user access token (string). Defaults to the locally saved token, which is the recommended method
  8749. for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8750. To disable authentication, pass `False`.
  8751. Returns:
  8752. `Organization`: An [`Organization`] object with the organization's overview.
  8753. Raises:
  8754. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8755. HTTP 404 If the organization does not exist on the Hub.
  8756. """
  8757. r = get_session().get(
  8758. f"{constants.ENDPOINT}/api/organizations/{organization}/overview",
  8759. headers=self._build_hf_headers(token=token),
  8760. )
  8761. hf_raise_for_status(r)
  8762. return Organization(**r.json())
  8763. @validate_hf_hub_args
  8764. def list_organization_followers(self, organization: str, token: Union[bool, str, None] = None) -> Iterable[User]:
  8765. """
  8766. List followers of an organization on the Hub.
  8767. Args:
  8768. organization (`str`):
  8769. Name of the organization to get the followers of.
  8770. token (`bool` or `str`, *optional*):
  8771. A valid user access token (string). Defaults to the locally saved
  8772. token, which is the recommended method for authentication (see
  8773. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8774. To disable authentication, pass `False`.
  8775. Returns:
  8776. `Iterable[User]`: A list of [`User`] objects with the followers of the organization.
  8777. Raises:
  8778. [`HfHubHTTPError`]:
  8779. HTTP 404 If the organization does not exist on the Hub.
  8780. """
  8781. for follower in paginate(
  8782. path=f"{constants.ENDPOINT}/api/organizations/{organization}/followers",
  8783. params={},
  8784. headers=self._build_hf_headers(token=token),
  8785. ):
  8786. yield User(**follower)
  8787. def list_organization_members(self, organization: str, token: Union[bool, str, None] = None) -> Iterable[User]:
  8788. """
  8789. List of members of an organization on the Hub.
  8790. Args:
  8791. organization (`str`):
  8792. Name of the organization to get the members of.
  8793. token (`bool` or `str`, *optional*):
  8794. A valid user access token (string). Defaults to the locally saved
  8795. token, which is the recommended method for authentication (see
  8796. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8797. To disable authentication, pass `False`.
  8798. Returns:
  8799. `Iterable[User]`: A list of [`User`] objects with the members of the organization.
  8800. Raises:
  8801. [`HfHubHTTPError`]:
  8802. HTTP 404 If the organization does not exist on the Hub.
  8803. """
  8804. for member in paginate(
  8805. path=f"{constants.ENDPOINT}/api/organizations/{organization}/members",
  8806. params={},
  8807. headers=self._build_hf_headers(token=token),
  8808. ):
  8809. yield User(**member)
  8810. def list_user_followers(self, username: str, token: Union[bool, str, None] = None) -> Iterable[User]:
  8811. """
  8812. Get the list of followers of a user on the Hub.
  8813. Args:
  8814. username (`str`):
  8815. Username of the user to get the followers of.
  8816. token (`bool` or `str`, *optional*):
  8817. A valid user access token (string). Defaults to the locally saved
  8818. token, which is the recommended method for authentication (see
  8819. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8820. To disable authentication, pass `False`.
  8821. Returns:
  8822. `Iterable[User]`: A list of [`User`] objects with the followers of the user.
  8823. Raises:
  8824. [`HfHubHTTPError`]:
  8825. HTTP 404 If the user does not exist on the Hub.
  8826. """
  8827. for follower in paginate(
  8828. path=f"{constants.ENDPOINT}/api/users/{username}/followers",
  8829. params={},
  8830. headers=self._build_hf_headers(token=token),
  8831. ):
  8832. yield User(**follower)
  8833. def list_user_following(self, username: str, token: Union[bool, str, None] = None) -> Iterable[User]:
  8834. """
  8835. Get the list of users followed by a user on the Hub.
  8836. Args:
  8837. username (`str`):
  8838. Username of the user to get the users followed by.
  8839. token (`bool` or `str`, *optional*):
  8840. A valid user access token (string). Defaults to the locally saved
  8841. token, which is the recommended method for authentication (see
  8842. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8843. To disable authentication, pass `False`.
  8844. Returns:
  8845. `Iterable[User]`: A list of [`User`] objects with the users followed by the user.
  8846. Raises:
  8847. [`HfHubHTTPError`]:
  8848. HTTP 404 If the user does not exist on the Hub.
  8849. """
  8850. for followed_user in paginate(
  8851. path=f"{constants.ENDPOINT}/api/users/{username}/following",
  8852. params={},
  8853. headers=self._build_hf_headers(token=token),
  8854. ):
  8855. yield User(**followed_user)
  8856. def list_papers(
  8857. self,
  8858. *,
  8859. query: Optional[str] = None,
  8860. limit: Optional[int] = None,
  8861. token: Union[bool, str, None] = None,
  8862. ) -> Iterable[PaperInfo]:
  8863. """
  8864. List daily papers on the Hugging Face Hub given a search query.
  8865. Args:
  8866. query (`str`, *optional*):
  8867. A search query string to find papers.
  8868. If provided, returns papers that match the query.
  8869. limit (`int`, *optional*):
  8870. The maximum number of papers to return.
  8871. token (Union[bool, str, None], *optional*):
  8872. A valid user access token (string). Defaults to the locally saved
  8873. token, which is the recommended method for authentication (see
  8874. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8875. To disable authentication, pass `False`.
  8876. Returns:
  8877. `Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects.
  8878. Example:
  8879. ```python
  8880. >>> from huggingface_hub import HfApi
  8881. >>> api = HfApi()
  8882. # List all papers with "attention" in their title
  8883. >>> api.list_papers(query="attention")
  8884. ```
  8885. """
  8886. path = f"{self.endpoint}/api/papers/search"
  8887. params: dict[str, Any] = {}
  8888. if query:
  8889. params["q"] = query
  8890. if limit is not None:
  8891. params["limit"] = limit
  8892. r = get_session().get(
  8893. path,
  8894. params=params,
  8895. headers=self._build_hf_headers(token=token),
  8896. )
  8897. hf_raise_for_status(r)
  8898. for paper in r.json():
  8899. yield PaperInfo(**paper)
  8900. def paper_info(self, id: str) -> PaperInfo:
  8901. """
  8902. Get information for a paper on the Hub.
  8903. Args:
  8904. id (`str`, **optional**):
  8905. ArXiv id of the paper.
  8906. Returns:
  8907. `PaperInfo`: A `PaperInfo` object.
  8908. Raises:
  8909. [`HfHubHTTPError`]:
  8910. HTTP 404 If the paper does not exist on the Hub.
  8911. """
  8912. path = f"{self.endpoint}/api/papers/{id}"
  8913. r = get_session().get(path)
  8914. hf_raise_for_status(r)
  8915. return PaperInfo(**r.json())
  8916. def list_daily_papers(
  8917. self,
  8918. *,
  8919. date: Optional[str] = None,
  8920. token: Union[bool, str, None] = None,
  8921. week: Optional[str] = None,
  8922. month: Optional[str] = None,
  8923. submitter: Optional[str] = None,
  8924. sort: Optional[Literal["publishedAt", "trending"]] = None,
  8925. p: Optional[int] = None,
  8926. limit: Optional[int] = None,
  8927. ) -> Iterable[PaperInfo]:
  8928. """
  8929. List the daily papers published on a given date on the Hugging Face Hub.
  8930. Args:
  8931. date (`str`, *optional*):
  8932. Date in ISO format (YYYY-MM-DD) for which to fetch daily papers.
  8933. Defaults to most recent ones.
  8934. token (Union[bool, str, None], *optional*):
  8935. A valid user access token (string). Defaults to the locally saved
  8936. token. To disable authentication, pass `False`.
  8937. week (`str`, *optional*):
  8938. Week in ISO format (YYYY-Www) for which to fetch daily papers. Example, `2025-W09`.
  8939. month (`str`, *optional*):
  8940. Month in ISO format (YYYY-MM) for which to fetch daily papers. Example, `2025-02`.
  8941. submitter (`str`, *optional*):
  8942. Username of the submitter to filter daily papers.
  8943. sort (`Literal["publishedAt", "trending"]`, *optional*):
  8944. Sort order for the daily papers. Can be either by `publishedAt` or by `trending`.
  8945. Defaults to `"publishedAt"`
  8946. p (`int`, *optional*):
  8947. Page number for pagination. Defaults to 0.
  8948. limit (`int`, *optional*):
  8949. Limit of papers to fetch. Defaults to 50.
  8950. Returns:
  8951. `Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects.
  8952. Example:
  8953. ```python
  8954. >>> from huggingface_hub import HfApi
  8955. >>> api = HfApi()
  8956. >>> list(api.list_daily_papers(date="2025-10-29"))
  8957. ```
  8958. """
  8959. path = f"{self.endpoint}/api/daily_papers"
  8960. params = {
  8961. k: v
  8962. for k, v in {
  8963. "p": p,
  8964. "limit": limit,
  8965. "sort": sort,
  8966. "date": date,
  8967. "week": week,
  8968. "month": month,
  8969. "submitter": submitter,
  8970. }.items()
  8971. if v is not None
  8972. }
  8973. r = get_session().get(path, params=params, headers=self._build_hf_headers(token=token))
  8974. hf_raise_for_status(r)
  8975. for paper in r.json():
  8976. yield PaperInfo(**paper)
  8977. def auth_check(
  8978. self, repo_id: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  8979. ) -> None:
  8980. """
  8981. Check if the provided user token has access to a specific repository on the Hugging Face Hub.
  8982. This method verifies whether the user, authenticated via the provided token, has access to the specified
  8983. repository. If the repository is not found or if the user lacks the required permissions to access it,
  8984. the method raises an appropriate exception.
  8985. Args:
  8986. repo_id (`str`):
  8987. The repository to check for access. Format should be `"user/repo_name"`.
  8988. Example: `"user/my-cool-model"`.
  8989. repo_type (`str`, *optional*):
  8990. The type of the repository. Should be one of `"model"`, `"dataset"`, or `"space"`.
  8991. If not specified, the default is `"model"`.
  8992. token `(Union[bool, str, None]`, *optional*):
  8993. A valid user access token. If not provided, the locally saved token will be used, which is the
  8994. recommended authentication method. Set to `False` to disable authentication.
  8995. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  8996. Raises:
  8997. [`~utils.RepositoryNotFoundError`]:
  8998. Raised if the repository does not exist, is private, or the user does not have access. This can
  8999. occur if the `repo_id` or `repo_type` is incorrect or if the repository is private but the user
  9000. is not authenticated.
  9001. [`~utils.GatedRepoError`]:
  9002. Raised if the repository exists but is gated and the user is not authorized to access it.
  9003. Example:
  9004. Check if the user has access to a repository:
  9005. ```python
  9006. >>> from huggingface_hub import auth_check
  9007. >>> from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
  9008. try:
  9009. auth_check("user/my-cool-model")
  9010. except GatedRepoError:
  9011. # Handle gated repository error
  9012. print("You do not have permission to access this gated repository.")
  9013. except RepositoryNotFoundError:
  9014. # Handle repository not found error
  9015. print("The repository was not found or you do not have access.")
  9016. ```
  9017. In this example:
  9018. - If the user has access, the method completes successfully.
  9019. - If the repository is gated or does not exist, appropriate exceptions are raised, allowing the user
  9020. to handle them accordingly.
  9021. """
  9022. headers = self._build_hf_headers(token=token)
  9023. if repo_type is None:
  9024. repo_type = constants.REPO_TYPE_MODEL
  9025. if repo_type not in constants.REPO_TYPES:
  9026. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  9027. path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/auth-check"
  9028. r = get_session().get(path, headers=headers)
  9029. hf_raise_for_status(r)
  9030. def run_job(
  9031. self,
  9032. *,
  9033. image: str,
  9034. command: list[str],
  9035. env: Optional[dict[str, Any]] = None,
  9036. secrets: Optional[dict[str, Any]] = None,
  9037. flavor: Optional[SpaceHardware] = None,
  9038. timeout: Optional[Union[int, float, str]] = None,
  9039. namespace: Optional[str] = None,
  9040. token: Union[bool, str, None] = None,
  9041. ) -> JobInfo:
  9042. """
  9043. Run compute Jobs on Hugging Face infrastructure.
  9044. Args:
  9045. image (`str`):
  9046. The Docker image to use.
  9047. Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`.
  9048. Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`.
  9049. command (`list[str]`):
  9050. The command to run. Example: `["echo", "hello"]`.
  9051. env (`dict[str, Any]`, *optional*):
  9052. Defines the environment variables for the Job.
  9053. secrets (`dict[str, Any]`, *optional*):
  9054. Defines the secret environment variables for the Job.
  9055. flavor (`str`, *optional*):
  9056. Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
  9057. Defaults to `"cpu-basic"`.
  9058. timeout (`Union[int, float, str]`, *optional*):
  9059. Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days).
  9060. Example: `300` or `"5m"` for 5 minutes.
  9061. namespace (`str`, *optional*):
  9062. The namespace where the Job will be created. Defaults to the current user's namespace.
  9063. token `(Union[bool, str, None]`, *optional*):
  9064. A valid user access token. If not provided, the locally saved token will be used, which is the
  9065. recommended authentication method. Set to `False` to disable authentication.
  9066. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9067. Example:
  9068. Run your first Job:
  9069. ```python
  9070. >>> from huggingface_hub import run_job
  9071. >>> run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
  9072. ```
  9073. Run a GPU Job:
  9074. ```python
  9075. >>> from huggingface_hub import run_job
  9076. >>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
  9077. >>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
  9078. >>> run_job(image=image, command=command, flavor="a10g-small")
  9079. ```
  9080. """
  9081. if namespace is None:
  9082. namespace = self.whoami(token=token)["name"]
  9083. job_spec = _create_job_spec(
  9084. image=image,
  9085. command=command,
  9086. env=env,
  9087. secrets=secrets,
  9088. flavor=flavor,
  9089. timeout=timeout,
  9090. )
  9091. response = get_session().post(
  9092. f"{self.endpoint}/api/jobs/{namespace}",
  9093. json=job_spec,
  9094. headers=self._build_hf_headers(token=token),
  9095. )
  9096. hf_raise_for_status(response)
  9097. job_info = response.json()
  9098. return JobInfo(**job_info, endpoint=self.endpoint)
  9099. def _fetch_running_job_sse(
  9100. self,
  9101. *,
  9102. job_id: str,
  9103. route: str,
  9104. timeout: int,
  9105. skip_previous_events_on_retry: bool,
  9106. double_check_job_has_finished_on_status_code_or_error: tuple[Union[int, Type[Exception]], ...],
  9107. namespace: Optional[str] = None,
  9108. token: Union[bool, str, None] = None,
  9109. ) -> Iterable[dict[str, Any]]:
  9110. if namespace is None:
  9111. namespace = self.whoami(token=token)["name"]
  9112. # We don't use http_backoff since we need to check ourselves if the job is still running
  9113. nb_tries = 0
  9114. max_retries = 5
  9115. min_wait_time = 1
  9116. max_wait_time = 10
  9117. sleep_time = 0
  9118. start_event_idx = 0
  9119. error_to_retry = None
  9120. while True:
  9121. if error_to_retry is not None:
  9122. logger.warning(f"'{error_to_retry}' thrown while requesting jobs /{route} for {job_id=}")
  9123. logger.warning(f"Retrying in {sleep_time}s [Retry {nb_tries}/{max_retries}].")
  9124. error_to_retry = None
  9125. time.sleep(sleep_time)
  9126. try:
  9127. with get_session().stream(
  9128. "GET",
  9129. f"{self.endpoint}/api/jobs/{namespace}/{job_id}/{route}",
  9130. headers=self._build_hf_headers(token=token),
  9131. timeout=timeout,
  9132. ) as response:
  9133. if response.status_code == 200:
  9134. event_idx = -1
  9135. for line in response.iter_lines():
  9136. if line and line.startswith("data: {"):
  9137. event_idx += 1
  9138. if event_idx >= start_event_idx:
  9139. if skip_previous_events_on_retry:
  9140. start_event_idx += 1
  9141. yield json.loads(line[len("data: ") :])
  9142. break
  9143. elif response.status_code not in double_check_job_has_finished_on_status_code_or_error:
  9144. hf_raise_for_status(response)
  9145. except httpx.HTTPStatusError:
  9146. raise
  9147. except httpx.DecodingError:
  9148. # Response ended prematurely
  9149. break
  9150. except KeyboardInterrupt:
  9151. break
  9152. except (httpx.HTTPError, httpcore.TimeoutException) as err:
  9153. is_no_new_line_timeout = (
  9154. isinstance(err, httpx.NetworkError)
  9155. and err.__context__
  9156. and isinstance(getattr(err.__context__, "__cause__", None), TimeoutError)
  9157. )
  9158. if is_no_new_line_timeout:
  9159. # job is likely finished
  9160. pass
  9161. elif type(err) in double_check_job_has_finished_on_status_code_or_error:
  9162. pass
  9163. elif nb_tries >= max_retries:
  9164. raise
  9165. else:
  9166. nb_tries += 1
  9167. sleep_time = min(max_wait_time, max(min_wait_time, sleep_time * 2))
  9168. error_to_retry = err
  9169. job_status_response = get_session().get(
  9170. f"{self.endpoint}/api/jobs/{namespace}/{job_id}",
  9171. headers=self._build_hf_headers(token=token),
  9172. )
  9173. hf_raise_for_status(job_status_response)
  9174. job_status = job_status_response.json()
  9175. if "status" in job_status and job_status["status"]["stage"] not in ("RUNNING", "UPDATING"):
  9176. break
  9177. def fetch_job_logs(
  9178. self,
  9179. *,
  9180. job_id: str,
  9181. namespace: Optional[str] = None,
  9182. token: Union[bool, str, None] = None,
  9183. ) -> Iterable[str]:
  9184. """
  9185. Fetch all the logs from a compute Job on Hugging Face infrastructure.
  9186. Args:
  9187. job_id (`str`):
  9188. ID of the Job.
  9189. namespace (`str`, *optional*):
  9190. The namespace where the Job is running. Defaults to the current user's namespace.
  9191. token `(Union[bool, str, None]`, *optional*):
  9192. A valid user access token. If not provided, the locally saved token will be used, which is the
  9193. recommended authentication method. Set to `False` to disable authentication.
  9194. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9195. Example:
  9196. ```python
  9197. >>> from huggingface_hub import fetch_job_logs, run_job
  9198. >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
  9199. >>> for log in fetch_job_logs(job_id=job.id):
  9200. ... print(log)
  9201. Hello from HF compute!
  9202. ```
  9203. """
  9204. # - We need to retry because sometimes the /logs doesn't return logs when the job just started.
  9205. # (for example it can return only two lines: one for "Job started" and one empty line)
  9206. # - Timeouts can happen in case of build errors
  9207. # - ChunkedEncodingError can happen in case of stopped logging in the middle of streaming
  9208. # - Infinite empty log stream can happen in case of build error
  9209. # (the logs stream is infinite and empty except for the Job started message)
  9210. # - there is a ": keep-alive" every 30 seconds
  9211. seconds_between_keep_alive = 30
  9212. for event in self._fetch_running_job_sse(
  9213. job_id=job_id,
  9214. route="logs",
  9215. timeout=4 * seconds_between_keep_alive,
  9216. skip_previous_events_on_retry=True,
  9217. double_check_job_has_finished_on_status_code_or_error=tuple(),
  9218. namespace=namespace,
  9219. token=token,
  9220. ):
  9221. # timestamp = event["timestamp"]
  9222. if not event["data"].startswith("===== Job started"):
  9223. log = event["data"]
  9224. yield log
  9225. def fetch_job_metrics(
  9226. self,
  9227. *,
  9228. job_id: str,
  9229. namespace: Optional[str] = None,
  9230. token: Union[bool, str, None] = None,
  9231. ) -> Iterable[dict[str, Any]]:
  9232. """
  9233. Fetch all the live metrics from a compute Job on Hugging Face infrastructure.
  9234. Args:
  9235. job_id (`str`):
  9236. ID of the Job.
  9237. namespace (`str`, *optional*):
  9238. The namespace where the Job is running. Defaults to the current user's namespace.
  9239. token `(Union[bool, str, None]`, *optional*):
  9240. A valid user access token. If not provided, the locally saved token will be used, which is the
  9241. recommended authentication method. Set to `False` to disable authentication.
  9242. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9243. Example:
  9244. ```python
  9245. >>> from huggingface_hub import fetch_job_metrics, run_job
  9246. >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], flavor="a10g-small")
  9247. >>> for metrics in fetch_job_metrics(job_id=job.id):
  9248. ... print(metrics)
  9249. {
  9250. "cpu_usage_pct": 0,
  9251. "cpu_millicores": 3500,
  9252. "memory_used_bytes": 1306624,
  9253. "memory_total_bytes": 15032385536,
  9254. "rx_bps": 0,
  9255. "tx_bps": 0,
  9256. "gpus": {
  9257. "882fa930": {
  9258. "utilization": 0,
  9259. "memory_used_bytes": 0,
  9260. "memory_total_bytes": 22836000000
  9261. }
  9262. },
  9263. "replica": "57vr7"
  9264. }
  9265. ```
  9266. """
  9267. # - there is one "metric" event every second, like this:
  9268. # event: metric
  9269. # data: {"cpu_usage_pct":0,"cpu_millicores":3500,"memory_used_bytes":1417216,"memory_total_bytes":15032385536,"rx_bps":0,"tx_bps":0,"gpus":{"d901cd7f":{"utilization":0,"memory_used_bytes":0,"memory_total_bytes":22836000000}},"replica":"j6qz9"}
  9270. # - the stream doesn't end when the job finishes, so we rely on timeouts (httpx.NetworkError with Timeout as cause)
  9271. # - httpx.ReadTimeout can happen if the job is marked as running but the hardware is not available yet, that we can ignore
  9272. # - it returns an internal error 500 if the job has already finished, we simply ignore it
  9273. # - ChunkedEncodingError can happen in case of stopped logging in the middle of streaming
  9274. # - there is a ": keep-alive" every 30 seconds
  9275. seconds_between_events = 1
  9276. yield from self._fetch_running_job_sse(
  9277. job_id=job_id,
  9278. route="metrics",
  9279. timeout=10 * seconds_between_events,
  9280. skip_previous_events_on_retry=False,
  9281. double_check_job_has_finished_on_status_code_or_error=(500, httpx.ReadTimeout),
  9282. namespace=namespace,
  9283. token=token,
  9284. )
  9285. def list_jobs(
  9286. self,
  9287. *,
  9288. timeout: Optional[int] = None,
  9289. namespace: Optional[str] = None,
  9290. token: Union[bool, str, None] = None,
  9291. ) -> list[JobInfo]:
  9292. """
  9293. List compute Jobs on Hugging Face infrastructure.
  9294. Args:
  9295. timeout (`float`, *optional*):
  9296. Whether to set a timeout for the request to the Hub.
  9297. namespace (`str`, *optional*):
  9298. The namespace from where it lists the jobs. Defaults to the current user's namespace.
  9299. token `(Union[bool, str, None]`, *optional*):
  9300. A valid user access token. If not provided, the locally saved token will be used, which is the
  9301. recommended authentication method. Set to `False` to disable authentication.
  9302. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9303. """
  9304. if namespace is None:
  9305. namespace = whoami(token=token)["name"]
  9306. response = get_session().get(
  9307. f"{self.endpoint}/api/jobs/{namespace}",
  9308. headers=self._build_hf_headers(token=token),
  9309. timeout=timeout,
  9310. )
  9311. response.raise_for_status()
  9312. return [JobInfo(**job_info, endpoint=self.endpoint) for job_info in response.json()]
  9313. def list_jobs_hardware(self, token: Union[bool, str, None] = None) -> list[JobHardware]:
  9314. """
  9315. List available hardware options for Jobs on Hugging Face infrastructure.
  9316. Returns:
  9317. `list[JobHardware]`: A list of available hardware configurations.
  9318. Example:
  9319. ```python
  9320. >>> from huggingface_hub import HfApi
  9321. >>> api = HfApi()
  9322. >>> hardware_list = api.list_jobs_hardware()
  9323. >>> hardware_list[0]
  9324. JobHardware(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute')
  9325. >>> hardware_list[0].name
  9326. 'cpu-basic'
  9327. # Filter GPU options
  9328. >>> gpu_hardware = [hw for hw in hardware_list if hw.accelerator is not None]
  9329. >>> gpu_hardware[0].accelerator.model
  9330. 'T4'
  9331. ```
  9332. """
  9333. response = get_session().get(f"{self.endpoint}/api/jobs/hardware", headers=self._build_hf_headers(token=token))
  9334. hf_raise_for_status(response)
  9335. return [JobHardware(**hardware) for hardware in response.json()]
  9336. def inspect_job(
  9337. self,
  9338. *,
  9339. job_id: str,
  9340. namespace: Optional[str] = None,
  9341. token: Union[bool, str, None] = None,
  9342. ) -> JobInfo:
  9343. """
  9344. Inspect a compute Job on Hugging Face infrastructure.
  9345. Args:
  9346. job_id (`str`):
  9347. ID of the Job.
  9348. namespace (`str`, *optional*):
  9349. The namespace where the Job is running. Defaults to the current user's namespace.
  9350. token `(Union[bool, str, None]`, *optional*):
  9351. A valid user access token. If not provided, the locally saved token will be used, which is the
  9352. recommended authentication method. Set to `False` to disable authentication.
  9353. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9354. Example:
  9355. ```python
  9356. >>> from huggingface_hub import inspect_job, run_job
  9357. >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
  9358. >>> inspect_job(job.id)
  9359. JobInfo(
  9360. id='68780d00bbe36d38803f645f',
  9361. created_at=datetime.datetime(2025, 7, 16, 20, 35, 12, 808000, tzinfo=datetime.timezone.utc),
  9362. docker_image='python:3.12',
  9363. space_id=None,
  9364. command=['python', '-c', "print('Hello from HF compute!')"],
  9365. arguments=[],
  9366. environment={},
  9367. secrets={},
  9368. flavor='cpu-basic',
  9369. status=JobStatus(stage='RUNNING', message=None)
  9370. )
  9371. ```
  9372. """
  9373. if namespace is None:
  9374. namespace = self.whoami(token=token)["name"]
  9375. response = get_session().get(
  9376. f"{self.endpoint}/api/jobs/{namespace}/{job_id}",
  9377. headers=self._build_hf_headers(token=token),
  9378. )
  9379. response.raise_for_status()
  9380. return JobInfo(**response.json(), endpoint=self.endpoint)
  9381. def cancel_job(
  9382. self,
  9383. *,
  9384. job_id: str,
  9385. namespace: Optional[str] = None,
  9386. token: Union[bool, str, None] = None,
  9387. ) -> None:
  9388. """
  9389. Cancel a compute Job on Hugging Face infrastructure.
  9390. Args:
  9391. job_id (`str`):
  9392. ID of the Job.
  9393. namespace (`str`, *optional*):
  9394. The namespace where the Job is running. Defaults to the current user's namespace.
  9395. token `(Union[bool, str, None]`, *optional*):
  9396. A valid user access token. If not provided, the locally saved token will be used, which is the
  9397. recommended authentication method. Set to `False` to disable authentication.
  9398. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9399. """
  9400. if namespace is None:
  9401. namespace = self.whoami(token=token)["name"]
  9402. get_session().post(
  9403. f"{self.endpoint}/api/jobs/{namespace}/{job_id}/cancel",
  9404. headers=self._build_hf_headers(token=token),
  9405. ).raise_for_status()
  9406. @experimental
  9407. def run_uv_job(
  9408. self,
  9409. script: str,
  9410. *,
  9411. script_args: Optional[list[str]] = None,
  9412. dependencies: Optional[list[str]] = None,
  9413. python: Optional[str] = None,
  9414. image: Optional[str] = None,
  9415. env: Optional[dict[str, Any]] = None,
  9416. secrets: Optional[dict[str, Any]] = None,
  9417. flavor: Optional[SpaceHardware] = None,
  9418. timeout: Optional[Union[int, float, str]] = None,
  9419. namespace: Optional[str] = None,
  9420. token: Union[bool, str, None] = None,
  9421. ) -> JobInfo:
  9422. """
  9423. Run a UV script Job on Hugging Face infrastructure.
  9424. Args:
  9425. script (`str`):
  9426. Path or URL of the UV script, or a command.
  9427. script_args (`list[str]`, *optional*)
  9428. Arguments to pass to the script or command.
  9429. dependencies (`list[str]`, *optional*)
  9430. Dependencies to use to run the UV script.
  9431. python (`str`, *optional*)
  9432. Use a specific Python version. Default is 3.12.
  9433. image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"):
  9434. Use a custom Docker image with `uv` installed.
  9435. env (`dict[str, Any]`, *optional*):
  9436. Defines the environment variables for the Job.
  9437. secrets (`dict[str, Any]`, *optional*):
  9438. Defines the secret environment variables for the Job.
  9439. flavor (`str`, *optional*):
  9440. Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
  9441. Defaults to `"cpu-basic"`.
  9442. timeout (`Union[int, float, str]`, *optional*):
  9443. Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days).
  9444. Example: `300` or `"5m"` for 5 minutes.
  9445. namespace (`str`, *optional*):
  9446. The namespace where the Job will be created. Defaults to the current user's namespace.
  9447. token `(Union[bool, str, None]`, *optional*):
  9448. A valid user access token. If not provided, the locally saved token will be used, which is the
  9449. recommended authentication method. Set to `False` to disable authentication.
  9450. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9451. Example:
  9452. Run a script from a URL:
  9453. ```python
  9454. >>> from huggingface_hub import run_uv_job
  9455. >>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
  9456. >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
  9457. >>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")
  9458. ```
  9459. Run a local script:
  9460. ```python
  9461. >>> from huggingface_hub import run_uv_job
  9462. >>> script = "my_sft.py"
  9463. >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
  9464. >>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")
  9465. ```
  9466. Run a command:
  9467. ```python
  9468. >>> from huggingface_hub import run_uv_job
  9469. >>> script = "lighteval"
  9470. >>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
  9471. >>> run_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small")
  9472. ```
  9473. """
  9474. image = image or "ghcr.io/astral-sh/uv:python3.12-bookworm"
  9475. env = env or {}
  9476. secrets = secrets or {}
  9477. # Build command
  9478. command, env, secrets = self._create_uv_command_env_and_secrets(
  9479. script=script,
  9480. script_args=script_args,
  9481. dependencies=dependencies,
  9482. python=python,
  9483. env=env,
  9484. secrets=secrets,
  9485. namespace=namespace,
  9486. token=token,
  9487. )
  9488. # Create RunCommand args
  9489. return self.run_job(
  9490. image=image,
  9491. command=command,
  9492. env=env,
  9493. secrets=secrets,
  9494. flavor=flavor,
  9495. timeout=timeout,
  9496. namespace=namespace,
  9497. token=token,
  9498. )
  9499. def create_scheduled_job(
  9500. self,
  9501. *,
  9502. image: str,
  9503. command: list[str],
  9504. schedule: str,
  9505. suspend: Optional[bool] = None,
  9506. concurrency: Optional[bool] = None,
  9507. env: Optional[dict[str, Any]] = None,
  9508. secrets: Optional[dict[str, Any]] = None,
  9509. flavor: Optional[SpaceHardware] = None,
  9510. timeout: Optional[Union[int, float, str]] = None,
  9511. namespace: Optional[str] = None,
  9512. token: Union[bool, str, None] = None,
  9513. ) -> ScheduledJobInfo:
  9514. """
  9515. Create scheduled compute Jobs on Hugging Face infrastructure.
  9516. Args:
  9517. image (`str`):
  9518. The Docker image to use.
  9519. Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`.
  9520. Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`.
  9521. command (`list[str]`):
  9522. The command to run. Example: `["echo", "hello"]`.
  9523. schedule (`str`):
  9524. One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
  9525. CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
  9526. suspend (`bool`, *optional*):
  9527. If True, the scheduled Job is suspended (paused). Defaults to False.
  9528. concurrency (`bool`, *optional*):
  9529. If True, multiple instances of this Job can run concurrently. Defaults to False.
  9530. env (`dict[str, Any]`, *optional*):
  9531. Defines the environment variables for the Job.
  9532. secrets (`dict[str, Any]`, *optional*):
  9533. Defines the secret environment variables for the Job.
  9534. flavor (`str`, *optional*):
  9535. Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
  9536. Defaults to `"cpu-basic"`.
  9537. timeout (`Union[int, float, str]`, *optional*):
  9538. Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days).
  9539. Example: `300` or `"5m"` for 5 minutes.
  9540. namespace (`str`, *optional*):
  9541. The namespace where the Job will be created. Defaults to the current user's namespace.
  9542. token `(Union[bool, str, None]`, *optional*):
  9543. A valid user access token. If not provided, the locally saved token will be used, which is the
  9544. recommended authentication method. Set to `False` to disable authentication.
  9545. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9546. Example:
  9547. Create your first scheduled Job:
  9548. ```python
  9549. >>> from huggingface_hub import create_scheduled_job
  9550. >>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")
  9551. ```
  9552. Use a CRON schedule expression:
  9553. ```python
  9554. >>> from huggingface_hub import create_scheduled_job
  9555. >>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('this runs every 5min')"], schedule="*/5 * * * *")
  9556. ```
  9557. Create a scheduled GPU Job:
  9558. ```python
  9559. >>> from huggingface_hub import create_scheduled_job
  9560. >>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
  9561. >>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
  9562. >>> create_scheduled_job(image, command, flavor="a10g-small", schedule="@hourly")
  9563. ```
  9564. """
  9565. if namespace is None:
  9566. namespace = self.whoami(token=token)["name"]
  9567. # prepare payload to send to HF Jobs API
  9568. job_spec = _create_job_spec(
  9569. image=image,
  9570. command=command,
  9571. env=env,
  9572. secrets=secrets,
  9573. flavor=flavor,
  9574. timeout=timeout,
  9575. )
  9576. input_json: dict[str, Any] = {
  9577. "jobSpec": job_spec,
  9578. "schedule": schedule,
  9579. }
  9580. if concurrency is not None:
  9581. input_json["concurrency"] = concurrency
  9582. if suspend is not None:
  9583. input_json["suspend"] = suspend
  9584. response = get_session().post(
  9585. f"{self.endpoint}/api/scheduled-jobs/{namespace}",
  9586. json=input_json,
  9587. headers=self._build_hf_headers(token=token),
  9588. )
  9589. hf_raise_for_status(response)
  9590. scheduled_job_info = response.json()
  9591. return ScheduledJobInfo(**scheduled_job_info)
  9592. def list_scheduled_jobs(
  9593. self,
  9594. *,
  9595. timeout: Optional[int] = None,
  9596. namespace: Optional[str] = None,
  9597. token: Union[bool, str, None] = None,
  9598. ) -> list[ScheduledJobInfo]:
  9599. """
  9600. List scheduled compute Jobs on Hugging Face infrastructure.
  9601. Args:
  9602. timeout (`float`, *optional*):
  9603. Whether to set a timeout for the request to the Hub.
  9604. namespace (`str`, *optional*):
  9605. The namespace from where it lists the jobs. Defaults to the current user's namespace.
  9606. token `(Union[bool, str, None]`, *optional*):
  9607. A valid user access token. If not provided, the locally saved token will be used, which is the
  9608. recommended authentication method. Set to `False` to disable authentication.
  9609. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9610. """
  9611. if namespace is None:
  9612. namespace = self.whoami(token=token)["name"]
  9613. response = get_session().get(
  9614. f"{self.endpoint}/api/scheduled-jobs/{namespace}",
  9615. headers=self._build_hf_headers(token=token),
  9616. timeout=timeout,
  9617. )
  9618. hf_raise_for_status(response)
  9619. return [ScheduledJobInfo(**scheduled_job_info) for scheduled_job_info in response.json()]
  9620. def inspect_scheduled_job(
  9621. self,
  9622. *,
  9623. scheduled_job_id: str,
  9624. namespace: Optional[str] = None,
  9625. token: Union[bool, str, None] = None,
  9626. ) -> ScheduledJobInfo:
  9627. """
  9628. Inspect a scheduled compute Job on Hugging Face infrastructure.
  9629. Args:
  9630. scheduled_job_id (`str`):
  9631. ID of the scheduled Job.
  9632. namespace (`str`, *optional*):
  9633. The namespace where the scheduled Job is. Defaults to the current user's namespace.
  9634. token `(Union[bool, str, None]`, *optional*):
  9635. A valid user access token. If not provided, the locally saved token will be used, which is the
  9636. recommended authentication method. Set to `False` to disable authentication.
  9637. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9638. Example:
  9639. ```python
  9640. >>> from huggingface_hub import inspect_job, create_scheduled_job
  9641. >>> scheduled_job = create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")
  9642. >>> inspect_scheduled_job(scheduled_job.id)
  9643. ```
  9644. """
  9645. if namespace is None:
  9646. namespace = self.whoami(token=token)["name"]
  9647. response = get_session().get(
  9648. f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}",
  9649. headers=self._build_hf_headers(token=token),
  9650. )
  9651. hf_raise_for_status(response)
  9652. return ScheduledJobInfo(**response.json())
  9653. def delete_scheduled_job(
  9654. self,
  9655. *,
  9656. scheduled_job_id: str,
  9657. namespace: Optional[str] = None,
  9658. token: Union[bool, str, None] = None,
  9659. ) -> None:
  9660. """
  9661. Delete a scheduled compute Job on Hugging Face infrastructure.
  9662. Args:
  9663. scheduled_job_id (`str`):
  9664. ID of the scheduled Job.
  9665. namespace (`str`, *optional*):
  9666. The namespace where the scheduled Job is. Defaults to the current user's namespace.
  9667. token `(Union[bool, str, None]`, *optional*):
  9668. A valid user access token. If not provided, the locally saved token will be used, which is the
  9669. recommended authentication method. Set to `False` to disable authentication.
  9670. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9671. """
  9672. if namespace is None:
  9673. namespace = self.whoami(token=token)["name"]
  9674. response = get_session().delete(
  9675. f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}",
  9676. headers=self._build_hf_headers(token=token),
  9677. )
  9678. hf_raise_for_status(response)
  9679. def suspend_scheduled_job(
  9680. self,
  9681. *,
  9682. scheduled_job_id: str,
  9683. namespace: Optional[str] = None,
  9684. token: Union[bool, str, None] = None,
  9685. ) -> None:
  9686. """
  9687. Suspend (pause) a scheduled compute Job on Hugging Face infrastructure.
  9688. Args:
  9689. scheduled_job_id (`str`):
  9690. ID of the scheduled Job.
  9691. namespace (`str`, *optional*):
  9692. The namespace where the scheduled Job is. Defaults to the current user's namespace.
  9693. token `(Union[bool, str, None]`, *optional*):
  9694. A valid user access token. If not provided, the locally saved token will be used, which is the
  9695. recommended authentication method. Set to `False` to disable authentication.
  9696. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9697. """
  9698. if namespace is None:
  9699. namespace = self.whoami(token=token)["name"]
  9700. get_session().post(
  9701. f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}/suspend",
  9702. headers=self._build_hf_headers(token=token),
  9703. ).raise_for_status()
  9704. def resume_scheduled_job(
  9705. self,
  9706. *,
  9707. scheduled_job_id: str,
  9708. namespace: Optional[str] = None,
  9709. token: Union[bool, str, None] = None,
  9710. ) -> None:
  9711. """
  9712. Resume (unpause) a scheduled compute Job on Hugging Face infrastructure.
  9713. Args:
  9714. scheduled_job_id (`str`):
  9715. ID of the scheduled Job.
  9716. namespace (`str`, *optional*):
  9717. The namespace where the scheduled Job is. Defaults to the current user's namespace.
  9718. token `(Union[bool, str, None]`, *optional*):
  9719. A valid user access token. If not provided, the locally saved token will be used, which is the
  9720. recommended authentication method. Set to `False` to disable authentication.
  9721. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9722. """
  9723. if namespace is None:
  9724. namespace = self.whoami(token=token)["name"]
  9725. get_session().post(
  9726. f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}/resume",
  9727. headers=self._build_hf_headers(token=token),
  9728. ).raise_for_status()
  9729. @experimental
  9730. def create_scheduled_uv_job(
  9731. self,
  9732. script: str,
  9733. *,
  9734. script_args: Optional[list[str]] = None,
  9735. schedule: str,
  9736. suspend: Optional[bool] = None,
  9737. concurrency: Optional[bool] = None,
  9738. dependencies: Optional[list[str]] = None,
  9739. python: Optional[str] = None,
  9740. image: Optional[str] = None,
  9741. env: Optional[dict[str, Any]] = None,
  9742. secrets: Optional[dict[str, Any]] = None,
  9743. flavor: Optional[SpaceHardware] = None,
  9744. timeout: Optional[Union[int, float, str]] = None,
  9745. namespace: Optional[str] = None,
  9746. token: Union[bool, str, None] = None,
  9747. ) -> ScheduledJobInfo:
  9748. """
  9749. Run a UV script Job on Hugging Face infrastructure.
  9750. Args:
  9751. script (`str`):
  9752. Path or URL of the UV script, or a command.
  9753. script_args (`list[str]`, *optional*)
  9754. Arguments to pass to the script, or a command.
  9755. schedule (`str`):
  9756. One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
  9757. CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
  9758. suspend (`bool`, *optional*):
  9759. If True, the scheduled Job is suspended (paused). Defaults to False.
  9760. concurrency (`bool`, *optional*):
  9761. If True, multiple instances of this Job can run concurrently. Defaults to False.
  9762. dependencies (`list[str]`, *optional*)
  9763. Dependencies to use to run the UV script.
  9764. python (`str`, *optional*)
  9765. Use a specific Python version. Default is 3.12.
  9766. image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"):
  9767. Use a custom Docker image with `uv` installed.
  9768. env (`dict[str, Any]`, *optional*):
  9769. Defines the environment variables for the Job.
  9770. secrets (`dict[str, Any]`, *optional*):
  9771. Defines the secret environment variables for the Job.
  9772. flavor (`str`, *optional*):
  9773. Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
  9774. Defaults to `"cpu-basic"`.
  9775. timeout (`Union[int, float, str]`, *optional*):
  9776. Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days).
  9777. Example: `300` or `"5m"` for 5 minutes.
  9778. namespace (`str`, *optional*):
  9779. The namespace where the Job will be created. Defaults to the current user's namespace.
  9780. token `(Union[bool, str, None]`, *optional*):
  9781. A valid user access token. If not provided, the locally saved token will be used, which is the
  9782. recommended authentication method. Set to `False` to disable authentication.
  9783. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9784. Example:
  9785. Schedule a script from a URL:
  9786. ```python
  9787. >>> from huggingface_hub import create_scheduled_uv_job
  9788. >>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
  9789. >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
  9790. >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")
  9791. ```
  9792. Schedule a local script:
  9793. ```python
  9794. >>> from huggingface_hub import create_scheduled_uv_job
  9795. >>> script = "my_sft.py"
  9796. >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
  9797. >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")
  9798. ```
  9799. Schedule a command:
  9800. ```python
  9801. >>> from huggingface_hub import create_scheduled_uv_job
  9802. >>> script = "lighteval"
  9803. >>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
  9804. >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small", schedule="@weekly")
  9805. ```
  9806. """
  9807. image = image or "ghcr.io/astral-sh/uv:python3.12-bookworm"
  9808. # Build command
  9809. command, env, secrets = self._create_uv_command_env_and_secrets(
  9810. script=script,
  9811. script_args=script_args,
  9812. dependencies=dependencies,
  9813. python=python,
  9814. env=env,
  9815. secrets=secrets,
  9816. namespace=namespace,
  9817. token=token,
  9818. )
  9819. # Create RunCommand args
  9820. return self.create_scheduled_job(
  9821. image=image,
  9822. command=command,
  9823. schedule=schedule,
  9824. suspend=suspend,
  9825. concurrency=concurrency,
  9826. env=env,
  9827. secrets=secrets,
  9828. flavor=flavor,
  9829. timeout=timeout,
  9830. namespace=namespace,
  9831. token=token,
  9832. )
  9833. def _create_uv_command_env_and_secrets(
  9834. self,
  9835. *,
  9836. script: str,
  9837. script_args: Optional[list[str]],
  9838. dependencies: Optional[list[str]],
  9839. python: Optional[str],
  9840. env: Optional[dict[str, Any]],
  9841. secrets: Optional[dict[str, Any]],
  9842. namespace: Optional[str],
  9843. token: Union[bool, str, None],
  9844. ) -> tuple[list[str], dict[str, Any], dict[str, Any]]:
  9845. env = env or {}
  9846. secrets = secrets or {}
  9847. # Build command
  9848. uv_args = []
  9849. if dependencies:
  9850. for dependency in dependencies:
  9851. uv_args += ["--with", dependency]
  9852. if python:
  9853. uv_args += ["--python", python]
  9854. script_args = script_args or []
  9855. if namespace is None:
  9856. namespace = self.whoami(token=token)["name"]
  9857. is_url = script.startswith("http://") or script.startswith("https://")
  9858. if is_url or not Path(script).is_file():
  9859. # Direct URL execution or command - no upload needed
  9860. command = ["uv", "run"] + uv_args + [script] + script_args
  9861. else:
  9862. # Local file - embed as env variable
  9863. script_content = base64.b64encode(Path(script).read_bytes()).decode()
  9864. env["UV_SCRIPT_ENCODED"] = script_content
  9865. command = [
  9866. "bash",
  9867. "-c",
  9868. f'echo "$UV_SCRIPT_ENCODED" | base64 -d > /tmp/script.py && uv run {" ".join(uv_args)} /tmp/script.py {" ".join(script_args)}',
  9869. ]
  9870. return command, env, secrets
  9871. def _parse_revision_from_pr_url(pr_url: str) -> str:
  9872. """Safely parse revision number from a PR url.
  9873. Example:
  9874. ```py
  9875. >>> _parse_revision_from_pr_url("https://huggingface.co/bigscience/bloom/discussions/2")
  9876. "refs/pr/2"
  9877. ```
  9878. """
  9879. re_match = re.match(_REGEX_DISCUSSION_URL, pr_url)
  9880. if re_match is None:
  9881. raise RuntimeError(f"Unexpected response from the hub, expected a Pull Request URL but got: '{pr_url}'")
  9882. return f"refs/pr/{re_match[1]}"
  9883. def parse_local_safetensors_file_metadata(path: Union[str, Path]) -> SafetensorsFileMetadata:
  9884. """
  9885. Parse metadata from a local safetensors file.
  9886. For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
  9887. Args:
  9888. path (`str` or `Path`):
  9889. Path to the safetensors file.
  9890. Returns:
  9891. [`SafetensorsFileMetadata`]: information related to the safetensors file.
  9892. Raises:
  9893. [`SafetensorsParsingError`]:
  9894. If the safetensors file header couldn't be parsed correctly.
  9895. `FileNotFoundError`:
  9896. If the file does not exist.
  9897. Example:
  9898. ```py
  9899. >>> metadata = parse_local_safetensors_file_metadata("path/to/model.safetensors")
  9900. >>> metadata
  9901. SafetensorsFileMetadata(
  9902. metadata={'format': 'pt'},
  9903. tensors={'layer.weight': TensorInfo(dtype='F32', shape=[512, 512], ...}, ...}
  9904. )
  9905. >>> metadata.parameter_count
  9906. {'F32': 262144}
  9907. ```
  9908. """
  9909. path = Path(path)
  9910. filename = path.name
  9911. context_msg = f"path '{path}'"
  9912. with open(path, "rb") as f:
  9913. # 1. Read first 8 bytes and parse/validate metadata size using shared helper
  9914. size_bytes = f.read(8)
  9915. metadata_size = _get_safetensors_metadata_size(size_bytes, filename, context_msg)
  9916. # 2. Read metadata bytes
  9917. metadata_as_bytes = f.read(metadata_size)
  9918. if len(metadata_as_bytes) < metadata_size:
  9919. raise SafetensorsParsingError(
  9920. f"Failed to parse safetensors header for '{filename}' ({context_msg}): file is truncated. Expected "
  9921. f"{metadata_size} bytes of metadata but got {len(metadata_as_bytes)}."
  9922. )
  9923. # 3. Parse using shared helper
  9924. return _parse_safetensors_header(metadata_as_bytes, filename, context_msg)
  9925. def get_local_safetensors_metadata(path: Union[str, Path]) -> SafetensorsRepoMetadata:
  9926. """
  9927. Parse metadata for a local safetensors file or folder.
  9928. Supports:
  9929. - Single safetensors file (e.g., `model.safetensors`)
  9930. - Directory with non-sharded model (contains `model.safetensors`)
  9931. - Directory with sharded model (contains `model.safetensors.index.json`)
  9932. For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
  9933. Args:
  9934. path (`str` or `Path`):
  9935. Path to a safetensors file or directory containing safetensors files.
  9936. Returns:
  9937. [`SafetensorsRepoMetadata`]: information related to the safetensors repo.
  9938. Raises:
  9939. [`NotASafetensorsRepoError`]:
  9940. If the path is not a valid safetensors file or folder (i.e., doesn't have either a
  9941. `model.safetensors` or a `model.safetensors.index.json` file).
  9942. [`SafetensorsParsingError`]:
  9943. If a safetensors file header couldn't be parsed correctly.
  9944. `FileNotFoundError`:
  9945. If the path does not exist.
  9946. Example:
  9947. ```py
  9948. # Parse single safetensors file
  9949. >>> metadata = get_local_safetensors_metadata("path/to/model.safetensors")
  9950. >>> metadata
  9951. SafetensorsRepoMetadata(metadata=None, sharded=False, weight_map={...}, files_metadata={...})
  9952. # Parse directory with sharded model
  9953. >>> metadata = get_local_safetensors_metadata("path/to/model_folder")
  9954. >>> metadata
  9955. SafetensorsRepoMetadata(metadata={'total_size': ...}, sharded=True, weight_map={...}, files_metadata={...})
  9956. >>> len(metadata.files_metadata)
  9957. 3 # Number of safetensors shards
  9958. ```
  9959. """
  9960. path = Path(path)
  9961. # Case 1: Direct path to a safetensors file
  9962. if path.is_file():
  9963. file_metadata = parse_local_safetensors_file_metadata(path)
  9964. return SafetensorsRepoMetadata(
  9965. metadata=None,
  9966. sharded=False,
  9967. weight_map={tensor_name: path.name for tensor_name in file_metadata.tensors.keys()},
  9968. files_metadata={path.name: file_metadata},
  9969. )
  9970. # Case 2: Directory
  9971. if not path.is_dir():
  9972. raise FileNotFoundError(f"Path '{path}' does not exist.")
  9973. single_file_path = path / constants.SAFETENSORS_SINGLE_FILE
  9974. index_file_path = path / constants.SAFETENSORS_INDEX_FILE
  9975. # Case 2a: Non-sharded model (single model.safetensors file)
  9976. if single_file_path.exists():
  9977. file_metadata = parse_local_safetensors_file_metadata(single_file_path)
  9978. return SafetensorsRepoMetadata(
  9979. metadata=None,
  9980. sharded=False,
  9981. weight_map={
  9982. tensor_name: constants.SAFETENSORS_SINGLE_FILE for tensor_name in file_metadata.tensors.keys()
  9983. },
  9984. files_metadata={constants.SAFETENSORS_SINGLE_FILE: file_metadata},
  9985. )
  9986. # Case 2b: Sharded model (model.safetensors.index.json)
  9987. if index_file_path.exists():
  9988. with open(index_file_path) as f:
  9989. index = json.load(f)
  9990. weight_map = index.get("weight_map", {})
  9991. # Parse metadata from each shard
  9992. files_metadata = {}
  9993. for shard_filename in set(weight_map.values()):
  9994. shard_path = path / shard_filename
  9995. files_metadata[shard_filename] = parse_local_safetensors_file_metadata(shard_path)
  9996. return SafetensorsRepoMetadata(
  9997. metadata=index.get("metadata", None),
  9998. sharded=True,
  9999. weight_map=weight_map,
  10000. files_metadata=files_metadata,
  10001. )
  10002. # Not a valid safetensors folder
  10003. raise NotASafetensorsRepoError(
  10004. f"'{path}' is not a valid safetensors folder. Couldn't find '{constants.SAFETENSORS_INDEX_FILE}' or "
  10005. f"'{constants.SAFETENSORS_SINGLE_FILE}' files."
  10006. )
  10007. api = HfApi()
  10008. whoami = api.whoami
  10009. auth_check = api.auth_check
  10010. list_models = api.list_models
  10011. model_info = api.model_info
  10012. list_datasets = api.list_datasets
  10013. dataset_info = api.dataset_info
  10014. list_spaces = api.list_spaces
  10015. space_info = api.space_info
  10016. list_papers = api.list_papers
  10017. paper_info = api.paper_info
  10018. list_daily_papers = api.list_daily_papers
  10019. repo_exists = api.repo_exists
  10020. revision_exists = api.revision_exists
  10021. file_exists = api.file_exists
  10022. repo_info = api.repo_info
  10023. list_repo_files = api.list_repo_files
  10024. list_repo_refs = api.list_repo_refs
  10025. list_repo_commits = api.list_repo_commits
  10026. list_repo_tree = api.list_repo_tree
  10027. get_paths_info = api.get_paths_info
  10028. verify_repo_checksums = api.verify_repo_checksums
  10029. get_model_tags = api.get_model_tags
  10030. get_dataset_tags = api.get_dataset_tags
  10031. create_commit = api.create_commit
  10032. create_repo = api.create_repo
  10033. delete_repo = api.delete_repo
  10034. update_repo_settings = api.update_repo_settings
  10035. move_repo = api.move_repo
  10036. upload_file = api.upload_file
  10037. upload_folder = api.upload_folder
  10038. delete_file = api.delete_file
  10039. delete_folder = api.delete_folder
  10040. delete_files = api.delete_files
  10041. upload_large_folder = api.upload_large_folder
  10042. preupload_lfs_files = api.preupload_lfs_files
  10043. create_branch = api.create_branch
  10044. delete_branch = api.delete_branch
  10045. create_tag = api.create_tag
  10046. delete_tag = api.delete_tag
  10047. get_full_repo_name = api.get_full_repo_name
  10048. # Danger-zone API
  10049. super_squash_history = api.super_squash_history
  10050. list_lfs_files = api.list_lfs_files
  10051. permanently_delete_lfs_files = api.permanently_delete_lfs_files
  10052. # Safetensors helpers
  10053. get_safetensors_metadata = api.get_safetensors_metadata
  10054. parse_safetensors_file_metadata = api.parse_safetensors_file_metadata
  10055. # Background jobs
  10056. run_as_future = api.run_as_future
  10057. # Activity API
  10058. list_liked_repos = api.list_liked_repos
  10059. list_repo_likers = api.list_repo_likers
  10060. unlike = api.unlike
  10061. # Community API
  10062. get_discussion_details = api.get_discussion_details
  10063. get_repo_discussions = api.get_repo_discussions
  10064. create_discussion = api.create_discussion
  10065. create_pull_request = api.create_pull_request
  10066. change_discussion_status = api.change_discussion_status
  10067. comment_discussion = api.comment_discussion
  10068. edit_discussion_comment = api.edit_discussion_comment
  10069. rename_discussion = api.rename_discussion
  10070. merge_pull_request = api.merge_pull_request
  10071. # Space API
  10072. add_space_secret = api.add_space_secret
  10073. delete_space_secret = api.delete_space_secret
  10074. get_space_variables = api.get_space_variables
  10075. add_space_variable = api.add_space_variable
  10076. delete_space_variable = api.delete_space_variable
  10077. get_space_runtime = api.get_space_runtime
  10078. request_space_hardware = api.request_space_hardware
  10079. set_space_sleep_time = api.set_space_sleep_time
  10080. pause_space = api.pause_space
  10081. restart_space = api.restart_space
  10082. duplicate_space = api.duplicate_space
  10083. request_space_storage = api.request_space_storage
  10084. delete_space_storage = api.delete_space_storage
  10085. # Inference Endpoint API
  10086. list_inference_endpoints = api.list_inference_endpoints
  10087. create_inference_endpoint = api.create_inference_endpoint
  10088. get_inference_endpoint = api.get_inference_endpoint
  10089. update_inference_endpoint = api.update_inference_endpoint
  10090. delete_inference_endpoint = api.delete_inference_endpoint
  10091. pause_inference_endpoint = api.pause_inference_endpoint
  10092. resume_inference_endpoint = api.resume_inference_endpoint
  10093. scale_to_zero_inference_endpoint = api.scale_to_zero_inference_endpoint
  10094. create_inference_endpoint_from_catalog = api.create_inference_endpoint_from_catalog
  10095. list_inference_catalog = api.list_inference_catalog
  10096. # Collections API
  10097. get_collection = api.get_collection
  10098. list_collections = api.list_collections
  10099. create_collection = api.create_collection
  10100. update_collection_metadata = api.update_collection_metadata
  10101. delete_collection = api.delete_collection
  10102. add_collection_item = api.add_collection_item
  10103. update_collection_item = api.update_collection_item
  10104. delete_collection_item = api.delete_collection_item
  10105. delete_collection_item = api.delete_collection_item
  10106. # Access requests API
  10107. list_pending_access_requests = api.list_pending_access_requests
  10108. list_accepted_access_requests = api.list_accepted_access_requests
  10109. list_rejected_access_requests = api.list_rejected_access_requests
  10110. cancel_access_request = api.cancel_access_request
  10111. accept_access_request = api.accept_access_request
  10112. reject_access_request = api.reject_access_request
  10113. grant_access = api.grant_access
  10114. # Webhooks API
  10115. create_webhook = api.create_webhook
  10116. disable_webhook = api.disable_webhook
  10117. delete_webhook = api.delete_webhook
  10118. enable_webhook = api.enable_webhook
  10119. get_webhook = api.get_webhook
  10120. list_webhooks = api.list_webhooks
  10121. update_webhook = api.update_webhook
  10122. # User API
  10123. get_user_overview = api.get_user_overview
  10124. get_organization_overview = api.get_organization_overview
  10125. list_organization_followers = api.list_organization_followers
  10126. list_organization_members = api.list_organization_members
  10127. list_user_followers = api.list_user_followers
  10128. list_user_following = api.list_user_following
  10129. # Jobs API
  10130. run_job = api.run_job
  10131. fetch_job_logs = api.fetch_job_logs
  10132. fetch_job_metrics = api.fetch_job_metrics
  10133. list_jobs = api.list_jobs
  10134. list_jobs_hardware = api.list_jobs_hardware
  10135. inspect_job = api.inspect_job
  10136. cancel_job = api.cancel_job
  10137. run_uv_job = api.run_uv_job
  10138. create_scheduled_job = api.create_scheduled_job
  10139. list_scheduled_jobs = api.list_scheduled_jobs
  10140. inspect_scheduled_job = api.inspect_scheduled_job
  10141. delete_scheduled_job = api.delete_scheduled_job
  10142. suspend_scheduled_job = api.suspend_scheduled_job
  10143. resume_scheduled_job = api.resume_scheduled_job
  10144. create_scheduled_uv_job = api.create_scheduled_uv_job