hf_api.py 596 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945
  1. # Copyright 2019-present, the HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import annotations
  15. import base64
  16. import inspect
  17. import itertools
  18. import json
  19. import re
  20. import struct
  21. import time
  22. import warnings
  23. from collections import defaultdict
  24. from collections.abc import Callable, Iterable, Iterator
  25. from concurrent.futures import Future, ThreadPoolExecutor
  26. from dataclasses import asdict, dataclass, field
  27. from datetime import datetime
  28. from functools import wraps
  29. from itertools import islice
  30. from pathlib import Path
  31. from typing import TYPE_CHECKING, Any, BinaryIO, Literal, TypeVar, overload
  32. from urllib.parse import quote, unquote
  33. import httpcore
  34. import httpx
  35. from tqdm.auto import tqdm as base_tqdm
  36. from tqdm.contrib.concurrent import thread_map
  37. from huggingface_hub.utils._xet import (
  38. XetTokenType,
  39. fetch_xet_connection_info_from_repo_info,
  40. reset_xet_connection_info_cache_for_repo,
  41. )
  42. from . import constants
  43. from ._buckets import (
  44. BucketFile,
  45. BucketFileMetadata,
  46. BucketFolder,
  47. BucketInfo,
  48. BucketUrl,
  49. SyncPlan,
  50. _BucketAddFile,
  51. _BucketCopyFile,
  52. _BucketDeleteFile,
  53. _split_bucket_id_and_prefix,
  54. sync_bucket_internal,
  55. )
  56. from ._commit_api import (
  57. CommitOperation,
  58. CommitOperationAdd,
  59. CommitOperationCopy,
  60. CommitOperationDelete,
  61. _fetch_files_to_copy,
  62. _fetch_upload_modes,
  63. _prepare_commit_payload,
  64. _upload_files,
  65. _warn_on_overwriting_operations,
  66. )
  67. from ._dataset_viewer import DatasetParquetEntry
  68. from ._eval_results import EvalResultEntry, parse_eval_result_entries
  69. from ._inference_endpoints import InferenceEndpoint, InferenceEndpointScalingMetric, InferenceEndpointType
  70. from ._jobs_api import JobHardware, JobInfo, JobSpec, ScheduledJobInfo, _create_job_spec
  71. from ._space_api import SpaceHardware, SpaceRuntime, SpaceSearchResult, SpaceStorage, SpaceVariable, Volume
  72. from ._upload_large_folder import upload_large_folder_internal
  73. from .community import (
  74. Discussion,
  75. DiscussionComment,
  76. DiscussionStatusChange,
  77. DiscussionTitleChange,
  78. DiscussionWithDetails,
  79. deserialize_event,
  80. )
  81. from .errors import (
  82. BadRequestError,
  83. EntryNotFoundError,
  84. GatedRepoError,
  85. HfHubHTTPError,
  86. LocalTokenNotFoundError,
  87. RemoteEntryNotFoundError,
  88. RepositoryNotFoundError,
  89. RevisionNotFoundError,
  90. XetAuthorizationError,
  91. XetRefreshTokenError,
  92. )
  93. from .file_download import DryRunFileInfo, HfFileMetadata, get_hf_file_metadata, hf_hub_url
  94. from .repocard_data import DatasetCardData, ModelCardData, SpaceCardData
  95. from .utils import (
  96. DEFAULT_IGNORE_PATTERNS,
  97. NotASafetensorsRepoError,
  98. SafetensorsFileMetadata,
  99. SafetensorsParsingError,
  100. SafetensorsRepoMetadata,
  101. TensorInfo,
  102. are_progress_bars_disabled,
  103. build_hf_headers,
  104. chunk_iterable,
  105. experimental,
  106. filter_repo_objects,
  107. fix_hf_endpoint_in_url,
  108. get_session,
  109. get_token,
  110. hf_raise_for_status,
  111. http_backoff,
  112. logging,
  113. paginate,
  114. parse_datetime,
  115. parse_xet_file_data_from_response,
  116. refresh_xet_connection_info,
  117. silent_tqdm,
  118. validate_hf_hub_args,
  119. )
  120. from .utils import tqdm as hf_tqdm
  121. from .utils._auth import _get_token_from_environment, _get_token_from_file, _get_token_from_google_colab
  122. from .utils._deprecation import _deprecate_arguments, _deprecate_method
  123. from .utils._http import _httpx_follow_relative_redirects_with_backoff
  124. from .utils._typing import CallableT
  125. from .utils._verification import collect_local_files, resolve_local_root, verify_maps
  126. from .utils.endpoint_helpers import _is_emission_within_threshold
  127. from .utils.tqdm import _get_progress_bar_context
  128. if TYPE_CHECKING:
  129. from .inference._providers import PROVIDER_T
  130. from .utils._verification import FolderVerification
  131. from .utils._xet_progress_reporting import XetProgressReporter
  132. R = TypeVar("R") # Return type
  133. CollectionItemType_T = Literal["model", "dataset", "space", "paper", "collection", "bucket"]
  134. CollectionSort_T = Literal["lastModified", "trending", "upvotes"]
  135. RepoVisibility_T = Literal["public", "private", "protected"]
  136. ExpandModelProperty_T = Literal[
  137. "author",
  138. "baseModels",
  139. "cardData",
  140. "childrenModelCount",
  141. "config",
  142. "createdAt",
  143. "disabled",
  144. "downloads",
  145. "downloadsAllTime",
  146. "evalResults",
  147. "gated",
  148. "gguf",
  149. "inference",
  150. "inferenceProviderMapping",
  151. "lastModified",
  152. "library_name",
  153. "likes",
  154. "mask_token",
  155. "model-index",
  156. "pipeline_tag",
  157. "private",
  158. "resourceGroup",
  159. "safetensors",
  160. "sha",
  161. "siblings",
  162. "spaces",
  163. "tags",
  164. "transformersInfo",
  165. "trendingScore",
  166. "usedStorage",
  167. "widgetData",
  168. ]
  169. ExpandDatasetProperty_T = Literal[
  170. "author",
  171. "cardData",
  172. "citation",
  173. "createdAt",
  174. "description",
  175. "disabled",
  176. "downloads",
  177. "downloadsAllTime",
  178. "gated",
  179. "lastModified",
  180. "likes",
  181. "paperswithcode_id",
  182. "private",
  183. "resourceGroup",
  184. "sha",
  185. "siblings",
  186. "tags",
  187. "trendingScore",
  188. "usedStorage",
  189. ]
  190. ExpandSpaceProperty_T = Literal[
  191. "author",
  192. "cardData",
  193. "createdAt",
  194. "datasets",
  195. "disabled",
  196. "lastModified",
  197. "likes",
  198. "models",
  199. "private",
  200. "resourceGroup",
  201. "runtime",
  202. "sdk",
  203. "sha",
  204. "siblings",
  205. "subdomain",
  206. "tags",
  207. "trendingScore",
  208. "usedStorage",
  209. ]
  210. ModelSort_T = Literal["created_at", "downloads", "last_modified", "likes", "trending_score"]
  211. DatasetSort_T = Literal["created_at", "downloads", "last_modified", "likes", "trending_score"]
  212. SpaceSort_T = Literal["created_at", "last_modified", "likes", "trending_score"]
  213. DailyPapersSort_T = Literal["publishedAt", "trending"]
  214. USERNAME_PLACEHOLDER = "hf_user"
  215. _REGEX_DISCUSSION_URL = re.compile(r".*/discussions/(\d+)$")
  216. _REGEX_HTTP_PROTOCOL = re.compile(r"https?://")
  217. _CREATE_COMMIT_NO_REPO_ERROR_MESSAGE = (
  218. "\nNote: Creating a commit assumes that the repo already exists on the"
  219. " Huggingface Hub. Please use `create_repo` if it's not the case."
  220. )
  221. _AUTH_CHECK_NO_REPO_ERROR_MESSAGE = (
  222. "\nNote: The repository either does not exist or you do not have access rights."
  223. " Please check the repository ID and your access permissions."
  224. " If this is a private repository, ensure that your token is correct."
  225. )
  226. _BUCKET_PATHS_INFO_BATCH_SIZE = 1000
  227. _BUCKET_BATCH_ADD_CHUNK_SIZE = 1000
  228. _BUCKET_BATCH_DELETE_CHUNK_SIZE = 1000
  229. # Regex used to match special revisions with "/" in them (see #1710)
  230. SPECIAL_REFS_REVISION_REGEX = re.compile(
  231. r"""
  232. (^refs\/convert\/\w+) # `refs/convert/parquet` revisions
  233. |
  234. (^refs\/pr\/\d+) # PR revisions
  235. """,
  236. re.VERBOSE,
  237. )
  238. logger = logging.get_logger(__name__)
  239. def _resolve_repo_visibility(
  240. *,
  241. private: bool | None,
  242. visibility: RepoVisibility_T | None,
  243. repo_type: str | None,
  244. ) -> RepoVisibility_T | None:
  245. if private is not None and visibility is not None:
  246. raise ValueError("Received both `private` and `visibility` arguments. Please provide only one of them.")
  247. if visibility is None:
  248. if private is None:
  249. return None
  250. return "private" if private else "public"
  251. if visibility == "protected" and repo_type != constants.REPO_TYPE_SPACE:
  252. raise ValueError("Only Spaces can be 'protected'. Please set visibility to 'public' or 'private'.")
  253. return visibility
  254. def repo_type_and_id_from_hf_id(hf_id: str, hub_url: str | None = None) -> tuple[str | None, str | None, str]:
  255. """
  256. Returns the repo type and ID from a huggingface.co URL linking to a
  257. repository
  258. Args:
  259. hf_id (`str`):
  260. An URL or ID of a repository on the HF hub. Accepted values are:
  261. - https://huggingface.co/<repo_type>/<namespace>/<repo_id>
  262. - https://huggingface.co/<namespace>/<repo_id>
  263. - hf://<repo_type>/<namespace>/<repo_id>
  264. - hf://<namespace>/<repo_id>
  265. - <repo_type>/<namespace>/<repo_id>
  266. - <namespace>/<repo_id>
  267. - <repo_id>
  268. hub_url (`str`, *optional*):
  269. The URL of the HuggingFace Hub, defaults to https://huggingface.co
  270. Returns:
  271. A tuple with three items: repo_type (`str` or `None`), namespace (`str` or
  272. `None`) and repo_id (`str`).
  273. Raises:
  274. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  275. If URL cannot be parsed.
  276. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  277. If `repo_type` is unknown.
  278. """
  279. input_hf_id = hf_id
  280. # Get the hub_url (with or without protocol)
  281. full_hub_url = hub_url if hub_url is not None else constants.ENDPOINT
  282. hub_url_without_protocol = _REGEX_HTTP_PROTOCOL.sub("", full_hub_url)
  283. # Check if hf_id is a URL containing the hub_url (check both with and without protocol)
  284. hf_id_without_protocol = _REGEX_HTTP_PROTOCOL.sub("", hf_id)
  285. is_hf_url = hub_url_without_protocol in hf_id_without_protocol and "@" not in hf_id
  286. HFFS_PREFIX = "hf://"
  287. if hf_id.startswith(HFFS_PREFIX): # Remove "hf://" prefix if exists
  288. hf_id = hf_id[len(HFFS_PREFIX) :]
  289. # If it's a URL, strip the endpoint prefix to get the path
  290. if is_hf_url:
  291. # Remove protocol if present
  292. hf_id_normalized = _REGEX_HTTP_PROTOCOL.sub("", hf_id)
  293. # Remove the hub_url prefix to get the relative path
  294. if hf_id_normalized.startswith(hub_url_without_protocol):
  295. # Strip the hub URL and any leading slashes
  296. hf_id = hf_id_normalized[len(hub_url_without_protocol) :].lstrip("/")
  297. url_segments = hf_id.split("/")
  298. is_hf_id = len(url_segments) <= 3
  299. namespace: str | None
  300. if is_hf_url:
  301. # For URLs, we need to extract repo_type, namespace, repo_id
  302. # Expected format after stripping endpoint: [repo_type]/namespace/repo_id or namespace/repo_id
  303. if len(url_segments) >= 3:
  304. # Check if first segment is a repo type
  305. if url_segments[0] in constants.REPO_TYPES_MAPPING:
  306. repo_type = constants.REPO_TYPES_MAPPING[url_segments[0]]
  307. namespace = url_segments[1]
  308. repo_id = url_segments[2]
  309. elif url_segments[0] == "buckets":
  310. # Special case for buckets
  311. repo_type = "bucket"
  312. namespace = url_segments[1]
  313. repo_id = url_segments[2]
  314. else:
  315. # First segment is namespace
  316. namespace = url_segments[0]
  317. repo_id = url_segments[1]
  318. repo_type = None
  319. elif len(url_segments) == 2:
  320. namespace = url_segments[0]
  321. repo_id = url_segments[1]
  322. # Check if namespace is actually a repo type mapping
  323. if namespace in constants.REPO_TYPES_MAPPING:
  324. # Mean canonical dataset or model
  325. repo_type = constants.REPO_TYPES_MAPPING[namespace]
  326. namespace = None
  327. elif namespace == "buckets":
  328. # Special case for buckets
  329. repo_type = "bucket"
  330. namespace = None
  331. else:
  332. repo_type = None
  333. else:
  334. # Single segment
  335. repo_id = url_segments[0]
  336. namespace = None
  337. repo_type = None
  338. elif is_hf_id:
  339. if len(url_segments) == 3:
  340. # Passed <repo_type>/<user>/<model_id> or <repo_type>/<org>/<model_id>
  341. repo_type, namespace, repo_id = url_segments[-3:]
  342. elif len(url_segments) == 2:
  343. if url_segments[0] in constants.REPO_TYPES_MAPPING:
  344. # Passed '<model_id>' or 'datasets/<dataset_id>' for a canonical model or dataset
  345. repo_type = constants.REPO_TYPES_MAPPING[url_segments[0]]
  346. namespace = None
  347. repo_id = hf_id.split("/")[-1]
  348. elif url_segments[0] == "buckets":
  349. # Special case for buckets
  350. repo_type = "bucket"
  351. namespace = None
  352. repo_id = hf_id.split("/")[-1]
  353. else:
  354. # Passed <user>/<model_id> or <org>/<model_id>
  355. namespace, repo_id = hf_id.split("/")[-2:]
  356. repo_type = None
  357. else:
  358. # Passed <model_id>
  359. repo_id = url_segments[0]
  360. namespace, repo_type = None, None
  361. else:
  362. raise ValueError(f"Unable to retrieve user and repo ID from the passed HF ID: {hf_id}")
  363. # Check if repo type is known (mapping "spaces" => "space" + empty value => `None`)
  364. if repo_type in constants.REPO_TYPES_MAPPING:
  365. repo_type = constants.REPO_TYPES_MAPPING[repo_type]
  366. if repo_type == "":
  367. repo_type = None
  368. if repo_type not in constants.REPO_TYPES_WITH_KERNEL and repo_type != "bucket":
  369. raise ValueError(f"Unknown `repo_type`: '{repo_type}' ('{input_hf_id}')")
  370. return repo_type, namespace, repo_id
  371. def _parse_hf_copy_handle(hf_handle: str) -> _BucketCopyHandle | _RepoCopyHandle:
  372. # TODO: Harmonize hf:// parsing. See https://github.com/huggingface/huggingface_hub/issues/3971
  373. if not hf_handle.startswith("hf://"):
  374. raise ValueError(f"Invalid HF handle: '{hf_handle}'. Expected a path starting with 'hf://'.")
  375. path = hf_handle.removeprefix("hf://")
  376. if path.startswith("buckets/"):
  377. bucket_id, bucket_path = _split_bucket_id_and_prefix(path.removeprefix("buckets/"))
  378. return _BucketCopyHandle(
  379. bucket_id=bucket_id,
  380. path=bucket_path.strip("/"),
  381. )
  382. path = path.strip("/")
  383. if path == "":
  384. raise ValueError(f"Invalid HF handle: '{hf_handle}'.")
  385. parts = path.split("/")
  386. repo_type: str = constants.REPO_TYPE_MODEL
  387. if parts[0] in constants.REPO_TYPES_MAPPING:
  388. repo_type = constants.REPO_TYPES_MAPPING[parts[0]]
  389. parts = parts[1:]
  390. if len(parts) < 2:
  391. raise ValueError(
  392. f"Invalid repo HF handle: '{hf_handle}'. Expected format 'hf://<namespace>/<repo_id>/path' or with explicit repo type prefix."
  393. )
  394. namespace, repo_name_with_revision = parts[0], parts[1]
  395. remaining_parts = parts[2:]
  396. revision: str | None = None
  397. if "@" in repo_name_with_revision:
  398. repo_name, revision = repo_name_with_revision.split("@", 1)
  399. else:
  400. repo_name = repo_name_with_revision
  401. if revision is None:
  402. revision = constants.DEFAULT_REVISION
  403. else:
  404. revision = unquote(revision)
  405. if remaining_parts:
  406. maybe_special_ref = f"{revision}/{remaining_parts[0]}"
  407. match = SPECIAL_REFS_REVISION_REGEX.match(maybe_special_ref)
  408. if match is not None:
  409. revision = match.group()
  410. suffix = maybe_special_ref.removeprefix(revision).lstrip("/")
  411. remaining_parts = ([suffix] if suffix else []) + remaining_parts[1:]
  412. repo_path = "/".join(remaining_parts).strip("/")
  413. return _RepoCopyHandle(
  414. repo_type=repo_type, # type: ignore
  415. repo_id=f"{namespace}/{repo_name}",
  416. revision=revision,
  417. path=repo_path,
  418. )
  419. @dataclass
  420. class LastCommitInfo(dict):
  421. oid: str
  422. title: str
  423. date: datetime
  424. def __post_init__(self): # hack to make LastCommitInfo backward compatible
  425. self.update(asdict(self))
  426. @dataclass
  427. class BlobLfsInfo(dict):
  428. size: int
  429. sha256: str
  430. pointer_size: int
  431. def __post_init__(self): # hack to make BlobLfsInfo backward compatible
  432. self.update(asdict(self))
  433. @dataclass
  434. class BlobSecurityInfo(dict):
  435. safe: bool # duplicate information with "status" field, keeping it for backward compatibility
  436. status: str
  437. av_scan: dict | None
  438. pickle_import_scan: dict | None
  439. def __post_init__(self): # hack to make BlogSecurityInfo backward compatible
  440. self.update(asdict(self))
  441. @dataclass
  442. class TransformersInfo(dict):
  443. auto_model: str
  444. custom_class: str | None = None
  445. # possible `pipeline_tag` values: https://github.com/huggingface/huggingface.js/blob/3ee32554b8620644a6287e786b2a83bf5caf559c/packages/tasks/src/pipelines.ts#L72
  446. pipeline_tag: str | None = None
  447. processor: str | None = None
  448. def __post_init__(self): # hack to make TransformersInfo backward compatible
  449. self.update(asdict(self))
  450. @dataclass
  451. class SafeTensorsInfo(dict):
  452. parameters: dict[str, int]
  453. total: int
  454. def __post_init__(self): # hack to make SafeTensorsInfo backward compatible
  455. self.update(asdict(self))
  456. @dataclass
  457. class CommitInfo(str):
  458. """Data structure containing information about a newly created commit.
  459. Returned by any method that creates a commit on the Hub: [`create_commit`], [`upload_file`], [`upload_folder`],
  460. [`delete_file`], [`delete_folder`]. It inherits from `str` for backward compatibility but using methods specific
  461. to `str` is deprecated.
  462. Attributes:
  463. commit_url (`str`):
  464. Url where to find the commit.
  465. commit_message (`str`):
  466. The summary (first line) of the commit that has been created.
  467. commit_description (`str`):
  468. Description of the commit that has been created. Can be empty.
  469. oid (`str`):
  470. Commit hash id. Example: `"91c54ad1727ee830252e457677f467be0bfd8a57"`.
  471. pr_url (`str`, *optional*):
  472. Url to the PR that has been created, if any. Populated when `create_pr=True`
  473. is passed.
  474. pr_revision (`str`, *optional*):
  475. Revision of the PR that has been created, if any. Populated when
  476. `create_pr=True` is passed. Example: `"refs/pr/1"`.
  477. pr_num (`int`, *optional*):
  478. Number of the PR discussion that has been created, if any. Populated when
  479. `create_pr=True` is passed. Can be passed as `discussion_num` in
  480. [`get_discussion_details`]. Example: `1`.
  481. repo_url (`RepoUrl`):
  482. Repo URL of the commit containing info like repo_id, repo_type, etc.
  483. """
  484. commit_url: str
  485. commit_message: str
  486. commit_description: str
  487. oid: str
  488. _endpoint: str | None = field(default=None, repr=False)
  489. pr_url: str | None = None
  490. # Computed from `commit_url` in `__post_init__`
  491. repo_url: RepoUrl = field(init=False)
  492. # Computed from `pr_url` in `__post_init__`
  493. pr_revision: str | None = field(init=False)
  494. pr_num: int | None = field(init=False)
  495. def __new__(cls, *args, commit_url: str, **kwargs):
  496. return str.__new__(cls, commit_url)
  497. def __post_init__(self):
  498. """Populate pr-related fields after initialization.
  499. See https://docs.python.org/3.10/library/dataclasses.html#post-init-processing.
  500. """
  501. # Repo info
  502. self.repo_url = RepoUrl(self.commit_url.split("/commit/")[0], endpoint=self._endpoint)
  503. # PR info
  504. if self.pr_url is not None:
  505. self.pr_revision = _parse_revision_from_pr_url(self.pr_url)
  506. self.pr_num = int(self.pr_revision.split("/")[-1])
  507. else:
  508. self.pr_revision = None
  509. self.pr_num = None
  510. @dataclass
  511. class AccessRequest:
  512. """Data structure containing information about a user access request.
  513. Attributes:
  514. username (`str`):
  515. Username of the user who requested access.
  516. fullname (`str`):
  517. Fullname of the user who requested access.
  518. email (`Optional[str]`):
  519. Email of the user who requested access.
  520. Can only be `None` in the /accepted list if the user was granted access manually.
  521. timestamp (`datetime`):
  522. Timestamp of the request.
  523. status (`Literal["pending", "accepted", "rejected"]`):
  524. Status of the request. Can be one of `["pending", "accepted", "rejected"]`.
  525. fields (`dict[str, Any]`, *optional*):
  526. Additional fields filled by the user in the gate form.
  527. """
  528. username: str
  529. fullname: str
  530. email: str | None
  531. timestamp: datetime
  532. status: Literal["pending", "accepted", "rejected"]
  533. # Additional fields filled by the user in the gate form
  534. fields: dict[str, Any] | None = None
  535. @dataclass
  536. class WebhookWatchedItem:
  537. """Data structure containing information about the items watched by a webhook.
  538. Attributes:
  539. type (`Literal["dataset", "model", "org", "space", "user"]`):
  540. Type of the item to be watched. Can be one of `["dataset", "model", "org", "space", "user"]`.
  541. name (`str`):
  542. Name of the item to be watched. Can be the username, organization name, model name, dataset name or space name.
  543. """
  544. type: Literal["dataset", "model", "org", "space", "user"]
  545. name: str
  546. @dataclass
  547. class WebhookInfo:
  548. """Data structure containing information about a webhook.
  549. One of `url` or `job` is specified, but not both.
  550. Attributes:
  551. id (`str`):
  552. ID of the webhook.
  553. url (`str`, *optional*):
  554. URL of the webhook.
  555. job (`JobSpec`, *optional*):
  556. Specifications of the Job to trigger.
  557. watched (`list[WebhookWatchedItem]`):
  558. List of items watched by the webhook, see [`WebhookWatchedItem`].
  559. domains (`list[WEBHOOK_DOMAIN_T]`):
  560. List of domains the webhook is watching. Can be one of `["repo", "discussions"]`.
  561. secret (`str`, *optional*):
  562. Secret of the webhook.
  563. disabled (`bool`):
  564. Whether the webhook is disabled or not.
  565. """
  566. id: str
  567. url: str | None
  568. job: JobSpec | None
  569. watched: list[WebhookWatchedItem]
  570. domains: list[constants.WEBHOOK_DOMAIN_T]
  571. secret: str | None
  572. disabled: bool
  573. class RepoUrl(str):
  574. """Subclass of `str` describing a repo URL on the Hub.
  575. `RepoUrl` is returned by `HfApi.create_repo`. It inherits from `str` for backward
  576. compatibility. At initialization, the URL is parsed to populate properties:
  577. - endpoint (`str`)
  578. - namespace (`Optional[str]`)
  579. - repo_name (`str`)
  580. - repo_id (`str`)
  581. - repo_type (`Literal["model", "dataset", "space"]`)
  582. - url (`str`)
  583. Args:
  584. url (`Any`):
  585. String value of the repo url.
  586. endpoint (`str`, *optional*):
  587. Endpoint of the Hub. Defaults to <https://huggingface.co>.
  588. Example:
  589. ```py
  590. >>> RepoUrl('https://huggingface.co/gpt2')
  591. RepoUrl('https://huggingface.co/gpt2', endpoint='https://huggingface.co', repo_type='model', repo_id='gpt2')
  592. >>> RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co')
  593. 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')
  594. >>> RepoUrl('hf://datasets/my-user/my-dataset')
  595. RepoUrl('hf://datasets/my-user/my-dataset', endpoint='https://huggingface.co', repo_type='dataset', repo_id='user/dataset')
  596. >>> HfApi.create_repo("dummy_model")
  597. RepoUrl('https://huggingface.co/Wauplin/dummy_model', endpoint='https://huggingface.co', repo_type='model', repo_id='Wauplin/dummy_model')
  598. ```
  599. Raises:
  600. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  601. If URL cannot be parsed.
  602. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  603. If `repo_type` is unknown.
  604. """
  605. def __new__(cls, url: Any, endpoint: str | None = None):
  606. url = fix_hf_endpoint_in_url(url, endpoint=endpoint)
  607. return super().__new__(cls, url)
  608. def __init__(self, url: Any, endpoint: str | None = None) -> None:
  609. super().__init__()
  610. # Parse URL
  611. self.endpoint = endpoint or constants.ENDPOINT
  612. repo_type, namespace, repo_name = repo_type_and_id_from_hf_id(self, hub_url=self.endpoint)
  613. # Populate fields
  614. self.namespace = namespace
  615. self.repo_name = repo_name
  616. self.repo_id = repo_name if namespace is None else f"{namespace}/{repo_name}"
  617. self.repo_type = repo_type or constants.REPO_TYPE_MODEL
  618. self.url = str(self) # just in case it's needed
  619. def __repr__(self) -> str:
  620. return f"RepoUrl('{self}', endpoint='{self.endpoint}', repo_type='{self.repo_type}', repo_id='{self.repo_id}')"
  621. @dataclass(frozen=True)
  622. class _BucketCopyHandle:
  623. bucket_id: str
  624. path: str
  625. @dataclass(frozen=True)
  626. class _RepoCopyHandle:
  627. repo_type: Literal["model", "dataset", "space"]
  628. repo_id: str
  629. revision: str
  630. path: str
  631. @dataclass
  632. class RepoSibling:
  633. """
  634. Contains basic information about a repo file inside a repo on the Hub.
  635. > [!TIP]
  636. > All attributes of this class are optional except `rfilename`. This is because only the file names are returned when
  637. > listing repositories on the Hub (with [`list_models`], [`list_datasets`] or [`list_spaces`]). If you need more
  638. > information like file size, blob id or lfs details, you must request them specifically from one repo at a time
  639. > (using [`model_info`], [`dataset_info`] or [`space_info`]) as it adds more constraints on the backend server to
  640. > retrieve these.
  641. Attributes:
  642. rfilename (str):
  643. file name, relative to the repo root.
  644. size (`int`, *optional*):
  645. The file's size, in bytes. This attribute is defined when `files_metadata` argument of [`repo_info`] is set
  646. to `True`. It's `None` otherwise.
  647. blob_id (`str`, *optional*):
  648. The file's git OID. This attribute is defined when `files_metadata` argument of [`repo_info`] is set to
  649. `True`. It's `None` otherwise.
  650. lfs (`BlobLfsInfo`, *optional*):
  651. The file's LFS metadata. This attribute is defined when`files_metadata` argument of [`repo_info`] is set to
  652. `True` and the file is stored with Git LFS. It's `None` otherwise.
  653. """
  654. rfilename: str
  655. size: int | None = None
  656. blob_id: str | None = None
  657. lfs: BlobLfsInfo | None = None
  658. @dataclass
  659. class RepoFile:
  660. """
  661. Contains information about a file on the Hub.
  662. Attributes:
  663. path (str):
  664. file path relative to the repo root.
  665. size (`int`):
  666. The file's size, in bytes.
  667. blob_id (`str`):
  668. The file's git OID.
  669. lfs (`BlobLfsInfo`, *optional*):
  670. The file's LFS metadata.
  671. xet_hash (`str`, *optional*):
  672. The file's Xet hash.
  673. last_commit (`LastCommitInfo`, *optional*):
  674. The file's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
  675. are called with `expand=True`.
  676. security (`BlobSecurityInfo`, *optional*):
  677. The file's security scan metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
  678. are called with `expand=True`.
  679. """
  680. path: str
  681. size: int
  682. blob_id: str
  683. lfs: BlobLfsInfo | None = None
  684. xet_hash: str | None = None
  685. last_commit: LastCommitInfo | None = None
  686. security: BlobSecurityInfo | None = None
  687. def __init__(self, **kwargs):
  688. self.path = kwargs.pop("path")
  689. self.size = kwargs.pop("size")
  690. self.blob_id = kwargs.pop("oid")
  691. lfs = kwargs.pop("lfs", None)
  692. if lfs is not None:
  693. lfs = BlobLfsInfo(size=lfs["size"], sha256=lfs["oid"], pointer_size=lfs["pointerSize"])
  694. self.lfs = lfs
  695. self.xet_hash = kwargs.pop("xetHash", None)
  696. last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None)
  697. if last_commit is not None:
  698. last_commit = LastCommitInfo(
  699. oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"])
  700. )
  701. self.last_commit = last_commit
  702. security = kwargs.pop("securityFileStatus", None)
  703. if security is not None:
  704. safe = security["status"] == "safe"
  705. security = BlobSecurityInfo(
  706. safe=safe,
  707. status=security["status"],
  708. av_scan=security["avScan"],
  709. pickle_import_scan=security["pickleImportScan"],
  710. )
  711. self.security = security
  712. # backwards compatibility
  713. self.rfilename = self.path
  714. self.lastCommit = self.last_commit
  715. @dataclass
  716. class RepoFolder:
  717. """
  718. Contains information about a folder on the Hub.
  719. Attributes:
  720. path (str):
  721. folder path relative to the repo root.
  722. tree_id (`str`):
  723. The folder's git OID.
  724. last_commit (`LastCommitInfo`, *optional*):
  725. The folder's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
  726. are called with `expand=True`.
  727. """
  728. path: str
  729. tree_id: str
  730. last_commit: LastCommitInfo | None = None
  731. def __init__(self, **kwargs):
  732. self.path = kwargs.pop("path")
  733. self.tree_id = kwargs.pop("oid")
  734. last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None)
  735. if last_commit is not None:
  736. last_commit = LastCommitInfo(
  737. oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"])
  738. )
  739. self.last_commit = last_commit
  740. @dataclass
  741. class InferenceProviderMapping:
  742. provider: PROVIDER_T # Provider name
  743. hf_model_id: str # ID of the model on the Hugging Face Hub
  744. provider_id: str # ID of the model on the provider's side
  745. status: Literal["error", "live", "staging"]
  746. task: str
  747. adapter: str | None = None
  748. adapter_weights_path: str | None = None
  749. type: Literal["single-model", "tag-filter"] | None = None
  750. def __init__(self, **kwargs):
  751. self.provider = kwargs.pop("provider")
  752. self.hf_model_id = kwargs.pop("hf_model_id")
  753. self.provider_id = kwargs.pop("providerId")
  754. self.status = kwargs.pop("status")
  755. self.task = kwargs.pop("task")
  756. self.adapter = kwargs.pop("adapter", None)
  757. self.adapter_weights_path = kwargs.pop("adapterWeightsPath", None)
  758. self.type = kwargs.pop("type", None)
  759. self.__dict__.update(**kwargs)
  760. @dataclass
  761. class ModelInfo:
  762. """
  763. Contains information about a model on the Hub. This object is returned by [`model_info`] and [`list_models`].
  764. > [!TIP]
  765. > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
  766. > In general, the more specific the query, the more information is returned. On the contrary, when listing models
  767. > using [`list_models`] only a subset of the attributes are returned.
  768. Attributes:
  769. id (`str`):
  770. ID of model.
  771. author (`str`, *optional*):
  772. Author of the model.
  773. base_models (`list[str]`, *optional*):
  774. List of base models this model is derived from.
  775. card_data (`ModelCardData`, *optional*):
  776. Model Card Metadata as a [`huggingface_hub.repocard_data.ModelCardData`] object.
  777. children_model_count (`int`, *optional*):
  778. Number of children models derived from this model.
  779. config (`dict`, *optional*):
  780. Model configuration.
  781. created_at (`datetime`, *optional*):
  782. Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
  783. corresponding to the date when we began to store creation dates.
  784. disabled (`bool`, *optional*):
  785. Is the repo disabled.
  786. downloads (`int`):
  787. Number of downloads of the model over the last 30 days.
  788. downloads_all_time (`int`):
  789. Cumulated number of downloads of the model since its creation.
  790. eval_results (`list[EvalResultEntry]`, *optional*):
  791. Model's evaluation results.
  792. gated (`Literal["auto", "manual", False]`, *optional*):
  793. Is the repo gated.
  794. If so, whether there is manual or automatic approval.
  795. gguf (`dict`, *optional*):
  796. GGUF information of the model.
  797. inference (`Literal["warm"]`, *optional*):
  798. Status of the model on Inference Providers. Warm if the model is served by at least one provider.
  799. inference_provider_mapping (`list[InferenceProviderMapping]`, *optional*):
  800. A list of [`InferenceProviderMapping`] ordered after the user's provider order.
  801. last_modified (`datetime`, *optional*):
  802. Date of last commit to the repo.
  803. library_name (`str`, *optional*):
  804. Library associated with the model.
  805. likes (`int`):
  806. Number of likes of the model.
  807. mask_token (`str`, *optional*):
  808. Mask token used by the model.
  809. model_index (`dict`, *optional*):
  810. Model index for evaluation.
  811. pipeline_tag (`str`, *optional*):
  812. Pipeline tag associated with the model.
  813. private (`bool`):
  814. Is the repo private.
  815. resource_group (`dict`, *optional*):
  816. Resource group information for the model.
  817. safetensors (`SafeTensorsInfo`, *optional*):
  818. Model's safetensors information.
  819. security_repo_status (`dict`, *optional*):
  820. Model's security scan status.
  821. sha (`str`, *optional*):
  822. Repo SHA at this particular revision.
  823. siblings (`list[RepoSibling]`):
  824. List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the model.
  825. spaces (`list[str]`, *optional*):
  826. List of spaces using the model.
  827. tags (`list[str]`):
  828. List of tags of the model. Compared to `card_data.tags`, contains extra tags computed by the Hub
  829. (e.g. supported libraries, model's arXiv).
  830. transformers_info (`TransformersInfo`, *optional*):
  831. Transformers-specific info (auto class, processor, etc.) associated with the model.
  832. trending_score (`int`, *optional*):
  833. Trending score of the model.
  834. used_storage (`int`, *optional*):
  835. Size in bytes of the model on the Hub.
  836. widget_data (`Any`, *optional*):
  837. Widget data associated with the model.
  838. """
  839. id: str
  840. author: str | None
  841. base_models: list[str] | None
  842. card_data: ModelCardData | None
  843. children_model_count: int | None
  844. config: dict | None
  845. created_at: datetime | None
  846. disabled: bool | None
  847. downloads: int | None
  848. downloads_all_time: int | None
  849. eval_results: list[EvalResultEntry] | None
  850. gated: Literal["auto", "manual", False] | None
  851. gguf: dict | None
  852. inference: Literal["warm"] | None
  853. inference_provider_mapping: list[InferenceProviderMapping] | None
  854. last_modified: datetime | None
  855. library_name: str | None
  856. likes: int | None
  857. mask_token: str | None
  858. model_index: dict | None
  859. pipeline_tag: str | None
  860. private: bool | None
  861. resource_group: dict | None
  862. safetensors: SafeTensorsInfo | None
  863. security_repo_status: dict | None
  864. sha: str | None
  865. siblings: list[RepoSibling] | None
  866. spaces: list[str] | None
  867. tags: list[str] | None
  868. transformers_info: TransformersInfo | None
  869. trending_score: int | None
  870. used_storage: int | None
  871. widget_data: Any | None
  872. def __init__(self, **kwargs):
  873. self.id = kwargs.pop("id")
  874. self.author = kwargs.pop("author", None)
  875. self.sha = kwargs.pop("sha", None)
  876. last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
  877. self.last_modified = parse_datetime(last_modified) if last_modified else None
  878. created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
  879. self.created_at = parse_datetime(created_at) if created_at else None
  880. self.private = kwargs.pop("private", None)
  881. self.gated = kwargs.pop("gated", None)
  882. self.disabled = kwargs.pop("disabled", None)
  883. self.downloads = kwargs.pop("downloads", None)
  884. self.downloads_all_time = kwargs.pop("downloadsAllTime", None)
  885. self.likes = kwargs.pop("likes", None)
  886. self.library_name = kwargs.pop("library_name", None)
  887. self.gguf = kwargs.pop("gguf", None)
  888. self.inference = kwargs.pop("inference", None)
  889. # little hack to simplify Inference Providers logic and make it backward and forward compatible
  890. # right now, API returns a dict on model_info and a list on list_models. Let's harmonize to list.
  891. mapping = kwargs.pop("inferenceProviderMapping", None)
  892. if isinstance(mapping, list):
  893. self.inference_provider_mapping = [
  894. InferenceProviderMapping(**{**value, "hf_model_id": self.id}) for value in mapping
  895. ]
  896. elif isinstance(mapping, dict):
  897. self.inference_provider_mapping = [
  898. InferenceProviderMapping(**{**value, "hf_model_id": self.id, "provider": provider})
  899. for provider, value in mapping.items()
  900. ]
  901. elif mapping is None:
  902. self.inference_provider_mapping = None
  903. else:
  904. raise ValueError(
  905. f"Unexpected type for `inferenceProviderMapping`. Expecting `dict` or `list`. Got {mapping}."
  906. )
  907. self.tags = kwargs.pop("tags", None)
  908. self.pipeline_tag = kwargs.pop("pipeline_tag", None)
  909. self.mask_token = kwargs.pop("mask_token", None)
  910. self.trending_score = kwargs.pop("trendingScore", None)
  911. self.used_storage = kwargs.pop("usedStorage", None)
  912. card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
  913. self.card_data = (
  914. ModelCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
  915. )
  916. self.widget_data = kwargs.pop("widgetData", None)
  917. self.model_index = kwargs.pop("model-index", None) or kwargs.pop("model_index", None)
  918. self.config = kwargs.pop("config", None)
  919. transformers_info = kwargs.pop("transformersInfo", None) or kwargs.pop("transformers_info", None)
  920. self.transformers_info = TransformersInfo(**transformers_info) if transformers_info else None
  921. siblings = kwargs.pop("siblings", None)
  922. self.siblings = (
  923. [
  924. RepoSibling(
  925. rfilename=sibling["rfilename"],
  926. size=sibling.get("size"),
  927. blob_id=sibling.get("blobId"),
  928. lfs=(
  929. BlobLfsInfo(
  930. size=sibling["lfs"]["size"],
  931. sha256=sibling["lfs"]["sha256"],
  932. pointer_size=sibling["lfs"]["pointerSize"],
  933. )
  934. if sibling.get("lfs")
  935. else None
  936. ),
  937. )
  938. for sibling in siblings
  939. ]
  940. if siblings is not None
  941. else None
  942. )
  943. self.spaces = kwargs.pop("spaces", None)
  944. safetensors = kwargs.pop("safetensors", None)
  945. self.safetensors = (
  946. SafeTensorsInfo(
  947. parameters=safetensors["parameters"],
  948. total=safetensors["total"],
  949. )
  950. if safetensors
  951. else None
  952. )
  953. self.security_repo_status = kwargs.pop("securityRepoStatus", None)
  954. eval_results = kwargs.pop("evalResults", None)
  955. self.eval_results = parse_eval_result_entries(eval_results) if eval_results else None
  956. self.base_models = kwargs.pop("baseModels", None)
  957. self.children_model_count = kwargs.pop("childrenModelCount", None)
  958. self.resource_group = kwargs.pop("resourceGroup", None)
  959. # backwards compatibility
  960. self.lastModified = self.last_modified
  961. self.cardData = self.card_data
  962. self.transformersInfo = self.transformers_info
  963. self.__dict__.update(**kwargs)
  964. @dataclass
  965. class DatasetInfo:
  966. """
  967. Contains information about a dataset on the Hub. This object is returned by [`dataset_info`] and [`list_datasets`].
  968. > [!TIP]
  969. > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
  970. > In general, the more specific the query, the more information is returned. On the contrary, when listing datasets
  971. > using [`list_datasets`] only a subset of the attributes are returned.
  972. Attributes:
  973. id (`str`):
  974. ID of dataset.
  975. author (`str`):
  976. Author of the dataset.
  977. card_data (`DatasetCardData`, *optional*):
  978. Dataset Card Metadata as a [`huggingface_hub.repocard_data.DatasetCardData`] object.
  979. citation (`str`, *optional*):
  980. Citation information for the dataset.
  981. created_at (`datetime`, *optional*):
  982. Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
  983. corresponding to the date when we began to store creation dates.
  984. description (`str`, *optional*):
  985. Description of the dataset.
  986. disabled (`bool`, *optional*):
  987. Is the repo disabled.
  988. downloads (`int`):
  989. Number of downloads of the dataset over the last 30 days.
  990. downloads_all_time (`int`):
  991. Cumulated number of downloads of the dataset since its creation.
  992. gated (`Literal["auto", "manual", False]`, *optional*):
  993. Is the repo gated.
  994. If so, whether there is manual or automatic approval.
  995. last_modified (`datetime`, *optional*):
  996. Date of last commit to the repo.
  997. likes (`int`):
  998. Number of likes of the dataset.
  999. paperswithcode_id (`str`, *optional*):
  1000. Papers with code ID of the dataset.
  1001. private (`bool`):
  1002. Is the repo private.
  1003. resource_group (`dict`, *optional*):
  1004. Resource group information for the dataset.
  1005. sha (`str`):
  1006. Repo SHA at this particular revision.
  1007. siblings (`list[RepoSibling]`):
  1008. List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the dataset.
  1009. tags (`list[str]`):
  1010. List of tags of the dataset.
  1011. trending_score (`int`, *optional*):
  1012. Trending score of the dataset.
  1013. used_storage (`int`, *optional*):
  1014. Size in bytes of the dataset on the Hub.
  1015. """
  1016. id: str
  1017. author: str | None
  1018. card_data: DatasetCardData | None
  1019. citation: str | None
  1020. created_at: datetime | None
  1021. description: str | None
  1022. disabled: bool | None
  1023. downloads: int | None
  1024. downloads_all_time: int | None
  1025. gated: Literal["auto", "manual", False] | None
  1026. last_modified: datetime | None
  1027. likes: int | None
  1028. paperswithcode_id: str | None
  1029. private: bool | None
  1030. resource_group: dict | None
  1031. sha: str | None
  1032. siblings: list[RepoSibling] | None
  1033. tags: list[str] | None
  1034. trending_score: int | None
  1035. used_storage: int | None
  1036. def __init__(self, **kwargs):
  1037. self.id = kwargs.pop("id")
  1038. self.author = kwargs.pop("author", None)
  1039. self.sha = kwargs.pop("sha", None)
  1040. created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
  1041. self.created_at = parse_datetime(created_at) if created_at else None
  1042. last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
  1043. self.last_modified = parse_datetime(last_modified) if last_modified else None
  1044. self.private = kwargs.pop("private", None)
  1045. self.gated = kwargs.pop("gated", None)
  1046. self.disabled = kwargs.pop("disabled", None)
  1047. self.downloads = kwargs.pop("downloads", None)
  1048. self.downloads_all_time = kwargs.pop("downloadsAllTime", None)
  1049. self.likes = kwargs.pop("likes", None)
  1050. self.paperswithcode_id = kwargs.pop("paperswithcode_id", None)
  1051. self.tags = kwargs.pop("tags", None)
  1052. self.trending_score = kwargs.pop("trendingScore", None)
  1053. self.used_storage = kwargs.pop("usedStorage", None)
  1054. card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
  1055. self.card_data = (
  1056. DatasetCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
  1057. )
  1058. siblings = kwargs.pop("siblings", None)
  1059. self.siblings = (
  1060. [
  1061. RepoSibling(
  1062. rfilename=sibling["rfilename"],
  1063. size=sibling.get("size"),
  1064. blob_id=sibling.get("blobId"),
  1065. lfs=(
  1066. BlobLfsInfo(
  1067. size=sibling["lfs"]["size"],
  1068. sha256=sibling["lfs"]["sha256"],
  1069. pointer_size=sibling["lfs"]["pointerSize"],
  1070. )
  1071. if sibling.get("lfs")
  1072. else None
  1073. ),
  1074. )
  1075. for sibling in siblings
  1076. ]
  1077. if siblings is not None
  1078. else None
  1079. )
  1080. self.citation = kwargs.pop("citation", None)
  1081. self.description = kwargs.pop("description", None)
  1082. self.resource_group = kwargs.pop("resourceGroup", None)
  1083. # backwards compatibility
  1084. self.lastModified = self.last_modified
  1085. self.cardData = self.card_data
  1086. self.__dict__.update(**kwargs)
  1087. @dataclass
  1088. class SpaceInfo:
  1089. """
  1090. Contains information about a Space on the Hub. This object is returned by [`space_info`] and [`list_spaces`].
  1091. > [!TIP]
  1092. > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
  1093. > In general, the more specific the query, the more information is returned. On the contrary, when listing spaces
  1094. > using [`list_spaces`] only a subset of the attributes are returned.
  1095. Attributes:
  1096. id (`str`):
  1097. ID of the Space.
  1098. author (`str`, *optional*):
  1099. Author of the Space.
  1100. card_data (`SpaceCardData`, *optional*):
  1101. Space Card Metadata as a [`huggingface_hub.repocard_data.SpaceCardData`] object.
  1102. created_at (`datetime`, *optional*):
  1103. Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
  1104. corresponding to the date when we began to store creation dates.
  1105. datasets (`list[str]`, *optional*):
  1106. List of datasets used by the Space.
  1107. disabled (`bool`, *optional*):
  1108. Is the Space disabled.
  1109. gated (`Literal["auto", "manual", False]`, *optional*):
  1110. Is the repo gated.
  1111. If so, whether there is manual or automatic approval.
  1112. host (`str`, *optional*):
  1113. Host URL of the Space.
  1114. last_modified (`datetime`, *optional*):
  1115. Date of last commit to the repo.
  1116. likes (`int`):
  1117. Number of likes of the Space.
  1118. models (`list[str]`, *optional*):
  1119. List of models used by the Space.
  1120. private (`bool`):
  1121. Is the repo private.
  1122. resource_group (`dict`, *optional*):
  1123. Resource group information for the Space.
  1124. runtime (`SpaceRuntime`, *optional*):
  1125. Space runtime information as a [`huggingface_hub.hf_api.SpaceRuntime`] object.
  1126. sdk (`str`, *optional*):
  1127. SDK used by the Space.
  1128. sha (`str`, *optional*):
  1129. Repo SHA at this particular revision.
  1130. siblings (`list[RepoSibling]`):
  1131. List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the Space.
  1132. subdomain (`str`, *optional*):
  1133. Subdomain of the Space.
  1134. tags (`list[str]`):
  1135. List of tags of the Space.
  1136. trending_score (`int`, *optional*):
  1137. Trending score of the Space.
  1138. used_storage (`int`, *optional*):
  1139. Size in bytes of the Space on the Hub.
  1140. """
  1141. id: str
  1142. author: str | None
  1143. card_data: SpaceCardData | None
  1144. created_at: datetime | None
  1145. datasets: list[str] | None
  1146. disabled: bool | None
  1147. gated: Literal["auto", "manual", False] | None
  1148. host: str | None
  1149. last_modified: datetime | None
  1150. likes: int | None
  1151. models: list[str] | None
  1152. private: bool | None
  1153. resource_group: dict | None
  1154. runtime: SpaceRuntime | None
  1155. sdk: str | None
  1156. sha: str | None
  1157. siblings: list[RepoSibling] | None
  1158. subdomain: str | None
  1159. tags: list[str] | None
  1160. trending_score: int | None
  1161. used_storage: int | None
  1162. def __init__(self, **kwargs):
  1163. self.id = kwargs.pop("id")
  1164. self.author = kwargs.pop("author", None)
  1165. self.sha = kwargs.pop("sha", None)
  1166. created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
  1167. self.created_at = parse_datetime(created_at) if created_at else None
  1168. last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
  1169. self.last_modified = parse_datetime(last_modified) if last_modified else None
  1170. self.private = kwargs.pop("private", None)
  1171. self.gated = kwargs.pop("gated", None)
  1172. self.disabled = kwargs.pop("disabled", None)
  1173. self.host = kwargs.pop("host", None)
  1174. self.subdomain = kwargs.pop("subdomain", None)
  1175. self.likes = kwargs.pop("likes", None)
  1176. self.sdk = kwargs.pop("sdk", None)
  1177. self.tags = kwargs.pop("tags", None)
  1178. self.trending_score = kwargs.pop("trendingScore", None)
  1179. self.used_storage = kwargs.pop("usedStorage", None)
  1180. card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
  1181. self.card_data = (
  1182. SpaceCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
  1183. )
  1184. siblings = kwargs.pop("siblings", None)
  1185. self.siblings = (
  1186. [
  1187. RepoSibling(
  1188. rfilename=sibling["rfilename"],
  1189. size=sibling.get("size"),
  1190. blob_id=sibling.get("blobId"),
  1191. lfs=(
  1192. BlobLfsInfo(
  1193. size=sibling["lfs"]["size"],
  1194. sha256=sibling["lfs"]["sha256"],
  1195. pointer_size=sibling["lfs"]["pointerSize"],
  1196. )
  1197. if sibling.get("lfs")
  1198. else None
  1199. ),
  1200. )
  1201. for sibling in siblings
  1202. ]
  1203. if siblings is not None
  1204. else None
  1205. )
  1206. runtime = kwargs.pop("runtime", None)
  1207. self.runtime = SpaceRuntime(runtime) if runtime else None
  1208. self.models = kwargs.pop("models", None)
  1209. self.datasets = kwargs.pop("datasets", None)
  1210. self.resource_group = kwargs.pop("resourceGroup", None)
  1211. # backwards compatibility
  1212. self.lastModified = self.last_modified
  1213. self.cardData = self.card_data
  1214. self.__dict__.update(**kwargs)
  1215. @dataclass
  1216. class KernelInfo:
  1217. """
  1218. Contains information about a kernel repo on the Hub. This object is returned by [`kernel_info`].
  1219. Attributes:
  1220. id (`str`):
  1221. ID of the kernel repo.
  1222. author (`str`, *optional*):
  1223. Author of the kernel repo.
  1224. downloads (`int`, *optional*):
  1225. Number of downloads of the kernel repo over the last 30 days.
  1226. gated (`Literal["auto", "manual", False]`, *optional*):
  1227. Is the repo gated. If so, whether there is manual or automatic approval.
  1228. last_modified (`datetime`, *optional*):
  1229. Date of last commit to the repo.
  1230. likes (`int`, *optional*):
  1231. Number of likes of the kernel repo.
  1232. private (`bool`, *optional*):
  1233. Is the repo private.
  1234. sha (`str`, *optional*):
  1235. Repo SHA at this particular revision.
  1236. """
  1237. id: str
  1238. author: str | None
  1239. downloads: int | None
  1240. gated: Literal["auto", "manual", False] | None
  1241. last_modified: datetime | None
  1242. likes: int | None
  1243. private: bool | None
  1244. sha: str | None
  1245. def __init__(self, **kwargs):
  1246. self.id = kwargs.pop("id")
  1247. self.author = kwargs.pop("author", None)
  1248. self.downloads = kwargs.pop("downloads", None)
  1249. self.gated = kwargs.pop("gated", None)
  1250. last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
  1251. self.last_modified = parse_datetime(last_modified) if last_modified else None
  1252. self.likes = kwargs.pop("likes", None)
  1253. self.private = kwargs.pop("private", None)
  1254. self.sha = kwargs.pop("sha", None)
  1255. # future compatibility
  1256. self.__dict__.update(**kwargs)
  1257. @dataclass
  1258. class CollectionItem:
  1259. """
  1260. Contains information about an item of a Collection (model, dataset, Space, paper, collection or bucket).
  1261. Attributes:
  1262. item_object_id (`str`):
  1263. Unique ID of the item in the collection.
  1264. item_id (`str`):
  1265. ID of the underlying object on the Hub. Can be either a repo_id, a paper id, a collection slug
  1266. or a bucket id.
  1267. e.g. `"jbilcke-hf/ai-comic-factory"`, `"2307.09288"`, `"celinah/cerebras-function-calling-682607169c35fbfa98b30b9a"`.
  1268. item_type (`str`):
  1269. Type of the underlying object. Can be one of `"model"`, `"dataset"`, `"space"`, `"paper"`, `"collection"`
  1270. or `"bucket"`.
  1271. position (`int`):
  1272. Position of the item in the collection.
  1273. note (`str`, *optional*):
  1274. Note associated with the item, as plain text.
  1275. """
  1276. item_object_id: str # id in database
  1277. item_id: str # repo_id or paper id
  1278. item_type: str
  1279. position: int
  1280. note: str | None = None
  1281. def __init__(
  1282. self,
  1283. _id: str,
  1284. id: str,
  1285. type: CollectionItemType_T,
  1286. position: int,
  1287. note: dict | None = None,
  1288. **kwargs,
  1289. ) -> None:
  1290. self.item_object_id: str = _id # id in database
  1291. self.item_id: str = id # repo_id or paper id
  1292. # if the item is a collection, override item_id with the slug
  1293. slug = kwargs.get("slug")
  1294. if slug is not None:
  1295. self.item_id = slug # collection slug
  1296. self.item_type: CollectionItemType_T = type
  1297. self.position: int = position
  1298. note_text = note.get("text") if note is not None else None
  1299. self.note = note_text if isinstance(note_text, str) else None
  1300. @dataclass
  1301. class Collection:
  1302. """
  1303. Contains information about a Collection on the Hub.
  1304. Attributes:
  1305. slug (`str`):
  1306. Slug of the collection. E.g. `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  1307. title (`str`):
  1308. Title of the collection. E.g. `"Recent models"`.
  1309. owner (`str`):
  1310. Owner of the collection. E.g. `"TheBloke"`.
  1311. items (`list[CollectionItem]`):
  1312. List of items in the collection.
  1313. last_updated (`datetime`):
  1314. Date of the last update of the collection.
  1315. position (`int`):
  1316. Position of the collection in the list of collections of the owner.
  1317. private (`bool`):
  1318. Whether the collection is private or not.
  1319. theme (`str`):
  1320. Theme of the collection. E.g. `"green"`.
  1321. upvotes (`int`):
  1322. Number of upvotes of the collection.
  1323. description (`str`, *optional*):
  1324. Description of the collection, as plain text.
  1325. url (`str`):
  1326. (property) URL of the collection on the Hub.
  1327. """
  1328. slug: str
  1329. title: str
  1330. owner: str
  1331. items: list[CollectionItem]
  1332. last_updated: datetime
  1333. position: int
  1334. private: bool
  1335. theme: str
  1336. upvotes: int
  1337. description: str | None = None
  1338. def __init__(self, **kwargs) -> None:
  1339. self.slug = kwargs.pop("slug")
  1340. self.title = kwargs.pop("title")
  1341. self.owner = kwargs.pop("owner")
  1342. self.items = [CollectionItem(**item) for item in kwargs.pop("items")]
  1343. self.last_updated = parse_datetime(kwargs.pop("lastUpdated"))
  1344. self.position = kwargs.pop("position")
  1345. self.private = kwargs.pop("private")
  1346. self.theme = kwargs.pop("theme")
  1347. self.upvotes = kwargs.pop("upvotes")
  1348. self.description = kwargs.pop("description", None)
  1349. endpoint = kwargs.pop("endpoint", None)
  1350. if endpoint is None:
  1351. endpoint = constants.ENDPOINT
  1352. self._url = f"{endpoint}/collections/{self.slug}"
  1353. @property
  1354. def url(self) -> str:
  1355. """Returns the URL of the collection on the Hub."""
  1356. return self._url
  1357. @dataclass
  1358. class GitRefInfo:
  1359. """
  1360. Contains information about a git reference for a repo on the Hub.
  1361. Attributes:
  1362. name (`str`):
  1363. Name of the reference (e.g. tag name or branch name).
  1364. ref (`str`):
  1365. Full git ref on the Hub (e.g. `"refs/heads/main"` or `"refs/tags/v1.0"`).
  1366. target_commit (`str`):
  1367. OID of the target commit for the ref (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`)
  1368. """
  1369. name: str
  1370. ref: str
  1371. target_commit: str
  1372. @dataclass
  1373. class GitRefs:
  1374. """
  1375. Contains information about all git references for a repo on the Hub.
  1376. Object is returned by [`list_repo_refs`].
  1377. Attributes:
  1378. branches (`list[GitRefInfo]`):
  1379. A list of [`GitRefInfo`] containing information about branches on the repo.
  1380. converts (`list[GitRefInfo]`):
  1381. A list of [`GitRefInfo`] containing information about "convert" refs on the repo.
  1382. Converts are refs used (internally) to push preprocessed data in Dataset repos.
  1383. tags (`list[GitRefInfo]`):
  1384. A list of [`GitRefInfo`] containing information about tags on the repo.
  1385. pull_requests (`list[GitRefInfo]`, *optional*):
  1386. A list of [`GitRefInfo`] containing information about pull requests on the repo.
  1387. Only returned if `include_prs=True` is set.
  1388. """
  1389. branches: list[GitRefInfo]
  1390. converts: list[GitRefInfo]
  1391. tags: list[GitRefInfo]
  1392. pull_requests: list[GitRefInfo] | None = None
  1393. @dataclass
  1394. class GitCommitInfo:
  1395. """
  1396. Contains information about a git commit for a repo on the Hub. Check out [`list_repo_commits`] for more details.
  1397. Attributes:
  1398. commit_id (`str`):
  1399. OID of the commit (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`)
  1400. authors (`list[str]`):
  1401. List of authors of the commit.
  1402. created_at (`datetime`):
  1403. Datetime when the commit was created.
  1404. title (`str`):
  1405. Title of the commit. This is a free-text value entered by the authors.
  1406. message (`str`):
  1407. Description of the commit. This is a free-text value entered by the authors.
  1408. formatted_title (`str`):
  1409. Title of the commit formatted as HTML. Only returned if `formatted=True` is set.
  1410. formatted_message (`str`):
  1411. Description of the commit formatted as HTML. Only returned if `formatted=True` is set.
  1412. """
  1413. commit_id: str
  1414. authors: list[str]
  1415. created_at: datetime
  1416. title: str
  1417. message: str
  1418. formatted_title: str | None
  1419. formatted_message: str | None
  1420. @dataclass
  1421. class UserLikes:
  1422. """
  1423. Contains information about a user likes on the Hub.
  1424. Attributes:
  1425. user (`str`):
  1426. Name of the user for which we fetched the likes.
  1427. total (`int`):
  1428. Total number of likes.
  1429. datasets (`list[str]`):
  1430. List of datasets liked by the user (as repo_ids).
  1431. kernels (`list[str]`):
  1432. List of kernels liked by the user (as repo_ids).
  1433. models (`list[str]`):
  1434. List of models liked by the user (as repo_ids).
  1435. spaces (`list[str]`):
  1436. List of spaces liked by the user (as repo_ids).
  1437. """
  1438. # Metadata
  1439. user: str
  1440. total: int
  1441. # User likes
  1442. datasets: list[str]
  1443. kernels: list[str]
  1444. models: list[str]
  1445. spaces: list[str]
  1446. @dataclass
  1447. class Organization:
  1448. """
  1449. Contains information about an organization on the Hub.
  1450. Attributes:
  1451. avatar_url (`str`):
  1452. URL of the organization's avatar.
  1453. name (`str`):
  1454. Name of the organization on the Hub (unique).
  1455. fullname (`str`):
  1456. Organization's full name.
  1457. details (`str`, *optional*):
  1458. Organization's description.
  1459. is_verified (`bool`, *optional*):
  1460. Whether the organization is verified.
  1461. is_following (`bool`, *optional*):
  1462. Whether the authenticated user follows this organization.
  1463. num_users (`int`, *optional*):
  1464. Number of members in the organization.
  1465. num_models (`int`, *optional*):
  1466. Number of models owned by the organization.
  1467. num_spaces (`int`, *optional*):
  1468. Number of Spaces owned by the organization.
  1469. num_datasets (`int`, *optional*):
  1470. Number of datasets owned by the organization.
  1471. num_followers (`int`, *optional*):
  1472. Number of followers of the organization.
  1473. num_papers (`int`, *optional*):
  1474. Number of papers authored by the organization.
  1475. plan (`str`, *optional*):
  1476. The organization's plan (e.g., "enterprise", "team").
  1477. """
  1478. avatar_url: str
  1479. name: str
  1480. fullname: str
  1481. details: str | None = None
  1482. is_verified: bool | None = None
  1483. is_following: bool | None = None
  1484. num_users: int | None = None
  1485. num_models: int | None = None
  1486. num_spaces: int | None = None
  1487. num_datasets: int | None = None
  1488. num_followers: int | None = None
  1489. num_papers: int | None = None
  1490. plan: str | None = None
  1491. def __init__(self, **kwargs) -> None:
  1492. self.avatar_url = kwargs.pop("avatarUrl", "")
  1493. self.name = kwargs.pop("name", "")
  1494. self.fullname = kwargs.pop("fullname", "")
  1495. self.details = kwargs.pop("details", None)
  1496. self.is_verified = kwargs.pop("isVerified", None)
  1497. self.is_following = kwargs.pop("isFollowing", None)
  1498. self.num_users = kwargs.pop("numUsers", None)
  1499. self.num_models = kwargs.pop("numModels", None)
  1500. self.num_spaces = kwargs.pop("numSpaces", None)
  1501. self.num_datasets = kwargs.pop("numDatasets", None)
  1502. self.num_followers = kwargs.pop("numFollowers", None)
  1503. self.num_papers = kwargs.pop("numPapers", None)
  1504. self.plan = kwargs.pop("plan", None)
  1505. # forward compatibility
  1506. self.__dict__.update(**kwargs)
  1507. @dataclass
  1508. class User:
  1509. """
  1510. Contains information about a user on the Hub.
  1511. Attributes:
  1512. username (`str`):
  1513. Name of the user on the Hub (unique).
  1514. fullname (`str`):
  1515. User's full name.
  1516. avatar_url (`str`):
  1517. URL of the user's avatar.
  1518. details (`str`, *optional*):
  1519. User's details.
  1520. is_following (`bool`, *optional*):
  1521. Whether the authenticated user is following this user.
  1522. is_pro (`bool`, *optional*):
  1523. Whether the user is a pro user.
  1524. num_models (`int`, *optional*):
  1525. Number of models created by the user.
  1526. num_datasets (`int`, *optional*):
  1527. Number of datasets created by the user.
  1528. num_spaces (`int`, *optional*):
  1529. Number of spaces created by the user.
  1530. num_discussions (`int`, *optional*):
  1531. Number of discussions initiated by the user.
  1532. num_papers (`int`, *optional*):
  1533. Number of papers authored by the user.
  1534. num_upvotes (`int`, *optional*):
  1535. Number of upvotes received by the user.
  1536. num_likes (`int`, *optional*):
  1537. Number of likes given by the user.
  1538. num_following (`int`, *optional*):
  1539. Number of users this user is following.
  1540. num_followers (`int`, *optional*):
  1541. Number of users following this user.
  1542. orgs (list of [`Organization`]):
  1543. List of organizations the user is part of.
  1544. """
  1545. # Metadata
  1546. username: str
  1547. fullname: str
  1548. avatar_url: str
  1549. details: str | None = None
  1550. is_following: bool | None = None
  1551. is_pro: bool | None = None
  1552. num_models: int | None = None
  1553. num_datasets: int | None = None
  1554. num_spaces: int | None = None
  1555. num_discussions: int | None = None
  1556. num_papers: int | None = None
  1557. num_upvotes: int | None = None
  1558. num_likes: int | None = None
  1559. num_following: int | None = None
  1560. num_followers: int | None = None
  1561. orgs: list[Organization] = field(default_factory=list)
  1562. def __init__(self, **kwargs) -> None:
  1563. self.username = kwargs.pop("user", "")
  1564. self.fullname = kwargs.pop("fullname", "")
  1565. self.avatar_url = kwargs.pop("avatarUrl", "")
  1566. self.is_following = kwargs.pop("isFollowing", None)
  1567. self.is_pro = kwargs.pop("isPro", None)
  1568. self.details = kwargs.pop("details", None)
  1569. self.num_models = kwargs.pop("numModels", None)
  1570. self.num_datasets = kwargs.pop("numDatasets", None)
  1571. self.num_spaces = kwargs.pop("numSpaces", None)
  1572. self.num_discussions = kwargs.pop("numDiscussions", None)
  1573. self.num_papers = kwargs.pop("numPapers", None)
  1574. self.num_upvotes = kwargs.pop("numUpvotes", None)
  1575. self.num_likes = kwargs.pop("numLikes", None)
  1576. self.num_following = kwargs.pop("numFollowing", None)
  1577. self.num_followers = kwargs.pop("numFollowers", None)
  1578. self.user_type = kwargs.pop("type", None)
  1579. self.orgs = [Organization(**org) for org in kwargs.pop("orgs", [])]
  1580. # forward compatibility
  1581. self.__dict__.update(**kwargs)
  1582. @dataclass
  1583. class PaperAuthor:
  1584. """
  1585. Contains information about a paper author on the Hub.
  1586. Attributes:
  1587. name (`str`):
  1588. Name of the author.
  1589. user (`User`, *optional*):
  1590. Information about the author as a [`User`] object.
  1591. status (`str`, *optional*):
  1592. Status of the author on the Hub.
  1593. status_last_changed_at (`datetime`, *optional*):
  1594. Date when the status of the author changed.
  1595. hidden (`bool`, *optional*):
  1596. Whether the author is hidden on the Hub.
  1597. """
  1598. name: str
  1599. user: User | None
  1600. status: str | None
  1601. status_last_changed_at: datetime | None
  1602. hidden: bool | None
  1603. def __init__(self, **kwargs) -> None:
  1604. self.name = kwargs.pop("name", "")
  1605. user = kwargs.pop("user", None)
  1606. self.user = User(**user) if user else None
  1607. self.status = kwargs.pop("status", None)
  1608. status_last_changed_at = kwargs.pop("statusLastChangedAt", None)
  1609. self.status_last_changed_at = parse_datetime(status_last_changed_at) if status_last_changed_at else None
  1610. self.hidden = kwargs.pop("hidden", None)
  1611. self.__dict__.update(**kwargs)
  1612. @dataclass
  1613. class PaperInfo:
  1614. """
  1615. Contains information about a paper on the Hub.
  1616. Attributes:
  1617. id (`str`):
  1618. arXiv paper ID.
  1619. authors (`list[PaperAuthor]`, *optional*):
  1620. Authors of the paper.
  1621. published_at (`datetime`, *optional*):
  1622. Date paper published.
  1623. title (`str`, *optional*):
  1624. Title of the paper.
  1625. summary (`str`, *optional*):
  1626. Summary of the paper.
  1627. upvotes (`int`, *optional*):
  1628. Number of upvotes for the paper on the Hub.
  1629. discussion_id (`str`, *optional*):
  1630. Discussion ID for the paper on the Hub.
  1631. source (`str`, *optional*):
  1632. Source of the paper.
  1633. comments (`int`, *optional*):
  1634. Number of comments for the paper on the Hub.
  1635. submitted_at (`datetime`, *optional*):
  1636. Date paper appeared in daily papers on the Hub.
  1637. submitted_by (`User`, *optional*):
  1638. Information about who submitted the daily paper.
  1639. ai_summary (`str`, *optional*):
  1640. AI summary of the paper.
  1641. ai_keywords (`list[str]`, *optional*):
  1642. AI keywords of the paper.
  1643. organization (`Organization`, *optional*):
  1644. Information about the organization associated with the paper.
  1645. project_page (`str`, *optional*):
  1646. URL of the project page for the paper.
  1647. github_repo (`str`, *optional*):
  1648. URL of the GitHub repository for the paper.
  1649. github_stars (`int`, *optional*):
  1650. Number of stars of the GitHub repository for the paper.
  1651. """
  1652. id: str
  1653. authors: list[PaperAuthor] | None
  1654. published_at: datetime | None
  1655. title: str | None
  1656. summary: str | None
  1657. upvotes: int | None
  1658. discussion_id: str | None
  1659. source: str | None
  1660. comments: int | None
  1661. submitted_at: datetime | None
  1662. submitted_by: User | None
  1663. ai_summary: str | None
  1664. ai_keywords: list[str] | None
  1665. organization: Organization | None
  1666. project_page: str | None
  1667. github_repo: str | None
  1668. github_stars: int | None
  1669. def __init__(self, **kwargs) -> None:
  1670. paper = kwargs.pop("paper", {})
  1671. self.id = kwargs.pop("id", None) or paper.pop("id", None)
  1672. authors = paper.pop("authors", None) or kwargs.pop("authors", None)
  1673. self.authors = [PaperAuthor(**author) for author in authors] if authors else None
  1674. published_at = paper.pop("publishedAt", None) or kwargs.pop("publishedAt", None)
  1675. self.published_at = parse_datetime(published_at) if published_at else None
  1676. self.title = kwargs.pop("title", None)
  1677. self.source = kwargs.pop("source", None)
  1678. self.summary = paper.pop("summary", None) or kwargs.pop("summary", None)
  1679. self.upvotes = paper.pop("upvotes", None) or kwargs.pop("upvotes", None)
  1680. self.discussion_id = paper.pop("discussionId", None) or kwargs.pop("discussionId", None)
  1681. self.comments = kwargs.pop("numComments", 0)
  1682. submitted_at = kwargs.pop("publishedAt", None) or kwargs.pop("submittedOnDailyAt", None)
  1683. self.submitted_at = parse_datetime(submitted_at) if submitted_at else None
  1684. submitted_by = kwargs.pop("submittedBy", None) or kwargs.pop("submittedOnDailyBy", None)
  1685. self.submitted_by = User(**submitted_by) if submitted_by else None
  1686. self.ai_summary = kwargs.pop("ai_summary", None)
  1687. self.ai_keywords = kwargs.pop("ai_keywords", None)
  1688. organization = kwargs.pop("organization", None)
  1689. self.organization = Organization(**organization) if organization else None
  1690. self.project_page = kwargs.pop("projectPage", None)
  1691. self.github_repo = kwargs.pop("githubRepo", None)
  1692. self.github_stars = kwargs.pop("githubStars", None)
  1693. # forward compatibility
  1694. self.__dict__.update(**kwargs)
  1695. @dataclass
  1696. class LFSFileInfo:
  1697. """
  1698. Contains information about a file stored as LFS on a repo on the Hub.
  1699. Used in the context of listing and permanently deleting LFS files from a repo to free-up space.
  1700. See [`list_lfs_files`] and [`permanently_delete_lfs_files`] for more details.
  1701. Git LFS files are tracked using SHA-256 object IDs, rather than file paths, to optimize performance
  1702. This approach is necessary because a single object can be referenced by multiple paths across different commits,
  1703. 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)
  1704. to learn how to know which filename(s) is(are) associated with each SHA.
  1705. Attributes:
  1706. file_oid (`str`):
  1707. SHA-256 object ID of the file. This is the identifier to pass when permanently deleting the file.
  1708. filename (`str`):
  1709. Possible filename for the LFS object. See the note above for more information.
  1710. oid (`str`):
  1711. OID of the LFS object.
  1712. pushed_at (`datetime`):
  1713. Date the LFS object was pushed to the repo.
  1714. ref (`str`, *optional*):
  1715. Ref where the LFS object has been pushed (if any).
  1716. size (`int`):
  1717. Size of the LFS object.
  1718. Example:
  1719. ```py
  1720. >>> from huggingface_hub import HfApi
  1721. >>> api = HfApi()
  1722. >>> lfs_files = api.list_lfs_files("username/my-cool-repo")
  1723. # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
  1724. # e.g. select only LFS files in the "checkpoints" folder
  1725. >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
  1726. # Permanently delete LFS files
  1727. >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
  1728. ```
  1729. """
  1730. file_oid: str
  1731. filename: str
  1732. oid: str
  1733. pushed_at: datetime
  1734. ref: str | None
  1735. size: int
  1736. def __init__(self, **kwargs) -> None:
  1737. self.file_oid = kwargs.pop("fileOid")
  1738. self.filename = kwargs.pop("filename")
  1739. self.oid = kwargs.pop("oid")
  1740. self.pushed_at = parse_datetime(kwargs.pop("pushedAt"))
  1741. self.ref = kwargs.pop("ref", None)
  1742. self.size = kwargs.pop("size")
  1743. # forward compatibility
  1744. self.__dict__.update(**kwargs)
  1745. @dataclass
  1746. class DatasetLeaderboardEntry:
  1747. """Contains information about a single entry in a dataset leaderboard on the Hub.
  1748. A leaderboard ranks models based on their evaluation scores on a given benchmark dataset.
  1749. This object is returned by [`get_dataset_leaderboard`]. To get evaluation results for a
  1750. specific model across benchmarks, see [`ModelInfo.eval_results`] (via [`model_info`] with
  1751. `expand=["evalResults"]`) and [`EvalResultEntry`].
  1752. Attributes:
  1753. rank (`int`):
  1754. Rank of the model on the leaderboard (1-indexed).
  1755. model_id (`str`):
  1756. ID of the model (e.g. `"meta-llama/Llama-3-8b"`).
  1757. value (`float`):
  1758. Evaluation score value.
  1759. filename (`str`):
  1760. Name of the result file containing the evaluation data.
  1761. verified (`bool`):
  1762. Whether the result has been verified.
  1763. source (`dict[str, Any]`):
  1764. Information about the source of the evaluation result. Contains keys like
  1765. `"url"`, `"name"`, and `"isExternal"`.
  1766. author (`User` or `Organization`):
  1767. The model author, parsed based on the `"type"` field in the API response.
  1768. pull_request (`int`, *optional*):
  1769. Pull request number associated with the leaderboard entry, if any.
  1770. notes (`str`, *optional*):
  1771. Notes associated with the leaderboard entry, if any.
  1772. """
  1773. rank: int
  1774. model_id: str
  1775. value: float
  1776. filename: str
  1777. verified: bool
  1778. source: dict[str, Any]
  1779. author: User | Organization
  1780. pull_request: int | None = None
  1781. notes: str | None = None
  1782. def __init__(self, **kwargs) -> None:
  1783. self.rank = kwargs.pop("rank")
  1784. self.model_id = kwargs.pop("modelId")
  1785. self.value = kwargs.pop("value")
  1786. self.filename = kwargs.pop("filename")
  1787. self.verified = kwargs.pop("verified")
  1788. self.source = kwargs.pop("source")
  1789. author_data = dict(kwargs.pop("author"))
  1790. author_type = author_data.get("type")
  1791. if author_type == "org":
  1792. self.author = Organization(**author_data)
  1793. else:
  1794. author_data["user"] = author_data.pop("name", "")
  1795. self.author = User(**author_data)
  1796. self.pull_request = kwargs.pop("pullRequest", None)
  1797. self.notes = kwargs.pop("notes", None)
  1798. # forward compatibility
  1799. self.__dict__.update(**kwargs)
  1800. def future_compatible(fn: CallableT) -> CallableT:
  1801. """Wrap a method of `HfApi` to handle `run_as_future=True`.
  1802. A method flagged as "future_compatible" will be called in a thread if `run_as_future=True` and return a
  1803. `concurrent.futures.Future` instance. Otherwise, it will be called normally and return the result.
  1804. """
  1805. sig = inspect.signature(fn)
  1806. args_params = list(sig.parameters)[1:] # remove "self" from list
  1807. @wraps(fn)
  1808. def _inner(self, *args, **kwargs):
  1809. # Get `run_as_future` value if provided (default to False)
  1810. if "run_as_future" in kwargs:
  1811. run_as_future = kwargs["run_as_future"]
  1812. kwargs["run_as_future"] = False # avoid recursion error
  1813. else:
  1814. run_as_future = False
  1815. for param, value in zip(args_params, args):
  1816. if param == "run_as_future":
  1817. run_as_future = value
  1818. break
  1819. # Call the function in a thread if `run_as_future=True`
  1820. if run_as_future:
  1821. return self.run_as_future(fn, self, *args, **kwargs)
  1822. # Otherwise, call the function normally
  1823. return fn(self, *args, **kwargs)
  1824. _inner.is_future_compatible = True # type: ignore
  1825. return _inner # type: ignore
  1826. def _get_safetensors_metadata_size(size_bytes: bytes, filename: str, context_msg: str) -> int:
  1827. """
  1828. Parse and validate safetensors metadata size from the first 8 bytes.
  1829. This is a shared helper function used by both remote and local safetensors parsing.
  1830. Args:
  1831. size_bytes: First 8 bytes of the safetensors file.
  1832. filename: Filename for error messages.
  1833. context_msg: Additional context for error messages.
  1834. Returns:
  1835. The metadata size as an integer.
  1836. Raises:
  1837. SafetensorsParsingError: If size_bytes is too short or metadata size exceeds limit.
  1838. """
  1839. if len(size_bytes) < 8:
  1840. raise SafetensorsParsingError(
  1841. f"Failed to parse safetensors header for '{filename}' ({context_msg}): file is too small to be a valid "
  1842. "safetensors file."
  1843. )
  1844. metadata_size = struct.unpack("<Q", size_bytes[:8])[0]
  1845. if metadata_size > constants.SAFETENSORS_MAX_HEADER_LENGTH:
  1846. raise SafetensorsParsingError(
  1847. f"Failed to parse safetensors header for '{filename}' ({context_msg}): safetensors header is too big. "
  1848. f"Maximum supported size is {constants.SAFETENSORS_MAX_HEADER_LENGTH} bytes (got {metadata_size})."
  1849. )
  1850. return metadata_size
  1851. def _parse_safetensors_header(metadata_as_bytes: bytes, filename: str, context_msg: str) -> SafetensorsFileMetadata:
  1852. """
  1853. Parse safetensors metadata from raw header bytes.
  1854. This is a shared helper function used by both remote and local safetensors parsing.
  1855. Args:
  1856. metadata_as_bytes: Raw bytes of the JSON metadata header (without the 8-byte size prefix).
  1857. filename: Filename for error messages.
  1858. context_msg: Additional context for error messages (e.g., repo info or local path).
  1859. Returns:
  1860. SafetensorsFileMetadata object.
  1861. Raises:
  1862. SafetensorsParsingError: If the header cannot be parsed.
  1863. """
  1864. # Parse json header
  1865. try:
  1866. metadata_as_dict = json.loads(metadata_as_bytes.decode(errors="ignore"))
  1867. except json.JSONDecodeError as e:
  1868. raise SafetensorsParsingError(
  1869. f"Failed to parse safetensors header for '{filename}' ({context_msg}): header is not json-encoded string. "
  1870. "Please make sure this is a correctly formatted safetensors file."
  1871. ) from e
  1872. try:
  1873. return SafetensorsFileMetadata(
  1874. metadata=metadata_as_dict.get("__metadata__", {}),
  1875. tensors={
  1876. key: TensorInfo(
  1877. dtype=tensor["dtype"],
  1878. shape=tensor["shape"],
  1879. data_offsets=tuple(tensor["data_offsets"]), # type: ignore
  1880. )
  1881. for key, tensor in metadata_as_dict.items()
  1882. if key != "__metadata__"
  1883. },
  1884. )
  1885. except (KeyError, IndexError) as e:
  1886. raise SafetensorsParsingError(
  1887. f"Failed to parse safetensors header for '{filename}' ({context_msg}): header format not recognized. "
  1888. "Please make sure this is a correctly formatted safetensors file."
  1889. ) from e
  1890. class HfApi:
  1891. """
  1892. Client to interact with the Hugging Face Hub via HTTP.
  1893. The client is initialized with some high-level settings used in all requests
  1894. made to the Hub (HF endpoint, authentication, user agents...). Using the `HfApi`
  1895. client is preferred but not mandatory as all of its public methods are exposed
  1896. directly at the root of `huggingface_hub`.
  1897. Args:
  1898. endpoint (`str`, *optional*):
  1899. Endpoint of the Hub. Defaults to <https://huggingface.co>.
  1900. token (`bool` or `str`, *optional*):
  1901. A valid user access token (string). Defaults to the locally saved
  1902. token, which is the recommended method for authentication (see
  1903. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  1904. To disable authentication, pass `False`.
  1905. library_name (`str`, *optional*):
  1906. The name of the library that is making the HTTP request. Will be added to
  1907. the user-agent header. Example: `"transformers"`.
  1908. library_version (`str`, *optional*):
  1909. The version of the library that is making the HTTP request. Will be added
  1910. to the user-agent header. Example: `"4.24.0"`.
  1911. user_agent (`str`, `dict`, *optional*):
  1912. The user agent info in the form of a dictionary or a single string. It will
  1913. be completed with information about the installed packages.
  1914. headers (`dict`, *optional*):
  1915. Additional headers to be sent with each request. Example: `{"X-My-Header": "value"}`.
  1916. Headers passed here are taking precedence over the default headers.
  1917. """
  1918. def __init__(
  1919. self,
  1920. endpoint: str | None = None,
  1921. token: str | bool | None = None,
  1922. library_name: str | None = None,
  1923. library_version: str | None = None,
  1924. user_agent: dict | str | None = None,
  1925. headers: dict[str, str] | None = None,
  1926. ) -> None:
  1927. self.endpoint = endpoint if endpoint is not None else constants.ENDPOINT
  1928. self.token = token
  1929. self.library_name = library_name
  1930. self.library_version = library_version
  1931. self.user_agent = user_agent
  1932. self.headers = headers
  1933. self._thread_pool: ThreadPoolExecutor | None = None
  1934. # /whoami-v2 is the only endpoint for which we may want to cache results
  1935. self._whoami_cache: dict[str, dict] = {}
  1936. def run_as_future(self, fn: Callable[..., R], *args, **kwargs) -> Future[R]:
  1937. """
  1938. Run a method in the background and return a Future instance.
  1939. The main goal is to run methods without blocking the main thread (e.g. to push data during a training).
  1940. Background jobs are queued to preserve order but are not ran in parallel. If you need to speed-up your scripts
  1941. 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).
  1942. Note: Most-used methods like [`upload_file`], [`upload_folder`] and [`create_commit`] have a `run_as_future: bool`
  1943. argument to directly call them in the background. This is equivalent to calling `api.run_as_future(...)` on them
  1944. but less verbose.
  1945. Args:
  1946. fn (`Callable`):
  1947. The method to run in the background.
  1948. *args, **kwargs:
  1949. Arguments with which the method will be called.
  1950. Return:
  1951. `Future`: a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) instance to
  1952. get the result of the task.
  1953. Example:
  1954. ```py
  1955. >>> from huggingface_hub import HfApi
  1956. >>> api = HfApi()
  1957. >>> future = api.run_as_future(api.whoami) # instant
  1958. >>> future.done()
  1959. False
  1960. >>> future.result() # wait until complete and return result
  1961. (...)
  1962. >>> future.done()
  1963. True
  1964. ```
  1965. """
  1966. if self._thread_pool is None:
  1967. self._thread_pool = ThreadPoolExecutor(max_workers=1)
  1968. self._thread_pool
  1969. return self._thread_pool.submit(fn, *args, **kwargs)
  1970. @validate_hf_hub_args
  1971. def whoami(self, token: bool | str | None = None, *, cache: bool = False) -> dict:
  1972. """
  1973. Call HF API to know "whoami".
  1974. 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
  1975. `whoami` multiple times as this endpoint is heavily rate-limited for security reasons.
  1976. Args:
  1977. token (`bool` or `str`, *optional*):
  1978. A valid user access token (string). Defaults to the locally saved
  1979. token, which is the recommended method for authentication (see
  1980. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  1981. To disable authentication, pass `False`.
  1982. cache (`bool`, *optional*):
  1983. Whether to cache the result of the `whoami` call for subsequent calls.
  1984. If an error occurs during the first call, it won't be cached.
  1985. Defaults to `False`.
  1986. """
  1987. # Get the effective token using the helper function get_token
  1988. token = self.token if token is None else token
  1989. if token is False:
  1990. raise ValueError("Cannot use `token=False` with `whoami` method as it requires authentication.")
  1991. if token is True or token is None:
  1992. token = get_token()
  1993. if token is None:
  1994. raise LocalTokenNotFoundError(
  1995. "Token is required to call the /whoami-v2 endpoint, but no token found. You must provide a token or be logged in to "
  1996. "Hugging Face with `hf auth login` or `huggingface_hub.login`. See https://huggingface.co/settings/tokens."
  1997. )
  1998. if cache and (cached_token := self._whoami_cache.get(token)):
  1999. return cached_token
  2000. # Call Hub
  2001. output = self._inner_whoami(token=token)
  2002. # Cache result and return
  2003. if cache:
  2004. self._whoami_cache[token] = output
  2005. return output
  2006. def _inner_whoami(self, token: str) -> dict:
  2007. r = get_session().get(
  2008. f"{self.endpoint}/api/whoami-v2",
  2009. headers=self._build_hf_headers(token=token),
  2010. )
  2011. try:
  2012. hf_raise_for_status(r)
  2013. except HfHubHTTPError as e:
  2014. if e.response.status_code == 401:
  2015. error_message = "Invalid user token."
  2016. # Check which token is the effective one and generate the error message accordingly
  2017. if token == _get_token_from_google_colab():
  2018. error_message += " The token from Google Colab vault is invalid. Please update it from the UI."
  2019. elif token == _get_token_from_environment():
  2020. error_message += (
  2021. " The token from HF_TOKEN environment variable is invalid. "
  2022. "Note that HF_TOKEN takes precedence over `hf auth login`."
  2023. )
  2024. elif token == _get_token_from_file():
  2025. error_message += (
  2026. " The token stored is invalid. Please run `hf auth login --force` to set a new token."
  2027. )
  2028. raise HfHubHTTPError(error_message, response=e.response) from e
  2029. if e.response.status_code == 429:
  2030. error_message = (
  2031. "You've hit the rate limit for the /whoami-v2 endpoint, which is intentionally strict for security reasons."
  2032. " If you're calling it often, consider caching the response with `whoami(..., cache=True)`."
  2033. )
  2034. raise HfHubHTTPError(error_message, response=e.response) from e
  2035. raise
  2036. return r.json()
  2037. def get_model_tags(self) -> dict:
  2038. """
  2039. List all valid model tags as a nested namespace object
  2040. """
  2041. path = f"{self.endpoint}/api/models-tags-by-type"
  2042. r = get_session().get(path)
  2043. hf_raise_for_status(r)
  2044. return r.json()
  2045. def get_dataset_tags(self) -> dict:
  2046. """
  2047. List all valid dataset tags as a nested namespace object.
  2048. """
  2049. path = f"{self.endpoint}/api/datasets-tags-by-type"
  2050. r = get_session().get(path)
  2051. hf_raise_for_status(r)
  2052. return r.json()
  2053. @_deprecate_arguments(version="2.0", deprecated_args=["model_name"], custom_message="Use `search` instead.")
  2054. @validate_hf_hub_args
  2055. def list_models(
  2056. self,
  2057. *,
  2058. # Search-query parameter
  2059. filter: str | Iterable[str] | None = None,
  2060. author: str | None = None,
  2061. apps: str | list[str] | None = None,
  2062. gated: bool | None = None,
  2063. inference: Literal["warm"] | None = None,
  2064. inference_provider: Literal["all"] | PROVIDER_T | list[PROVIDER_T] | None = None,
  2065. model_name: str | None = None,
  2066. trained_dataset: str | list[str] | None = None,
  2067. search: str | None = None,
  2068. pipeline_tag: str | None = None,
  2069. num_parameters: str | None = None,
  2070. emissions_thresholds: tuple[float, float] | None = None,
  2071. # Sorting and pagination parameters
  2072. sort: ModelSort_T | None = None,
  2073. limit: int | None = None,
  2074. # Additional data to fetch
  2075. expand: list[ExpandModelProperty_T] | None = None,
  2076. full: bool | None = None,
  2077. cardData: bool = False,
  2078. fetch_config: bool = False,
  2079. token: bool | str | None = None,
  2080. ) -> Iterable[ModelInfo]:
  2081. """
  2082. List models hosted on the Huggingface Hub, given some filters.
  2083. Args:
  2084. filter (`str` or `Iterable[str]`, *optional*):
  2085. A string or list of string to filter models on the Hub.
  2086. Models can be filtered by library, language, task, tags, and more.
  2087. author (`str`, *optional*):
  2088. A string which identify the author (user or organization) of the
  2089. returned models.
  2090. apps (`str` or `List`, *optional*):
  2091. A string or list of strings to filter models on the Hub that
  2092. support the specified apps. Example values include `"ollama"` or `["ollama", "vllm"]`.
  2093. gated (`bool`, *optional*):
  2094. A boolean to filter models on the Hub that are gated or not. By default, all models are returned.
  2095. If `gated=True` is passed, only gated models are returned.
  2096. If `gated=False` is passed, only non-gated models are returned.
  2097. inference (`Literal["warm"]`, *optional*):
  2098. If "warm", filter models on the Hub currently served by at least one provider.
  2099. inference_provider (`Literal["all"]` or `str`, *optional*):
  2100. A string to filter models on the Hub that are served by a specific provider.
  2101. Pass `"all"` to get all models served by at least one provider.
  2102. trained_dataset (`str` or `List`, *optional*):
  2103. A string tag or a list of string tags of the trained dataset for a
  2104. model on the Hub.
  2105. search (`str`, *optional*):
  2106. A string that will be contained in the returned model ids.
  2107. pipeline_tag (`str`, *optional*):
  2108. A string pipeline tag to filter models on the Hub by, such as `summarization`.
  2109. num_parameters (`str`, *optional*):
  2110. Filter models by parameter count. Accepts the same range syntax as the Hub UI and API, for example
  2111. `"min:6B,max:128B"`, `"min:6B"` or `"max:128B"`.
  2112. emissions_thresholds (`Tuple`, *optional*):
  2113. A tuple of two ints or floats representing a minimum and maximum
  2114. carbon footprint to filter the resulting models with in grams.
  2115. sort (`ModelSort_T`, *optional*):
  2116. The key with which to sort the resulting models. Possible values are "created_at", "downloads",
  2117. "last_modified", "likes" and "trending_score".
  2118. limit (`int`, *optional*):
  2119. The limit on the number of models fetched. Leaving this option
  2120. to `None` fetches all models.
  2121. expand (`list[ExpandModelProperty_T]`, *optional*):
  2122. List properties to return in the response. When used, only the properties in the list will be returned.
  2123. This parameter cannot be used if `full`, `cardData` or `fetch_config` are passed.
  2124. Possible values are `"author"`, `"cardData"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"evalResults"`, `"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"`.
  2125. full (`bool`, *optional*):
  2126. Whether to fetch all model data, including the `last_modified`,
  2127. the `sha`, the files and the `tags`. This is set to `True` by
  2128. default when using a filter.
  2129. cardData (`bool`, *optional*):
  2130. Whether to grab the metadata for the model as well. Can contain
  2131. useful information such as carbon emissions, metrics, and
  2132. datasets trained on.
  2133. fetch_config (`bool`, *optional*):
  2134. Whether to fetch the model configs as well. This is not included
  2135. in `full` due to its size.
  2136. token (`bool` or `str`, *optional*):
  2137. A valid user access token (string). Defaults to the locally saved
  2138. token, which is the recommended method for authentication (see
  2139. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2140. To disable authentication, pass `False`.
  2141. model_name (`str`, *optional*):
  2142. (deprecated). Use `search` instead.
  2143. Returns:
  2144. `Iterable[ModelInfo]`: an iterable of [`huggingface_hub.hf_api.ModelInfo`] objects.
  2145. Example:
  2146. ```python
  2147. >>> from huggingface_hub import HfApi
  2148. >>> api = HfApi()
  2149. # List all models
  2150. >>> api.list_models()
  2151. # List text classification models
  2152. >>> api.list_models(filter="text-classification")
  2153. # List models from the KerasHub library
  2154. >>> api.list_models(filter="keras-hub")
  2155. # List models served by Cohere
  2156. >>> api.list_models(inference_provider="cohere")
  2157. # List models with "bert" in their name
  2158. >>> api.list_models(search="bert")
  2159. # List models with "bert" in their name and pushed by google
  2160. >>> api.list_models(search="bert", author="google")
  2161. # List models with 6B to 128B parameters
  2162. >>> api.list_models(num_parameters="min:6B,max:128B", sort="likes")
  2163. ```
  2164. """
  2165. if expand and (full or cardData or fetch_config):
  2166. raise ValueError("`expand` cannot be used if `full`, `cardData` or `fetch_config` are passed.")
  2167. if emissions_thresholds is not None and not cardData:
  2168. raise ValueError("`emissions_thresholds` were passed without setting `cardData=True`.")
  2169. path = f"{self.endpoint}/api/models"
  2170. headers = self._build_hf_headers(token=token)
  2171. params: dict[str, Any] = {}
  2172. # Build the filter list
  2173. filter_list: list[str] = []
  2174. if filter:
  2175. filter_list.extend([filter] if isinstance(filter, str) else filter)
  2176. if trained_dataset:
  2177. datasets = [trained_dataset] if isinstance(trained_dataset, str) else trained_dataset
  2178. filter_list.extend(f"dataset:{d}" if not d.startswith("dataset:") else d for d in datasets)
  2179. if len(filter_list) > 0:
  2180. params["filter"] = filter_list
  2181. # Handle other query params
  2182. if author:
  2183. params["author"] = author
  2184. if apps:
  2185. if isinstance(apps, str):
  2186. apps = [apps]
  2187. params["apps"] = apps
  2188. if gated is not None:
  2189. params["gated"] = gated
  2190. if inference is not None:
  2191. params["inference"] = inference
  2192. if inference_provider is not None:
  2193. params["inference_provider"] = inference_provider
  2194. if pipeline_tag:
  2195. params["pipeline_tag"] = pipeline_tag
  2196. if num_parameters is not None:
  2197. params["num_parameters"] = num_parameters
  2198. search_list = []
  2199. if model_name: # deprecated
  2200. search_list.append(model_name)
  2201. if search:
  2202. search_list.append(search)
  2203. if len(search_list) > 0:
  2204. params["search"] = search_list
  2205. if sort is not None:
  2206. params["sort"] = (
  2207. "lastModified"
  2208. if sort == "last_modified"
  2209. else "trendingScore"
  2210. if sort == "trending_score"
  2211. else "createdAt"
  2212. if sort == "created_at"
  2213. else sort
  2214. )
  2215. if limit is not None:
  2216. params["limit"] = limit
  2217. # Request additional data
  2218. if full:
  2219. params["full"] = True
  2220. if fetch_config:
  2221. params["config"] = True
  2222. if cardData:
  2223. params["cardData"] = True
  2224. if expand:
  2225. params["expand"] = expand
  2226. # `items` is a generator
  2227. items = paginate(path, params=params, headers=headers)
  2228. if limit is not None:
  2229. items = islice(items, limit) # Do not iterate over all pages
  2230. for item in items:
  2231. if "siblings" not in item:
  2232. item["siblings"] = None
  2233. model_info = ModelInfo(**item)
  2234. if emissions_thresholds is None or _is_emission_within_threshold(model_info, *emissions_thresholds):
  2235. yield model_info
  2236. @validate_hf_hub_args
  2237. def list_datasets(
  2238. self,
  2239. *,
  2240. # Search-query parameter
  2241. filter: str | Iterable[str] | None = None,
  2242. author: str | None = None,
  2243. benchmark: Literal[True] | Literal["official"] | str | None = None,
  2244. dataset_name: str | None = None,
  2245. gated: bool | None = None,
  2246. language_creators: str | list[str] | None = None,
  2247. language: str | list[str] | None = None,
  2248. multilinguality: str | list[str] | None = None,
  2249. size_categories: str | list[str] | None = None,
  2250. task_categories: str | list[str] | None = None,
  2251. task_ids: str | list[str] | None = None,
  2252. search: str | None = None,
  2253. # Sorting and pagination parameters
  2254. sort: DatasetSort_T | None = None,
  2255. limit: int | None = None,
  2256. # Additional data to fetch
  2257. expand: list[ExpandDatasetProperty_T] | None = None,
  2258. full: bool | None = None,
  2259. token: bool | str | None = None,
  2260. ) -> Iterable[DatasetInfo]:
  2261. """
  2262. List datasets hosted on the Huggingface Hub, given some filters.
  2263. Args:
  2264. filter (`str` or `Iterable[str]`, *optional*):
  2265. A string or list of string to filter datasets on the hub.
  2266. author (`str`, *optional*):
  2267. A string which identify the author of the returned datasets.
  2268. benchmark (`True`, `"official"`, `str`, *optional*):
  2269. Filter datasets by benchmark. Can be `True` or `"official"` to return official benchmark datasets.
  2270. For future-compatibility, can also be a string representing the benchmark name (currently only "official" is supported).
  2271. dataset_name (`str`, *optional*):
  2272. A string or list of strings that can be used to identify datasets on
  2273. the Hub by its name, such as `SQAC` or `wikineural`
  2274. gated (`bool`, *optional*):
  2275. A boolean to filter datasets on the Hub that are gated or not. By default, all datasets are returned.
  2276. If `gated=True` is passed, only gated datasets are returned.
  2277. If `gated=False` is passed, only non-gated datasets are returned.
  2278. language_creators (`str` or `List`, *optional*):
  2279. A string or list of strings that can be used to identify datasets on
  2280. the Hub with how the data was curated, such as `crowdsourced` or
  2281. `machine_generated`.
  2282. language (`str` or `List`, *optional*):
  2283. A string or list of strings representing a two-character language to
  2284. filter datasets by on the Hub.
  2285. multilinguality (`str` or `List`, *optional*):
  2286. A string or list of strings representing a filter for datasets that
  2287. contain multiple languages.
  2288. size_categories (`str` or `List`, *optional*):
  2289. A string or list of strings that can be used to identify datasets on
  2290. the Hub by the size of the dataset such as `100K<n<1M` or
  2291. `1M<n<10M`.
  2292. tags (`str` or `List`, *optional*):
  2293. Deprecated. Pass tags in `filter` to filter datasets by tags.
  2294. task_categories (`str` or `List`, *optional*):
  2295. A string or list of strings that can be used to identify datasets on
  2296. the Hub by the designed task, such as `audio_classification` or
  2297. `named_entity_recognition`.
  2298. task_ids (`str` or `List`, *optional*):
  2299. A string or list of strings that can be used to identify datasets on
  2300. the Hub by the specific task such as `speech_emotion_recognition` or
  2301. `paraphrase`.
  2302. search (`str`, *optional*):
  2303. A string that will be contained in the returned datasets.
  2304. sort (`DatasetSort_T`, *optional*):
  2305. The key with which to sort the resulting datasets. Possible values are "created_at", "downloads",
  2306. "last_modified", "likes" and "trending_score".
  2307. limit (`int`, *optional*):
  2308. The limit on the number of datasets fetched. Leaving this option
  2309. to `None` fetches all datasets.
  2310. expand (`list[ExpandDatasetProperty_T]`, *optional*):
  2311. List properties to return in the response. When used, only the properties in the list will be returned.
  2312. This parameter cannot be used if `full` is passed.
  2313. Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
  2314. full (`bool`, *optional*):
  2315. Whether to fetch all dataset data, including the `last_modified`,
  2316. the `card_data` and the files. Can contain useful information such as the
  2317. PapersWithCode ID.
  2318. token (`bool` or `str`, *optional*):
  2319. A valid user access token (string). Defaults to the locally saved
  2320. token, which is the recommended method for authentication (see
  2321. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2322. To disable authentication, pass `False`.
  2323. Returns:
  2324. `Iterable[DatasetInfo]`: an iterable of [`huggingface_hub.hf_api.DatasetInfo`] objects.
  2325. Example usage with the `filter` argument:
  2326. ```python
  2327. >>> from huggingface_hub import HfApi
  2328. >>> api = HfApi()
  2329. # List all datasets
  2330. >>> api.list_datasets()
  2331. # List only the text classification datasets
  2332. >>> api.list_datasets(filter="task_categories:text-classification")
  2333. # List only the datasets in russian for language modeling
  2334. >>> api.list_datasets(
  2335. ... filter=("language:ru", "task_ids:language-modeling")
  2336. ... )
  2337. # List FiftyOne datasets (identified by the tag "fiftyone" in dataset card)
  2338. >>> api.list_datasets(tags="fiftyone")
  2339. ```
  2340. Example usage with the `search` argument:
  2341. ```python
  2342. >>> from huggingface_hub import HfApi
  2343. >>> api = HfApi()
  2344. # List all datasets with "text" in their name
  2345. >>> api.list_datasets(search="text")
  2346. # List all datasets with "text" in their name made by google
  2347. >>> api.list_datasets(search="text", author="google")
  2348. ```
  2349. """
  2350. if expand and full:
  2351. raise ValueError("`expand` cannot be used if `full` is passed.")
  2352. path = f"{self.endpoint}/api/datasets"
  2353. headers = self._build_hf_headers(token=token)
  2354. params: dict[str, Any] = {}
  2355. # Build `filter` list
  2356. filter_list = []
  2357. if filter is not None:
  2358. if isinstance(filter, str):
  2359. filter_list.append(filter)
  2360. else:
  2361. filter_list.extend(filter)
  2362. for key, value in (
  2363. ("language_creators", language_creators),
  2364. ("language", language),
  2365. ("multilinguality", multilinguality),
  2366. ("size_categories", size_categories),
  2367. ("task_categories", task_categories),
  2368. ("task_ids", task_ids),
  2369. ):
  2370. if value:
  2371. if isinstance(value, str):
  2372. value = [value]
  2373. for value_item in value:
  2374. if not value_item.startswith(f"{key}:"):
  2375. data = f"{key}:{value_item}"
  2376. else:
  2377. data = value_item
  2378. filter_list.append(data)
  2379. if benchmark is not None:
  2380. if benchmark is True: # alias for official benchmark
  2381. benchmark = "official"
  2382. filter_list.append(f"benchmark:{benchmark}")
  2383. if len(filter_list) > 0:
  2384. params["filter"] = filter_list
  2385. # Handle other query params
  2386. if author:
  2387. params["author"] = author
  2388. if gated is not None:
  2389. params["gated"] = gated
  2390. search_list = []
  2391. if dataset_name:
  2392. search_list.append(dataset_name)
  2393. if search:
  2394. search_list.append(search)
  2395. if len(search_list) > 0:
  2396. params["search"] = search_list
  2397. if sort is not None:
  2398. params["sort"] = (
  2399. "lastModified"
  2400. if sort == "last_modified"
  2401. else "trendingScore"
  2402. if sort == "trending_score"
  2403. else "createdAt"
  2404. if sort == "created_at"
  2405. else sort
  2406. )
  2407. if limit is not None:
  2408. params["limit"] = limit
  2409. # Request additional data
  2410. if expand:
  2411. params["expand"] = expand
  2412. if full:
  2413. params["full"] = True
  2414. items = paginate(path, params=params, headers=headers)
  2415. if limit is not None:
  2416. items = islice(items, limit) # Do not iterate over all pages
  2417. for item in items:
  2418. if "siblings" not in item:
  2419. item["siblings"] = None
  2420. yield DatasetInfo(**item)
  2421. @validate_hf_hub_args
  2422. def list_dataset_parquet_files(
  2423. self,
  2424. repo_id: str,
  2425. *,
  2426. config: str | None = None,
  2427. token: bool | str | None = None,
  2428. ) -> list[DatasetParquetEntry]:
  2429. """List parquet files available for a dataset on the Hub.
  2430. All datasets hosted on the Hub are auto-converted to Parquet by the
  2431. [Dataset Viewer](https://huggingface.co/docs/dataset-viewer/parquet).
  2432. This method returns the list of parquet files with their URLs, configs,
  2433. splits and sizes.
  2434. Args:
  2435. repo_id (`str`):
  2436. The dataset repository ID (e.g. `"username/dataset-name"`).
  2437. config (`str`, *optional*):
  2438. Filter by a specific config/subset name. When provided, only
  2439. parquet files for that config are returned.
  2440. token (`bool` or `str`, *optional*):
  2441. A valid user access token (string). Defaults to the locally saved
  2442. token, which is the recommended method for authentication (see
  2443. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2444. To disable authentication, pass `False`.
  2445. Returns:
  2446. `list[DatasetParquetEntry]`: a list of [`DatasetParquetEntry`] objects
  2447. containing config, split, url and size for each parquet file.
  2448. Example:
  2449. ```python
  2450. >>> from huggingface_hub import list_dataset_parquet_files
  2451. >>> list_dataset_parquet_files("lhoestq/demo1")
  2452. >>> entries[0]
  2453. DatasetParquetEntry(config='default', split='train', url='https://huggingface.co/...', size=5038)
  2454. ```
  2455. """
  2456. if self.endpoint != constants._HF_DEFAULT_ENDPOINT:
  2457. raise ValueError(
  2458. "The Dataset Viewer is only available on the Hugging Face Hub"
  2459. f" (endpoint='{constants._HF_DEFAULT_ENDPOINT}'). It is not supported on"
  2460. f" third-party endpoints. (endpoint={self.endpoint})"
  2461. )
  2462. url = f"{constants.DATASETS_SERVER_ENDPOINT}/parquet"
  2463. params: dict[str, str] = {"dataset": repo_id}
  2464. if config is not None:
  2465. params["config"] = config
  2466. response = get_session().get(url, params=params, headers=self._build_hf_headers(token=token))
  2467. hf_raise_for_status(response)
  2468. payload = response.json()
  2469. return [
  2470. DatasetParquetEntry(
  2471. config=file_info["config"],
  2472. split=file_info["split"],
  2473. url=file_info["url"],
  2474. size=file_info["size"],
  2475. )
  2476. for file_info in payload.get("parquet_files", [])
  2477. ]
  2478. @validate_hf_hub_args
  2479. def list_spaces(
  2480. self,
  2481. *,
  2482. # Search-query parameter
  2483. filter: str | Iterable[str] | None = None,
  2484. author: str | None = None,
  2485. search: str | None = None,
  2486. datasets: str | Iterable[str] | None = None,
  2487. models: str | Iterable[str] | None = None,
  2488. linked: bool = False,
  2489. # Sorting and pagination parameters
  2490. sort: SpaceSort_T | None = None,
  2491. limit: int | None = None,
  2492. # Additional data to fetch
  2493. expand: list[ExpandSpaceProperty_T] | None = None,
  2494. full: bool | None = None,
  2495. token: bool | str | None = None,
  2496. ) -> Iterable[SpaceInfo]:
  2497. """
  2498. List spaces hosted on the Huggingface Hub, given some filters.
  2499. Args:
  2500. filter (`str` or `Iterable`, *optional*):
  2501. A string tag or list of tags that can be used to identify Spaces on the Hub.
  2502. author (`str`, *optional*):
  2503. A string which identify the author of the returned Spaces.
  2504. search (`str`, *optional*):
  2505. A string that will be contained in the returned Spaces.
  2506. datasets (`str` or `Iterable`, *optional*):
  2507. Whether to return Spaces that make use of a dataset.
  2508. The name of a specific dataset can be passed as a string.
  2509. models (`str` or `Iterable`, *optional*):
  2510. Whether to return Spaces that make use of a model.
  2511. The name of a specific model can be passed as a string.
  2512. linked (`bool`, *optional*):
  2513. Whether to return Spaces that make use of either a model or a dataset.
  2514. sort (`SpaceSort_T`, *optional*):
  2515. The key with which to sort the resulting spaces. Possible values are "created_at", "last_modified",
  2516. "likes" and "trending_score".
  2517. limit (`int`, *optional*):
  2518. The limit on the number of Spaces fetched. Leaving this option
  2519. to `None` fetches all Spaces.
  2520. expand (`list[ExpandSpaceProperty_T]`, *optional*):
  2521. List properties to return in the response. When used, only the properties in the list will be returned.
  2522. This parameter cannot be used if `full` is passed.
  2523. Possible values are `"author"`, `"cardData"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"createdAt"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
  2524. full (`bool`, *optional*):
  2525. Whether to fetch all Spaces data, including the `last_modified`, `siblings`
  2526. and `card_data` fields.
  2527. token (`bool` or `str`, *optional*):
  2528. A valid user access token (string). Defaults to the locally saved
  2529. token, which is the recommended method for authentication (see
  2530. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2531. To disable authentication, pass `False`.
  2532. Returns:
  2533. `Iterable[SpaceInfo]`: an iterable of [`huggingface_hub.hf_api.SpaceInfo`] objects.
  2534. """
  2535. if expand and full:
  2536. raise ValueError("`expand` cannot be used if `full` is passed.")
  2537. path = f"{self.endpoint}/api/spaces"
  2538. headers = self._build_hf_headers(token=token)
  2539. params: dict[str, Any] = {}
  2540. if filter is not None:
  2541. params["filter"] = filter
  2542. if author is not None:
  2543. params["author"] = author
  2544. if search is not None:
  2545. params["search"] = search
  2546. if sort is not None:
  2547. params["sort"] = (
  2548. "lastModified"
  2549. if sort == "last_modified"
  2550. else "trendingScore"
  2551. if sort == "trending_score"
  2552. else "createdAt"
  2553. if sort == "created_at"
  2554. else sort
  2555. )
  2556. if limit is not None:
  2557. params["limit"] = limit
  2558. if linked:
  2559. params["linked"] = True
  2560. if datasets is not None:
  2561. params["datasets"] = datasets
  2562. if models is not None:
  2563. params["models"] = models
  2564. # Request additional data
  2565. if expand:
  2566. params["expand"] = expand
  2567. if full:
  2568. params["full"] = True
  2569. items = paginate(path, params=params, headers=headers)
  2570. if limit is not None:
  2571. items = islice(items, limit) # Do not iterate over all pages
  2572. for item in items:
  2573. if "siblings" not in item:
  2574. item["siblings"] = None
  2575. yield SpaceInfo(**item)
  2576. @validate_hf_hub_args
  2577. def search_spaces(
  2578. self,
  2579. query: str,
  2580. *,
  2581. filter: str | Iterable[str] | None = None,
  2582. sdk: str | list[str] | None = None,
  2583. include_non_running: bool = False,
  2584. token: bool | str | None = None,
  2585. ) -> Iterable[SpaceSearchResult]:
  2586. """Search Spaces on the Hub using semantic search.
  2587. This endpoint uses semantic search (embedding-based) for multi-word queries
  2588. and full-text search for single-word queries.
  2589. Args:
  2590. query (`str`):
  2591. The search query string.
  2592. filter (`str` or `Iterable[str]`, *optional*):
  2593. A string tag or list of tags to filter by.
  2594. sdk (`str` or `list[str]`, *optional*):
  2595. Filter by SDK (e.g. `"gradio"`, `"docker"`, `"static"`).
  2596. include_non_running (`bool`, *optional*):
  2597. Whether to include non-running Spaces in results. Defaults to `False`.
  2598. token (`bool` or `str`, *optional*):
  2599. A valid user access token (string). Defaults to the locally saved
  2600. token, which is the recommended method for authentication (see
  2601. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2602. To disable authentication, pass `False`.
  2603. Returns:
  2604. `Iterable[SpaceSearchResult]`: an iterable of [`SpaceSearchResult`] objects.
  2605. Example:
  2606. ```python
  2607. >>> from huggingface_hub import HfApi
  2608. >>> api = HfApi()
  2609. >>> results = list(api.search_spaces("generate image"))
  2610. >>> results[0].id
  2611. 'mrfakename/Z-Image-Turbo'
  2612. >>> results[0].ai_category
  2613. 'Image Generation'
  2614. ```
  2615. """
  2616. path = f"{self.endpoint}/api/spaces/semantic-search"
  2617. headers = self._build_hf_headers(token=token)
  2618. params: dict[str, Any] = {"q": query}
  2619. if filter is not None:
  2620. params["filter"] = filter
  2621. if sdk is not None:
  2622. params["sdk"] = sdk
  2623. if include_non_running:
  2624. params["includeNonRunning"] = True
  2625. r = get_session().get(path, headers=headers, params=params)
  2626. hf_raise_for_status(r)
  2627. for item in r.json():
  2628. yield SpaceSearchResult(item)
  2629. @validate_hf_hub_args
  2630. def unlike(
  2631. self,
  2632. repo_id: str,
  2633. *,
  2634. token: bool | str | None = None,
  2635. repo_type: str | None = None,
  2636. ) -> None:
  2637. """
  2638. Unlike a given repo on the Hub (e.g. remove from favorite list).
  2639. To prevent spam usage, it is not possible to `like` a repository from a script.
  2640. See also [`list_liked_repos`].
  2641. Args:
  2642. repo_id (`str`):
  2643. The repository to unlike. Example: `"user/my-cool-model"`.
  2644. token (`bool` or `str`, *optional*):
  2645. A valid user access token (string). Defaults to the locally saved
  2646. token, which is the recommended method for authentication (see
  2647. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2648. To disable authentication, pass `False`.
  2649. repo_type (`str`, *optional*):
  2650. Set to `"dataset"` or `"space"` if unliking a dataset or space, `None` or
  2651. `"model"` if unliking a model. Default is `None`.
  2652. Raises:
  2653. [`~utils.RepositoryNotFoundError`]:
  2654. If repository is not found (error 404): wrong repo_id/repo_type, private
  2655. but not authenticated or repo does not exist.
  2656. Example:
  2657. ```python
  2658. >>> from huggingface_hub import list_liked_repos, unlike
  2659. >>> "gpt2" in list_liked_repos().models # we assume you have already liked gpt2
  2660. True
  2661. >>> unlike("gpt2")
  2662. >>> "gpt2" in list_liked_repos().models
  2663. False
  2664. ```
  2665. """
  2666. if repo_type is None:
  2667. repo_type = constants.REPO_TYPE_MODEL
  2668. response = get_session().delete(
  2669. url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/like", headers=self._build_hf_headers(token=token)
  2670. )
  2671. hf_raise_for_status(response)
  2672. @validate_hf_hub_args
  2673. def list_liked_repos(
  2674. self,
  2675. user: str | None = None,
  2676. *,
  2677. token: bool | str | None = None,
  2678. ) -> UserLikes:
  2679. """
  2680. List all public repos liked by a user on huggingface.co.
  2681. This list is public so token is optional. If `user` is not passed, it defaults to
  2682. the logged in user.
  2683. See also [`unlike`].
  2684. Args:
  2685. user (`str`, *optional*):
  2686. Name of the user for which you want to fetch the likes.
  2687. token (`bool` or `str`, *optional*):
  2688. A valid user access token (string). Defaults to the locally saved
  2689. token, which is the recommended method for authentication (see
  2690. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2691. To disable authentication, pass `False`.
  2692. Returns:
  2693. [`UserLikes`]: object containing the user name and 3 lists of repo ids (1 for
  2694. models, 1 for datasets and 1 for Spaces).
  2695. Raises:
  2696. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  2697. If `user` is not passed and no token found (either from argument or from machine).
  2698. Example:
  2699. ```python
  2700. >>> from huggingface_hub import list_liked_repos
  2701. >>> likes = list_liked_repos("julien-c")
  2702. >>> likes.user
  2703. "julien-c"
  2704. >>> likes.models
  2705. ["osanseviero/streamlit_1.15", "Xhaheen/ChatGPT_HF", ...]
  2706. ```
  2707. """
  2708. # User is either provided explicitly or retrieved from current token.
  2709. if user is None:
  2710. me = self.whoami(token=token)
  2711. if me["type"] == "user":
  2712. user = me["name"]
  2713. else:
  2714. raise ValueError(
  2715. "Cannot list liked repos. You must provide a 'user' as input or be logged in as a user."
  2716. )
  2717. path = f"{self.endpoint}/api/users/{user}/likes"
  2718. headers = self._build_hf_headers(token=token)
  2719. likes = list(paginate(path, params={}, headers=headers))
  2720. # Looping over a list of items similar to:
  2721. # {
  2722. # 'createdAt': '2021-09-09T21:53:27.000Z',
  2723. # 'repo': {
  2724. # 'name': 'PaddlePaddle/PaddleOCR',
  2725. # 'type': 'space'
  2726. # }
  2727. # }
  2728. # Let's loop 3 times over the received list. Less efficient but more straightforward to read.
  2729. return UserLikes(
  2730. user=user,
  2731. total=len(likes),
  2732. kernels=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "kernel"],
  2733. models=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "model"],
  2734. datasets=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "dataset"],
  2735. spaces=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "space"],
  2736. )
  2737. @validate_hf_hub_args
  2738. def list_repo_likers(
  2739. self,
  2740. repo_id: str,
  2741. *,
  2742. repo_type: str | None = None,
  2743. token: bool | str | None = None,
  2744. ) -> Iterable[User]:
  2745. """
  2746. List all users who liked a given repo on the hugging Face Hub.
  2747. See also [`list_liked_repos`].
  2748. Args:
  2749. repo_id (`str`):
  2750. The repository to retrieve . Example: `"user/my-cool-model"`.
  2751. token (`bool` or `str`, *optional*):
  2752. A valid user access token (string). Defaults to the locally saved
  2753. token, which is the recommended method for authentication (see
  2754. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2755. To disable authentication, pass `False`.
  2756. repo_type (`str`, *optional*):
  2757. Set to `"dataset"` or `"space"` if uploading to a dataset or
  2758. space, `None` or `"model"` if uploading to a model. Default is
  2759. `None`.
  2760. Returns:
  2761. `Iterable[User]`: an iterable of [`huggingface_hub.hf_api.User`] objects.
  2762. """
  2763. # Construct the API endpoint
  2764. if repo_type is None:
  2765. repo_type = constants.REPO_TYPE_MODEL
  2766. path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/likers"
  2767. for liker in paginate(path, params={}, headers=self._build_hf_headers(token=token)):
  2768. yield User(username=liker["user"], fullname=liker["fullname"], avatar_url=liker["avatarUrl"])
  2769. @validate_hf_hub_args
  2770. def model_info(
  2771. self,
  2772. repo_id: str,
  2773. *,
  2774. revision: str | None = None,
  2775. timeout: float | None = None,
  2776. securityStatus: bool | None = None,
  2777. files_metadata: bool = False,
  2778. expand: list[ExpandModelProperty_T] | None = None,
  2779. token: bool | str | None = None,
  2780. ) -> ModelInfo:
  2781. """
  2782. Get info on one specific model on huggingface.co
  2783. Model can be private if you pass an acceptable token or are logged in.
  2784. Args:
  2785. repo_id (`str`):
  2786. A namespace (user or an organization) and a repo name separated
  2787. by a `/`.
  2788. revision (`str`, *optional*):
  2789. The revision of the model repository from which to get the
  2790. information.
  2791. timeout (`float`, *optional*):
  2792. Whether to set a timeout for the request to the Hub.
  2793. securityStatus (`bool`, *optional*):
  2794. Whether to retrieve the security status from the model
  2795. repository as well. The security status will be returned in the `security_repo_status` field.
  2796. files_metadata (`bool`, *optional*):
  2797. Whether or not to retrieve metadata for files in the repository
  2798. (size, LFS metadata, etc). Defaults to `False`.
  2799. expand (`list[ExpandModelProperty_T]`, *optional*):
  2800. List properties to return in the response. When used, only the properties in the list will be returned.
  2801. This parameter cannot be used if `securityStatus` or `files_metadata` are passed.
  2802. Possible values are `"author"`, `"baseModels"`, `"cardData"`, `"childrenModelCount"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"evalResults"`, `"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"`.
  2803. token (`bool` or `str`, *optional*):
  2804. A valid user access token (string). Defaults to the locally saved
  2805. token, which is the recommended method for authentication (see
  2806. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2807. To disable authentication, pass `False`.
  2808. Returns:
  2809. [`huggingface_hub.hf_api.ModelInfo`]: The model repository information.
  2810. > [!TIP]
  2811. > Raises the following errors:
  2812. >
  2813. > - [`~utils.RepositoryNotFoundError`]
  2814. > If the repository to download from cannot be found. This may be because it doesn't exist,
  2815. > or because it is set to `private` and you do not have access.
  2816. > - [`~utils.RevisionNotFoundError`]
  2817. > If the revision to download from cannot be found.
  2818. """
  2819. if expand and (securityStatus or files_metadata):
  2820. raise ValueError("`expand` cannot be used if `securityStatus` or `files_metadata` are set.")
  2821. headers = self._build_hf_headers(token=token)
  2822. path = (
  2823. f"{self.endpoint}/api/models/{repo_id}"
  2824. if revision is None
  2825. else (f"{self.endpoint}/api/models/{repo_id}/revision/{quote(revision, safe='')}")
  2826. )
  2827. params: dict = {}
  2828. if securityStatus:
  2829. params["securityStatus"] = True
  2830. if files_metadata:
  2831. params["blobs"] = True
  2832. if expand:
  2833. params["expand"] = expand
  2834. r = get_session().get(path, headers=headers, timeout=timeout, params=params)
  2835. hf_raise_for_status(r)
  2836. data = r.json()
  2837. return ModelInfo(**data)
  2838. @validate_hf_hub_args
  2839. def dataset_info(
  2840. self,
  2841. repo_id: str,
  2842. *,
  2843. revision: str | None = None,
  2844. timeout: float | None = None,
  2845. files_metadata: bool = False,
  2846. expand: list[ExpandDatasetProperty_T] | None = None,
  2847. token: bool | str | None = None,
  2848. ) -> DatasetInfo:
  2849. """
  2850. Get info on one specific dataset on huggingface.co.
  2851. Dataset can be private if you pass an acceptable token.
  2852. Args:
  2853. repo_id (`str`):
  2854. A namespace (user or an organization) and a repo name separated
  2855. by a `/`.
  2856. revision (`str`, *optional*):
  2857. The revision of the dataset repository from which to get the
  2858. information.
  2859. timeout (`float`, *optional*):
  2860. Whether to set a timeout for the request to the Hub.
  2861. files_metadata (`bool`, *optional*):
  2862. Whether or not to retrieve metadata for files in the repository
  2863. (size, LFS metadata, etc). Defaults to `False`.
  2864. expand (`list[ExpandDatasetProperty_T]`, *optional*):
  2865. List properties to return in the response. When used, only the properties in the list will be returned.
  2866. This parameter cannot be used if `files_metadata` is passed.
  2867. Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`,`"usedStorage"`, and `"resourceGroup"`.
  2868. token (`bool` or `str`, *optional*):
  2869. A valid user access token (string). Defaults to the locally saved
  2870. token, which is the recommended method for authentication (see
  2871. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2872. To disable authentication, pass `False`.
  2873. Returns:
  2874. [`hf_api.DatasetInfo`]: The dataset repository information.
  2875. > [!TIP]
  2876. > Raises the following errors:
  2877. >
  2878. > - [`~utils.RepositoryNotFoundError`]
  2879. > If the repository to download from cannot be found. This may be because it doesn't exist,
  2880. > or because it is set to `private` and you do not have access.
  2881. > - [`~utils.RevisionNotFoundError`]
  2882. > If the revision to download from cannot be found.
  2883. """
  2884. if expand and files_metadata:
  2885. raise ValueError("`expand` cannot be used if `files_metadata` is set.")
  2886. headers = self._build_hf_headers(token=token)
  2887. path = (
  2888. f"{self.endpoint}/api/datasets/{repo_id}"
  2889. if revision is None
  2890. else (f"{self.endpoint}/api/datasets/{repo_id}/revision/{quote(revision, safe='')}")
  2891. )
  2892. params: dict = {}
  2893. if files_metadata:
  2894. params["blobs"] = True
  2895. if expand:
  2896. params["expand"] = expand
  2897. r = get_session().get(path, headers=headers, timeout=timeout, params=params)
  2898. hf_raise_for_status(r)
  2899. data = r.json()
  2900. return DatasetInfo(**data)
  2901. @validate_hf_hub_args
  2902. def get_dataset_leaderboard(
  2903. self,
  2904. repo_id: str,
  2905. *,
  2906. token: bool | str | None = None,
  2907. timeout: float | None = None,
  2908. ) -> list[DatasetLeaderboardEntry]:
  2909. """Get the leaderboard for a dataset on the Hub.
  2910. The leaderboard ranks models based on their evaluation scores on the given benchmark
  2911. dataset. Not all datasets have leaderboards — only benchmark datasets with evaluation
  2912. results submitted to them. This gives a dataset-centric view of scores; for a model-centric
  2913. view, use [`model_info`] with `expand=["evalResults"]`.
  2914. Args:
  2915. repo_id (`str`):
  2916. A namespace (user or an organization) and a repo name separated
  2917. by a `/`. For example: `"allenai/olmOCR-bench"`.
  2918. token (`bool` or `str`, *optional*):
  2919. A valid user access token. Defaults to the locally saved
  2920. token, which is the recommended method for authentication (see
  2921. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2922. To disable authentication, pass `False`.
  2923. timeout (`float`, *optional*):
  2924. Whether to set a timeout for the request to the Hub.
  2925. Returns:
  2926. `list[DatasetLeaderboardEntry]`: A list of [`DatasetLeaderboardEntry`] objects representing
  2927. the leaderboard entries, sorted by rank.
  2928. > [!TIP]
  2929. > Raises the following errors:
  2930. >
  2931. > - [`~utils.RepositoryNotFoundError`]
  2932. > If the repository cannot be found. This may be because it doesn't exist,
  2933. > or because it is set to `private` and you do not have access.
  2934. > - [`~utils.HfHubHTTPError`]
  2935. > If the dataset does not have a leaderboard.
  2936. Example:
  2937. ```python
  2938. >>> from huggingface_hub import HfApi
  2939. >>> api = HfApi()
  2940. >>> leaderboard = api.get_dataset_leaderboard("allenai/olmOCR-bench")
  2941. >>> leaderboard[0].model_id
  2942. 'datalab-to/chandra-ocr-2'
  2943. >>> leaderboard[0].rank
  2944. 1
  2945. ```
  2946. """
  2947. headers = self._build_hf_headers(token=token)
  2948. path = f"{self.endpoint}/api/datasets/{repo_id}/leaderboard"
  2949. r = get_session().get(path, headers=headers, timeout=timeout)
  2950. hf_raise_for_status(r)
  2951. data = r.json()
  2952. return [DatasetLeaderboardEntry(**entry) for entry in data]
  2953. @validate_hf_hub_args
  2954. def space_info(
  2955. self,
  2956. repo_id: str,
  2957. *,
  2958. revision: str | None = None,
  2959. timeout: float | None = None,
  2960. files_metadata: bool = False,
  2961. expand: list[ExpandSpaceProperty_T] | None = None,
  2962. token: bool | str | None = None,
  2963. ) -> SpaceInfo:
  2964. """
  2965. Get info on one specific Space on huggingface.co.
  2966. Space can be private if you pass an acceptable token.
  2967. Args:
  2968. repo_id (`str`):
  2969. A namespace (user or an organization) and a repo name separated
  2970. by a `/`.
  2971. revision (`str`, *optional*):
  2972. The revision of the space repository from which to get the
  2973. information.
  2974. timeout (`float`, *optional*):
  2975. Whether to set a timeout for the request to the Hub.
  2976. files_metadata (`bool`, *optional*):
  2977. Whether or not to retrieve metadata for files in the repository
  2978. (size, LFS metadata, etc). Defaults to `False`.
  2979. expand (`list[ExpandSpaceProperty_T]`, *optional*):
  2980. List properties to return in the response. When used, only the properties in the list will be returned.
  2981. This parameter cannot be used if `full` is passed.
  2982. Possible values are `"author"`, `"cardData"`, `"createdAt"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
  2983. token (`bool` or `str`, *optional*):
  2984. A valid user access token (string). Defaults to the locally saved
  2985. token, which is the recommended method for authentication (see
  2986. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2987. To disable authentication, pass `False`.
  2988. Returns:
  2989. [`~hf_api.SpaceInfo`]: The space repository information.
  2990. > [!TIP]
  2991. > Raises the following errors:
  2992. >
  2993. > - [`~utils.RepositoryNotFoundError`]
  2994. > If the repository to download from cannot be found. This may be because it doesn't exist,
  2995. > or because it is set to `private` and you do not have access.
  2996. > - [`~utils.RevisionNotFoundError`]
  2997. > If the revision to download from cannot be found.
  2998. """
  2999. if expand and files_metadata:
  3000. raise ValueError("`expand` cannot be used if `files_metadata` is set.")
  3001. headers = self._build_hf_headers(token=token)
  3002. path = (
  3003. f"{self.endpoint}/api/spaces/{repo_id}"
  3004. if revision is None
  3005. else (f"{self.endpoint}/api/spaces/{repo_id}/revision/{quote(revision, safe='')}")
  3006. )
  3007. params: dict = {}
  3008. if files_metadata:
  3009. params["blobs"] = True
  3010. if expand:
  3011. params["expand"] = expand
  3012. r = get_session().get(path, headers=headers, timeout=timeout, params=params)
  3013. hf_raise_for_status(r)
  3014. data = r.json()
  3015. return SpaceInfo(**data)
  3016. @validate_hf_hub_args
  3017. def kernel_info(
  3018. self,
  3019. repo_id: str,
  3020. *,
  3021. revision: str | None = None,
  3022. timeout: float | None = None,
  3023. token: bool | str | None = None,
  3024. ) -> KernelInfo:
  3025. """
  3026. Get info on one specific kernel on huggingface.co.
  3027. Args:
  3028. repo_id (`str`):
  3029. A namespace (user or an organization) and a repo name separated by a `/`.
  3030. revision (`str`, *optional*):
  3031. The revision of the kernel repository from which to get the
  3032. information.
  3033. timeout (`float`, *optional*):
  3034. Whether to set a timeout for the request to the Hub.
  3035. token (`bool` or `str`, *optional*):
  3036. A valid user access token (string). Defaults to the locally saved
  3037. token, which is the recommended method for authentication (see
  3038. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3039. To disable authentication, pass `False`.
  3040. Returns:
  3041. [`~hf_api.ModelInfo`]: The kernel repository information.
  3042. """
  3043. headers = self._build_hf_headers(token=token)
  3044. path = (
  3045. f"{self.endpoint}/api/kernels/{repo_id}"
  3046. if revision is None
  3047. else (f"{self.endpoint}/api/kernels/{repo_id}/revision/{quote(revision, safe='')}")
  3048. )
  3049. r = get_session().get(path, headers=headers, timeout=timeout)
  3050. hf_raise_for_status(r)
  3051. data = r.json()
  3052. return KernelInfo(**data)
  3053. @validate_hf_hub_args
  3054. def repo_info(
  3055. self,
  3056. repo_id: str,
  3057. *,
  3058. revision: str | None = None,
  3059. repo_type: str | None = None,
  3060. timeout: float | None = None,
  3061. files_metadata: bool = False,
  3062. expand: ExpandModelProperty_T | ExpandDatasetProperty_T | ExpandSpaceProperty_T | None = None,
  3063. token: bool | str | None = None,
  3064. ) -> ModelInfo | DatasetInfo | SpaceInfo | KernelInfo:
  3065. """
  3066. Get the info object for a given repo of a given type.
  3067. Args:
  3068. repo_id (`str`):
  3069. A namespace (user or an organization) and a repo name separated
  3070. by a `/`.
  3071. revision (`str`, *optional*):
  3072. The revision of the repository from which to get the
  3073. information.
  3074. repo_type (`str`, *optional*):
  3075. Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
  3076. `None` or `"model"` if getting repository info from a model. Default is `None`.
  3077. timeout (`float`, *optional*):
  3078. Whether to set a timeout for the request to the Hub.
  3079. expand (`ExpandModelProperty_T` or `ExpandDatasetProperty_T` or `ExpandSpaceProperty_T`, *optional*):
  3080. List properties to return in the response. When used, only the properties in the list will be returned.
  3081. This parameter cannot be used if `files_metadata` is passed.
  3082. For an exhaustive list of available properties, check out [`model_info`], [`dataset_info`] or [`space_info`].
  3083. files_metadata (`bool`, *optional*):
  3084. Whether or not to retrieve metadata for files in the repository
  3085. (size, LFS metadata, etc). Defaults to `False`.
  3086. token (`bool` or `str`, *optional*):
  3087. A valid user access token (string). Defaults to the locally saved
  3088. token, which is the recommended method for authentication (see
  3089. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3090. To disable authentication, pass `False`.
  3091. Returns:
  3092. `Union[SpaceInfo, DatasetInfo, ModelInfo]`: The repository information, as a
  3093. [`huggingface_hub.hf_api.DatasetInfo`], [`huggingface_hub.hf_api.ModelInfo`]
  3094. or [`huggingface_hub.hf_api.SpaceInfo`] object.
  3095. > [!TIP]
  3096. > Raises the following errors:
  3097. >
  3098. > - [`~utils.RepositoryNotFoundError`]
  3099. > If the repository to download from cannot be found. This may be because it doesn't exist,
  3100. > or because it is set to `private` and you do not have access.
  3101. > - [`~utils.RevisionNotFoundError`]
  3102. > If the revision to download from cannot be found.
  3103. """
  3104. match repo_type:
  3105. case None | "model":
  3106. method = self.model_info
  3107. case "dataset":
  3108. method = self.dataset_info # type: ignore
  3109. case "space":
  3110. method = self.space_info # type: ignore
  3111. case "kernel":
  3112. # No expand/files_metadata for kernels
  3113. return self.kernel_info(repo_id, revision=revision, token=token, timeout=timeout)
  3114. case _:
  3115. raise ValueError("Unsupported repo type.")
  3116. return method(
  3117. repo_id,
  3118. revision=revision,
  3119. token=token,
  3120. timeout=timeout,
  3121. expand=expand, # type: ignore
  3122. files_metadata=files_metadata,
  3123. )
  3124. @validate_hf_hub_args
  3125. def repo_exists(
  3126. self,
  3127. repo_id: str,
  3128. *,
  3129. repo_type: str | None = None,
  3130. token: str | bool | None = None,
  3131. ) -> bool:
  3132. """
  3133. Checks if a repository exists on the Hugging Face Hub.
  3134. Args:
  3135. repo_id (`str`):
  3136. A namespace (user or an organization) and a repo name separated
  3137. by a `/`.
  3138. repo_type (`str`, *optional*):
  3139. Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
  3140. `None` or `"model"` if getting repository info from a model. Default is `None`.
  3141. token (`bool` or `str`, *optional*):
  3142. A valid user access token (string). Defaults to the locally saved
  3143. token, which is the recommended method for authentication (see
  3144. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3145. To disable authentication, pass `False`.
  3146. Returns:
  3147. True if the repository exists, False otherwise.
  3148. Examples:
  3149. ```py
  3150. >>> from huggingface_hub import repo_exists
  3151. >>> repo_exists("google/gemma-7b")
  3152. True
  3153. >>> repo_exists("google/not-a-repo")
  3154. False
  3155. ```
  3156. """
  3157. try:
  3158. self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token)
  3159. return True
  3160. except GatedRepoError:
  3161. return True # we don't have access but it exists
  3162. except RepositoryNotFoundError:
  3163. return False
  3164. @validate_hf_hub_args
  3165. def revision_exists(
  3166. self,
  3167. repo_id: str,
  3168. revision: str,
  3169. *,
  3170. repo_type: str | None = None,
  3171. token: str | bool | None = None,
  3172. ) -> bool:
  3173. """
  3174. Checks if a specific revision exists on a repo on the Hugging Face Hub.
  3175. Args:
  3176. repo_id (`str`):
  3177. A namespace (user or an organization) and a repo name separated
  3178. by a `/`.
  3179. revision (`str`):
  3180. The revision of the repository to check.
  3181. repo_type (`str`, *optional*):
  3182. Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
  3183. `None` or `"model"` if getting repository info from a model. Default is `None`.
  3184. token (`bool` or `str`, *optional*):
  3185. A valid user access token (string). Defaults to the locally saved
  3186. token, which is the recommended method for authentication (see
  3187. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3188. To disable authentication, pass `False`.
  3189. Returns:
  3190. True if the repository and the revision exists, False otherwise.
  3191. Examples:
  3192. ```py
  3193. >>> from huggingface_hub import revision_exists
  3194. >>> revision_exists("google/gemma-7b", "float16")
  3195. True
  3196. >>> revision_exists("google/gemma-7b", "not-a-revision")
  3197. False
  3198. ```
  3199. """
  3200. try:
  3201. self.repo_info(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token)
  3202. return True
  3203. except RevisionNotFoundError:
  3204. return False
  3205. except RepositoryNotFoundError:
  3206. return False
  3207. @validate_hf_hub_args
  3208. def file_exists(
  3209. self,
  3210. repo_id: str,
  3211. filename: str,
  3212. *,
  3213. repo_type: str | None = None,
  3214. revision: str | None = None,
  3215. token: str | bool | None = None,
  3216. ) -> bool:
  3217. """
  3218. Checks if a file exists in a repository on the Hugging Face Hub.
  3219. Args:
  3220. repo_id (`str`):
  3221. A namespace (user or an organization) and a repo name separated
  3222. by a `/`.
  3223. filename (`str`):
  3224. The name of the file to check, for example:
  3225. `"config.json"`
  3226. repo_type (`str`, *optional*):
  3227. Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
  3228. `None` or `"model"` if getting repository info from a model. Default is `None`.
  3229. revision (`str`, *optional*):
  3230. The revision of the repository from which to get the information. Defaults to `"main"` branch.
  3231. token (`bool` or `str`, *optional*):
  3232. A valid user access token (string). Defaults to the locally saved
  3233. token, which is the recommended method for authentication (see
  3234. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3235. To disable authentication, pass `False`.
  3236. Returns:
  3237. True if the file exists, False otherwise.
  3238. Examples:
  3239. ```py
  3240. >>> from huggingface_hub import file_exists
  3241. >>> file_exists("bigcode/starcoder", "config.json")
  3242. True
  3243. >>> file_exists("bigcode/starcoder", "not-a-file")
  3244. False
  3245. >>> file_exists("bigcode/not-a-repo", "config.json")
  3246. False
  3247. ```
  3248. """
  3249. url = hf_hub_url(
  3250. repo_id=repo_id, repo_type=repo_type, revision=revision, filename=filename, endpoint=self.endpoint
  3251. )
  3252. try:
  3253. if token is None:
  3254. token = self.token
  3255. get_hf_file_metadata(url, token=token)
  3256. return True
  3257. except GatedRepoError: # raise specifically on gated repo
  3258. raise
  3259. except (RepositoryNotFoundError, RemoteEntryNotFoundError, RevisionNotFoundError):
  3260. return False
  3261. @validate_hf_hub_args
  3262. def list_repo_files(
  3263. self,
  3264. repo_id: str,
  3265. *,
  3266. revision: str | None = None,
  3267. repo_type: str | None = None,
  3268. token: str | bool | None = None,
  3269. ) -> list[str]:
  3270. """
  3271. Get the list of files in a given repo.
  3272. Args:
  3273. repo_id (`str`):
  3274. A namespace (user or an organization) and a repo name separated by a `/`.
  3275. revision (`str`, *optional*):
  3276. The revision of the repository from which to get the information.
  3277. repo_type (`str`, *optional*):
  3278. Set to `"dataset"` or `"space"` if uploading to a dataset or space, `None` or `"model"` if uploading to
  3279. a model. Default is `None`.
  3280. token (`bool` or `str`, *optional*):
  3281. A valid user access token (string). Defaults to the locally saved
  3282. token, which is the recommended method for authentication (see
  3283. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3284. To disable authentication, pass `False`.
  3285. Returns:
  3286. `list[str]`: the list of files in a given repository.
  3287. """
  3288. return [
  3289. f.rfilename
  3290. for f in self.list_repo_tree(
  3291. repo_id=repo_id, recursive=True, revision=revision, repo_type=repo_type, token=token
  3292. )
  3293. if isinstance(f, RepoFile)
  3294. ]
  3295. @validate_hf_hub_args
  3296. def list_repo_tree(
  3297. self,
  3298. repo_id: str,
  3299. path_in_repo: str | None = None,
  3300. *,
  3301. recursive: bool = False,
  3302. expand: bool = False,
  3303. revision: str | None = None,
  3304. repo_type: str | None = None,
  3305. token: str | bool | None = None,
  3306. ) -> Iterable[RepoFile | RepoFolder]:
  3307. """
  3308. List a repo tree's files and folders and get information about them.
  3309. Args:
  3310. repo_id (`str`):
  3311. A namespace (user or an organization) and a repo name separated by a `/`.
  3312. path_in_repo (`str`, *optional*):
  3313. Relative path of the tree (folder) in the repo, for example:
  3314. `"checkpoints/1fec34a/results"`. Will default to the root tree (folder) of the repository.
  3315. recursive (`bool`, *optional*, defaults to `False`):
  3316. Whether to list tree's files and folders recursively.
  3317. expand (`bool`, *optional*, defaults to `False`):
  3318. Whether to fetch more information about the tree's files and folders (e.g. last commit and files' security scan results). This
  3319. operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
  3320. As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
  3321. takes to get the results.
  3322. revision (`str`, *optional*):
  3323. The revision of the repository from which to get the tree. Defaults to `"main"` branch.
  3324. repo_type (`str`, *optional*):
  3325. The type of the repository from which to get the tree (`"model"`, `"dataset"`, `"space"` or `"kernel"`).
  3326. Defaults to `"model"`.
  3327. token (`bool` or `str`, *optional*):
  3328. A valid user access token (string). Defaults to the locally saved
  3329. token, which is the recommended method for authentication (see
  3330. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3331. To disable authentication, pass `False`.
  3332. Returns:
  3333. `Iterable[Union[RepoFile, RepoFolder]]`:
  3334. 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
  3335. not guaranteed.
  3336. Raises:
  3337. [`~utils.RepositoryNotFoundError`]:
  3338. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  3339. does not exist.
  3340. [`~utils.RevisionNotFoundError`]:
  3341. If revision is not found (error 404) on the repo.
  3342. [`~utils.RemoteEntryNotFoundError`]:
  3343. If the tree (folder) does not exist (error 404) on the repo.
  3344. Examples:
  3345. Get information about a repo's tree.
  3346. ```py
  3347. >>> from huggingface_hub import list_repo_tree
  3348. >>> repo_tree = list_repo_tree("lysandre/arxiv-nlp")
  3349. >>> repo_tree
  3350. <generator object HfApi.list_repo_tree at 0x7fa4088e1ac0>
  3351. >>> list(repo_tree)
  3352. [
  3353. RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None),
  3354. RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None),
  3355. RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None),
  3356. RepoFile(
  3357. path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e',
  3358. lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None
  3359. ),
  3360. RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None),
  3361. RepoFile(
  3362. path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523',
  3363. lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None
  3364. ),
  3365. RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)]
  3366. ]
  3367. ```
  3368. Get even more information about a repo's tree (last commit and files' security scan results)
  3369. ```py
  3370. >>> from huggingface_hub import list_repo_tree
  3371. >>> repo_tree = list_repo_tree("prompthero/openjourney-v4", expand=True)
  3372. >>> list(repo_tree)
  3373. [
  3374. RepoFolder(
  3375. path='feature_extractor',
  3376. tree_id='aa536c4ea18073388b5b0bc791057a7296a00398',
  3377. last_commit={
  3378. 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
  3379. 'title': 'Upload diffusers weights (#48)',
  3380. 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
  3381. }
  3382. ),
  3383. RepoFolder(
  3384. path='safety_checker',
  3385. tree_id='65aef9d787e5557373fdf714d6c34d4fcdd70440',
  3386. last_commit={
  3387. 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
  3388. 'title': 'Upload diffusers weights (#48)',
  3389. 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
  3390. }
  3391. ),
  3392. RepoFile(
  3393. path='model_index.json',
  3394. size=582,
  3395. blob_id='d3d7c1e8c3e78eeb1640b8e2041ee256e24c9ee1',
  3396. lfs=None,
  3397. last_commit={
  3398. 'oid': 'b195ed2d503f3eb29637050a886d77bd81d35f0e',
  3399. 'title': 'Fix deprecation warning by changing `CLIPFeatureExtractor` to `CLIPImageProcessor`. (#54)',
  3400. 'date': datetime.datetime(2023, 5, 15, 21, 41, 59, tzinfo=datetime.timezone.utc)
  3401. },
  3402. security={
  3403. 'safe': True,
  3404. 'av_scan': {'virusFound': False, 'virusNames': None},
  3405. 'pickle_import_scan': None
  3406. }
  3407. )
  3408. ...
  3409. ]
  3410. ```
  3411. """
  3412. repo_type = repo_type or constants.REPO_TYPE_MODEL
  3413. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  3414. headers = self._build_hf_headers(token=token)
  3415. encoded_path_in_repo = "/" + quote(path_in_repo, safe="") if path_in_repo else ""
  3416. tree_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tree/{revision}{encoded_path_in_repo}"
  3417. for path_info in paginate(path=tree_url, headers=headers, params={"recursive": recursive, "expand": expand}):
  3418. yield (RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info))
  3419. @validate_hf_hub_args
  3420. def verify_repo_checksums(
  3421. self,
  3422. repo_id: str,
  3423. *,
  3424. repo_type: str | None = None,
  3425. revision: str | None = None,
  3426. local_dir: str | Path | None = None,
  3427. cache_dir: str | Path | None = None,
  3428. token: str | bool | None = None,
  3429. ) -> FolderVerification:
  3430. """
  3431. Verify local files for a repo against Hub checksums.
  3432. Args:
  3433. repo_id (`str`):
  3434. A namespace (user or an organization) and a repo name separated by a `/`.
  3435. repo_type (`str`, *optional*):
  3436. The type of the repository from which to get the tree (`"model"`, `"dataset"` or `"space"`.
  3437. Defaults to `"model"`.
  3438. revision (`str`, *optional*):
  3439. The revision of the repository from which to get the tree. Defaults to `"main"` branch.
  3440. local_dir (`str` or `Path`, *optional*):
  3441. The local directory to verify.
  3442. cache_dir (`str` or `Path`, *optional*):
  3443. The cache directory to verify.
  3444. token (Union[bool, str, None], optional):
  3445. A valid user access token (string). Defaults to the locally saved
  3446. token, which is the recommended method for authentication (see
  3447. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3448. To disable authentication, pass `False`.
  3449. Returns:
  3450. [`FolderVerification`]: a structured result containing the verification details.
  3451. Raises:
  3452. [`~utils.RepositoryNotFoundError`]:
  3453. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  3454. does not exist.
  3455. [`~utils.RevisionNotFoundError`]:
  3456. If revision is not found (error 404) on the repo.
  3457. """
  3458. if repo_type is None:
  3459. repo_type = constants.REPO_TYPE_MODEL
  3460. if local_dir is not None and cache_dir is not None:
  3461. raise ValueError("Pass either `local_dir` or `cache_dir`, not both.")
  3462. root, remote_revision = resolve_local_root(
  3463. repo_id=repo_id,
  3464. repo_type=repo_type,
  3465. revision=revision,
  3466. cache_dir=Path(cache_dir) if cache_dir is not None else None,
  3467. local_dir=Path(local_dir) if local_dir is not None else None,
  3468. )
  3469. local_by_path = collect_local_files(root)
  3470. # get remote entries (only files, not folders)
  3471. remote_by_path: dict[str, RepoFile] = {}
  3472. for entry in self.list_repo_tree(
  3473. repo_id=repo_id, recursive=True, revision=remote_revision, repo_type=repo_type, token=token
  3474. ):
  3475. if isinstance(entry, RepoFile):
  3476. remote_by_path[entry.path] = entry
  3477. return verify_maps(
  3478. remote_by_path=remote_by_path,
  3479. local_by_path=local_by_path,
  3480. revision=remote_revision,
  3481. verified_path=root,
  3482. )
  3483. @validate_hf_hub_args
  3484. def list_repo_refs(
  3485. self,
  3486. repo_id: str,
  3487. *,
  3488. repo_type: str | None = None,
  3489. include_pull_requests: bool = False,
  3490. token: str | bool | None = None,
  3491. ) -> GitRefs:
  3492. """
  3493. Get the list of refs of a given repo (both tags and branches).
  3494. Args:
  3495. repo_id (`str`):
  3496. A namespace (user or an organization) and a repo name separated
  3497. by a `/`.
  3498. repo_type (`str`, *optional*):
  3499. Set to `"dataset"`, `"space"` or `"kernel"` if listing refs from a dataset, a Space or a Kernel,
  3500. `None` or `"model"` if listing from a model. Default is `None`.
  3501. include_pull_requests (`bool`, *optional*):
  3502. Whether to include refs from pull requests in the list. Defaults to `False`.
  3503. token (`bool` or `str`, *optional*):
  3504. A valid user access token (string). Defaults to the locally saved
  3505. token, which is the recommended method for authentication (see
  3506. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3507. To disable authentication, pass `False`.
  3508. Example:
  3509. ```py
  3510. >>> from huggingface_hub import HfApi
  3511. >>> api = HfApi()
  3512. >>> api.list_repo_refs("gpt2")
  3513. GitRefs(branches=[GitRefInfo(name='main', ref='refs/heads/main', target_commit='e7da7f221d5bf496a48136c0cd264e630fe9fcc8')], converts=[], tags=[])
  3514. >>> api.list_repo_refs("bigcode/the-stack", repo_type='dataset')
  3515. GitRefs(
  3516. branches=[
  3517. GitRefInfo(name='main', ref='refs/heads/main', target_commit='18edc1591d9ce72aa82f56c4431b3c969b210ae3'),
  3518. GitRefInfo(name='v1.1.a1', ref='refs/heads/v1.1.a1', target_commit='f9826b862d1567f3822d3d25649b0d6d22ace714')
  3519. ],
  3520. converts=[],
  3521. tags=[
  3522. GitRefInfo(name='v1.0', ref='refs/tags/v1.0', target_commit='c37a8cd1e382064d8aced5e05543c5f7753834da')
  3523. ]
  3524. )
  3525. ```
  3526. Returns:
  3527. [`GitRefs`]: object containing all information about branches and tags for a
  3528. repo on the Hub.
  3529. """
  3530. repo_type = repo_type or constants.REPO_TYPE_MODEL
  3531. response = get_session().get(
  3532. f"{self.endpoint}/api/{repo_type}s/{repo_id}/refs",
  3533. headers=self._build_hf_headers(token=token),
  3534. params={"include_prs": 1} if include_pull_requests else {},
  3535. )
  3536. hf_raise_for_status(response)
  3537. data = response.json()
  3538. def _format_as_git_ref_info(item: dict) -> GitRefInfo:
  3539. return GitRefInfo(name=item["name"], ref=item["ref"], target_commit=item["targetCommit"])
  3540. return GitRefs(
  3541. branches=[_format_as_git_ref_info(item) for item in data["branches"]],
  3542. converts=[_format_as_git_ref_info(item) for item in data["converts"]],
  3543. tags=[_format_as_git_ref_info(item) for item in data["tags"]],
  3544. pull_requests=[_format_as_git_ref_info(item) for item in data["pullRequests"]]
  3545. if include_pull_requests
  3546. else None,
  3547. )
  3548. @validate_hf_hub_args
  3549. def list_repo_commits(
  3550. self,
  3551. repo_id: str,
  3552. *,
  3553. repo_type: str | None = None,
  3554. token: bool | str | None = None,
  3555. revision: str | None = None,
  3556. formatted: bool = False,
  3557. ) -> list[GitCommitInfo]:
  3558. """
  3559. Get the list of commits of a given revision for a repo on the Hub.
  3560. Commits are sorted by date (last commit first).
  3561. Args:
  3562. repo_id (`str`):
  3563. A namespace (user or an organization) and a repo name separated by a `/`.
  3564. repo_type (`str`, *optional*):
  3565. Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
  3566. listing from a model. Default is `None`.
  3567. token (`bool` or `str`, *optional*):
  3568. A valid user access token (string). Defaults to the locally saved
  3569. token, which is the recommended method for authentication (see
  3570. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3571. To disable authentication, pass `False`.
  3572. revision (`str`, *optional*):
  3573. The git revision to commit from. Defaults to the head of the `"main"` branch.
  3574. formatted (`bool`):
  3575. Whether to return the HTML-formatted title and description of the commits. Defaults to False.
  3576. Example:
  3577. ```py
  3578. >>> from huggingface_hub import HfApi
  3579. >>> api = HfApi()
  3580. # Commits are sorted by date (last commit first)
  3581. >>> initial_commit = api.list_repo_commits("gpt2")[-1]
  3582. # Initial commit is always a system commit containing the `.gitattributes` file.
  3583. >>> initial_commit
  3584. GitCommitInfo(
  3585. commit_id='9b865efde13a30c13e0a33e536cf3e4a5a9d71d8',
  3586. authors=['system'],
  3587. created_at=datetime.datetime(2019, 2, 18, 10, 36, 15, tzinfo=datetime.timezone.utc),
  3588. title='initial commit',
  3589. message='',
  3590. formatted_title=None,
  3591. formatted_message=None
  3592. )
  3593. # Create an empty branch by deriving from initial commit
  3594. >>> api.create_branch("gpt2", "new_empty_branch", revision=initial_commit.commit_id)
  3595. ```
  3596. Returns:
  3597. list[[`GitCommitInfo`]]: list of objects containing information about the commits for a repo on the Hub.
  3598. Raises:
  3599. [`~utils.RepositoryNotFoundError`]:
  3600. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  3601. does not exist.
  3602. [`~utils.RevisionNotFoundError`]:
  3603. If revision is not found (error 404) on the repo.
  3604. """
  3605. repo_type = repo_type or constants.REPO_TYPE_MODEL
  3606. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  3607. # Paginate over results and return the list of commits.
  3608. return [
  3609. GitCommitInfo(
  3610. commit_id=item["id"],
  3611. authors=[author["user"] for author in item["authors"]],
  3612. created_at=parse_datetime(item["date"]),
  3613. title=item["title"],
  3614. message=item["message"],
  3615. formatted_title=item.get("formatted", {}).get("title"),
  3616. formatted_message=item.get("formatted", {}).get("message"),
  3617. )
  3618. for item in paginate(
  3619. f"{self.endpoint}/api/{repo_type}s/{repo_id}/commits/{revision}",
  3620. headers=self._build_hf_headers(token=token),
  3621. params={"expand[]": "formatted"} if formatted else {},
  3622. )
  3623. ]
  3624. @validate_hf_hub_args
  3625. def get_paths_info(
  3626. self,
  3627. repo_id: str,
  3628. paths: list[str] | str,
  3629. *,
  3630. expand: bool = False,
  3631. revision: str | None = None,
  3632. repo_type: str | None = None,
  3633. token: str | bool | None = None,
  3634. ) -> list[RepoFile | RepoFolder]:
  3635. """
  3636. Get information about a repo's paths.
  3637. Args:
  3638. repo_id (`str`):
  3639. A namespace (user or an organization) and a repo name separated by a `/`.
  3640. paths (`Union[list[str], str]`, *optional*):
  3641. The paths to get information about. If a path do not exist, it is ignored without raising
  3642. an exception.
  3643. expand (`bool`, *optional*, defaults to `False`):
  3644. Whether to fetch more information about the paths (e.g. last commit and files' security scan results). This
  3645. operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
  3646. As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
  3647. takes to get the results.
  3648. revision (`str`, *optional*):
  3649. The revision of the repository from which to get the information. Defaults to `"main"` branch.
  3650. repo_type (`str`, *optional*):
  3651. The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`.
  3652. Defaults to `"model"`.
  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. Returns:
  3659. `list[Union[RepoFile, RepoFolder]]`:
  3660. The information about the paths, as a list of [`RepoFile`] and [`RepoFolder`] objects.
  3661. Raises:
  3662. [`~utils.RepositoryNotFoundError`]:
  3663. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  3664. does not exist.
  3665. [`~utils.RevisionNotFoundError`]:
  3666. If revision is not found (error 404) on the repo.
  3667. Example:
  3668. ```py
  3669. >>> from huggingface_hub import get_paths_info
  3670. >>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset")
  3671. >>> paths_info
  3672. [
  3673. RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None),
  3674. RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None)
  3675. ]
  3676. ```
  3677. """
  3678. repo_type = repo_type or constants.REPO_TYPE_MODEL
  3679. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  3680. headers = self._build_hf_headers(token=token)
  3681. response = get_session().post(
  3682. f"{self.endpoint}/api/{repo_type}s/{repo_id}/paths-info/{revision}",
  3683. data={
  3684. "paths": paths if isinstance(paths, list) else [paths],
  3685. "expand": expand,
  3686. },
  3687. headers=headers,
  3688. )
  3689. hf_raise_for_status(response)
  3690. paths_info = response.json()
  3691. return [
  3692. RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info)
  3693. for path_info in paths_info
  3694. ]
  3695. @validate_hf_hub_args
  3696. def super_squash_history(
  3697. self,
  3698. repo_id: str,
  3699. *,
  3700. branch: str | None = None,
  3701. commit_message: str | None = None,
  3702. repo_type: str | None = None,
  3703. token: str | bool | None = None,
  3704. ) -> None:
  3705. """Squash commit history on a branch for a repo on the Hub.
  3706. Squashing the repo history is useful when you know you'll make hundreds of commits and you don't want to
  3707. clutter the history. Squashing commits can only be performed from the head of a branch.
  3708. > [!WARNING]
  3709. > Once squashed, the commit history cannot be retrieved. This is a non-revertible operation.
  3710. > [!WARNING]
  3711. > Once the history of a branch has been squashed, it is not possible to merge it back into another branch since
  3712. > their history will have diverged.
  3713. Args:
  3714. repo_id (`str`):
  3715. A namespace (user or an organization) and a repo name separated by a `/`.
  3716. branch (`str`, *optional*):
  3717. The branch to squash. Defaults to the head of the `"main"` branch.
  3718. commit_message (`str`, *optional*):
  3719. The commit message to use for the squashed commit.
  3720. repo_type (`str`, *optional*):
  3721. Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
  3722. listing from a model. Default is `None`.
  3723. token (`bool` or `str`, *optional*):
  3724. A valid user access token (string). Defaults to the locally saved
  3725. token, which is the recommended method for authentication (see
  3726. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3727. To disable authentication, pass `False`.
  3728. Raises:
  3729. [`~utils.RepositoryNotFoundError`]:
  3730. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  3731. does not exist.
  3732. [`~utils.RevisionNotFoundError`]:
  3733. If the branch to squash cannot be found.
  3734. [`~utils.BadRequestError`]:
  3735. If invalid reference for a branch. You cannot squash history on tags.
  3736. Example:
  3737. ```py
  3738. >>> from huggingface_hub import HfApi
  3739. >>> api = HfApi()
  3740. # Create repo
  3741. >>> repo_id = api.create_repo("test-squash").repo_id
  3742. # Make a lot of commits.
  3743. >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content")
  3744. >>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content")
  3745. >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content")
  3746. # Squash history
  3747. >>> api.super_squash_history(repo_id=repo_id)
  3748. ```
  3749. """
  3750. if repo_type is None:
  3751. repo_type = constants.REPO_TYPE_MODEL
  3752. if repo_type not in constants.REPO_TYPES:
  3753. raise ValueError("Invalid repo type")
  3754. if branch is None:
  3755. branch = constants.DEFAULT_REVISION
  3756. # Prepare request
  3757. url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/super-squash/{quote(branch, safe='')}"
  3758. headers = self._build_hf_headers(token=token)
  3759. commit_message = commit_message or f"Super-squash branch '{branch}' using huggingface_hub"
  3760. # Super-squash
  3761. response = get_session().post(url=url, headers=headers, json={"message": commit_message})
  3762. hf_raise_for_status(response)
  3763. @validate_hf_hub_args
  3764. def list_lfs_files(
  3765. self,
  3766. repo_id: str,
  3767. *,
  3768. repo_type: str | None = None,
  3769. token: bool | str | None = None,
  3770. ) -> Iterable[LFSFileInfo]:
  3771. """
  3772. List all LFS files in a repo on the Hub.
  3773. This is primarily useful to count how much storage a repo is using and to eventually clean up large files
  3774. with [`permanently_delete_lfs_files`]. Note that this would be a permanent action that will affect all commits
  3775. referencing this deleted files and that cannot be undone.
  3776. Args:
  3777. repo_id (`str`):
  3778. The repository for which you are listing LFS files.
  3779. repo_type (`str`, *optional*):
  3780. Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or
  3781. `"model"` if listing from a model. Default is `None`.
  3782. token (`bool` or `str`, *optional*):
  3783. A valid user access token (string). Defaults to the locally saved
  3784. token, which is the recommended method for authentication (see
  3785. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3786. To disable authentication, pass `False`.
  3787. Returns:
  3788. `Iterable[LFSFileInfo]`: An iterator of [`LFSFileInfo`] objects.
  3789. Example:
  3790. ```py
  3791. >>> from huggingface_hub import HfApi
  3792. >>> api = HfApi()
  3793. >>> lfs_files = api.list_lfs_files("username/my-cool-repo")
  3794. # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
  3795. # e.g. select only LFS files in the "checkpoints" folder
  3796. >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
  3797. # Permanently delete LFS files
  3798. >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
  3799. ```
  3800. """
  3801. # Prepare request
  3802. if repo_type is None:
  3803. repo_type = constants.REPO_TYPE_MODEL
  3804. url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/lfs-files"
  3805. headers = self._build_hf_headers(token=token)
  3806. # Paginate over LFS items
  3807. for item in paginate(url, params={}, headers=headers):
  3808. yield LFSFileInfo(**item)
  3809. @validate_hf_hub_args
  3810. def permanently_delete_lfs_files(
  3811. self,
  3812. repo_id: str,
  3813. lfs_files: Iterable[LFSFileInfo],
  3814. *,
  3815. rewrite_history: bool = True,
  3816. repo_type: str | None = None,
  3817. token: bool | str | None = None,
  3818. ) -> None:
  3819. """
  3820. Permanently delete LFS files from a repo on the Hub.
  3821. > [!WARNING]
  3822. > This is a permanent action that will affect all commits referencing the deleted files and might corrupt your
  3823. > repository. This is a non-revertible operation. Use it only if you know what you are doing.
  3824. Args:
  3825. repo_id (`str`):
  3826. The repository for which you are listing LFS files.
  3827. lfs_files (`Iterable[LFSFileInfo]`):
  3828. An iterable of [`LFSFileInfo`] items to permanently delete from the repo. Use [`list_lfs_files`] to list
  3829. all LFS files from a repo.
  3830. rewrite_history (`bool`, *optional*, default to `True`):
  3831. Whether to rewrite repository history to remove file pointers referencing the deleted LFS files (recommended).
  3832. repo_type (`str`, *optional*):
  3833. Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or
  3834. `"model"` if listing from a model. Default is `None`.
  3835. token (`bool` or `str`, *optional*):
  3836. A valid user access token (string). Defaults to the locally saved
  3837. token, which is the recommended method for authentication (see
  3838. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3839. To disable authentication, pass `False`.
  3840. Example:
  3841. ```py
  3842. >>> from huggingface_hub import HfApi
  3843. >>> api = HfApi()
  3844. >>> lfs_files = api.list_lfs_files("username/my-cool-repo")
  3845. # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
  3846. # e.g. select only LFS files in the "checkpoints" folder
  3847. >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
  3848. # Permanently delete LFS files
  3849. >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
  3850. ```
  3851. """
  3852. # Prepare request
  3853. if repo_type is None:
  3854. repo_type = constants.REPO_TYPE_MODEL
  3855. url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/lfs-files/batch"
  3856. headers = self._build_hf_headers(token=token)
  3857. # Delete LFS items by batches of 1000
  3858. for batch in chunk_iterable(lfs_files, 1000):
  3859. shas = [item.file_oid for item in batch]
  3860. if len(shas) == 0:
  3861. return
  3862. payload = {
  3863. "deletions": {
  3864. "sha": shas,
  3865. "rewriteHistory": rewrite_history,
  3866. }
  3867. }
  3868. response = get_session().post(url, headers=headers, json=payload)
  3869. hf_raise_for_status(response)
  3870. @_deprecate_arguments(
  3871. version="2.0",
  3872. deprecated_args={"space_storage"},
  3873. custom_message="Use `space_volumes` to mount volumes on a Space.",
  3874. )
  3875. @validate_hf_hub_args
  3876. def create_repo(
  3877. self,
  3878. repo_id: str,
  3879. *,
  3880. token: str | bool | None = None,
  3881. private: bool | None = None,
  3882. visibility: RepoVisibility_T | None = None,
  3883. repo_type: str | None = None,
  3884. exist_ok: bool = False,
  3885. resource_group_id: str | None = None,
  3886. space_sdk: str | None = None,
  3887. space_hardware: SpaceHardware | None = None,
  3888. space_storage: SpaceStorage | None = None,
  3889. space_sleep_time: int | None = None,
  3890. space_secrets: list[dict[str, str]] | None = None,
  3891. space_variables: list[dict[str, str]] | None = None,
  3892. space_volumes: list[Volume] | None = None,
  3893. ) -> RepoUrl:
  3894. """Create an empty repo on the HuggingFace Hub.
  3895. Args:
  3896. repo_id (`str`):
  3897. A namespace (user or an organization) and a repo name separated
  3898. by a `/`.
  3899. token (`bool` or `str`, *optional*):
  3900. A valid user access token (string). Defaults to the locally saved
  3901. token, which is the recommended method for authentication (see
  3902. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3903. To disable authentication, pass `False`.
  3904. private (`bool`, *optional*):
  3905. 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. Cannot be passed together with `visibility`.
  3906. visibility (`Literal["public", "private", "protected"]`, *optional*):
  3907. Visibility of the repo. Can be `"public"` or `"private"`, or `"protected"` for Spaces. If `None`
  3908. (default), the repo will be public unless the organization's default is private. This value is ignored
  3909. if the repo already exists.
  3910. repo_type (`str`, *optional*):
  3911. Set to `"dataset"` or `"space"` if uploading to a dataset or
  3912. space, `None` or `"model"` if uploading to a model. Default is
  3913. `None`.
  3914. exist_ok (`bool`, *optional*, defaults to `False`):
  3915. If `True`, do not raise an error if repo already exists.
  3916. resource_group_id (`str`, *optional*):
  3917. Resource group in which to create the repo. Resource groups is only available for Enterprise Hub organizations and
  3918. allow to define which members of the organization can access the resource. The ID of a resource group
  3919. can be found in the URL of the resource's page on the Hub (e.g. `"66670e5163145ca562cb1988"`).
  3920. To learn more about resource groups, see https://huggingface.co/docs/hub/en/security-resource-groups.
  3921. space_sdk (`str`, *optional*):
  3922. Choice of SDK to use if repo_type is "space". Can be "streamlit", "gradio", "docker", or "static".
  3923. space_hardware (`SpaceHardware` or `str`, *optional*):
  3924. Choice of Hardware if repo_type is "space". See [`SpaceHardware`] for a complete list.
  3925. space_storage (`SpaceStorage` or `str`, *optional*):
  3926. <Deprecated, use `set_space_volumes` instead> Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
  3927. space_sleep_time (`int`, *optional*):
  3928. Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
  3929. your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
  3930. the sleep time (value is fixed to 48 hours of inactivity).
  3931. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  3932. space_secrets (`list[dict[str, str]]`, *optional*):
  3933. A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
  3934. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  3935. space_variables (`list[dict[str, str]]`, *optional*):
  3936. A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
  3937. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
  3938. space_volumes (`list[Volume]`, *optional*):
  3939. A list of [`Volume`] objects to mount in the Space at creation time. Each volume has a `type`
  3940. (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), a `source` (repo or bucket ID), a `mount_path`
  3941. (path inside the container), and optional `revision`, `read_only`, and `path` fields.
  3942. Only applicable if repo_type is "space".
  3943. Returns:
  3944. [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
  3945. attributes like `endpoint`, `repo_type` and `repo_id`.
  3946. """
  3947. organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id)
  3948. path = f"{self.endpoint}/api/repos/create"
  3949. if repo_type not in constants.REPO_TYPES_WITH_KERNEL:
  3950. raise ValueError("Invalid repo type")
  3951. resolved_visibility = _resolve_repo_visibility(private=private, visibility=visibility, repo_type=repo_type)
  3952. payload: dict[str, Any] = {"name": name, "organization": organization}
  3953. if resolved_visibility is not None:
  3954. payload["visibility"] = resolved_visibility
  3955. if repo_type is not None:
  3956. payload["type"] = repo_type
  3957. if repo_type == "space":
  3958. if space_sdk is None:
  3959. raise ValueError(
  3960. "No space_sdk provided. `create_repo` expects space_sdk to be one"
  3961. f" of {constants.SPACES_SDK_TYPES} when repo_type is 'space'`"
  3962. )
  3963. if space_sdk not in constants.SPACES_SDK_TYPES:
  3964. raise ValueError(f"Invalid space_sdk. Please choose one of {constants.SPACES_SDK_TYPES}.")
  3965. payload["sdk"] = space_sdk
  3966. if space_sdk is not None and repo_type != "space":
  3967. warnings.warn("Ignoring provided space_sdk because repo_type is not 'space'.")
  3968. space_args: list[tuple[str, str, Any]] = [
  3969. # input arg, payload key, value
  3970. ("space_hardware", "hardware", space_hardware),
  3971. ("space_storage", "storageTier", space_storage),
  3972. ("space_sleep_time", "sleepTimeSeconds", space_sleep_time),
  3973. ("space_secrets", "secrets", space_secrets),
  3974. ("space_variables", "variables", space_variables),
  3975. ("space_volumes", "volumes", [v.to_dict() for v in space_volumes] if space_volumes else None),
  3976. ]
  3977. if repo_type == constants.REPO_TYPE_SPACE:
  3978. for _, key, value in space_args:
  3979. if value is not None:
  3980. payload[key] = value
  3981. if space_sleep_time is not None and space_hardware == SpaceHardware.CPU_BASIC:
  3982. warnings.warn(
  3983. "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
  3984. " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
  3985. " you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
  3986. UserWarning,
  3987. )
  3988. else:
  3989. if provided_space_args := [arg for arg, _, value in space_args if value is not None]:
  3990. warnings.warn(f"Ignoring provided {', '.join(provided_space_args)} because repo_type is not 'space'.")
  3991. if resource_group_id is not None:
  3992. payload["resourceGroupId"] = resource_group_id
  3993. headers = self._build_hf_headers(token=token)
  3994. while True:
  3995. r = get_session().post(path, headers=headers, json=payload)
  3996. if r.status_code == 409 and "Cannot create repo: another conflicting operation is in progress" in r.text:
  3997. # Since https://github.com/huggingface/moon-landing/pull/7272 (private repo), it is not possible to
  3998. # concurrently create repos on the Hub for a same user. This is rarely an issue, except when running
  3999. # tests. To avoid any inconvenience, we retry to create the repo for this specific error.
  4000. # NOTE: This could have being fixed directly in the tests but adding it here should fixed CIs for all
  4001. # dependent libraries.
  4002. # NOTE: If a fix is implemented server-side, we should be able to remove this retry mechanism.
  4003. logger.debug("Create repo failed due to a concurrency issue. Retrying...")
  4004. continue
  4005. break
  4006. try:
  4007. hf_raise_for_status(r)
  4008. except HfHubHTTPError as err:
  4009. if exist_ok and err.response.status_code == 409:
  4010. # Repo already exists and `exist_ok=True`
  4011. pass
  4012. elif exist_ok and err.response.status_code == 403:
  4013. # No write permission on the namespace but repo might already exist
  4014. try:
  4015. self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token)
  4016. if repo_type is None or repo_type == constants.REPO_TYPE_MODEL:
  4017. return RepoUrl(f"{self.endpoint}/{repo_id}")
  4018. return RepoUrl(f"{self.endpoint}/{constants.REPO_TYPES_URL_PREFIXES[repo_type]}{repo_id}")
  4019. except HfHubHTTPError:
  4020. raise err
  4021. else:
  4022. raise
  4023. d = r.json()
  4024. return RepoUrl(d["url"], endpoint=self.endpoint)
  4025. @validate_hf_hub_args
  4026. def delete_repo(
  4027. self,
  4028. repo_id: str,
  4029. *,
  4030. token: str | bool | None = None,
  4031. repo_type: str | None = None,
  4032. missing_ok: bool = False,
  4033. ) -> None:
  4034. """
  4035. Delete a repo from the HuggingFace Hub. CAUTION: this is irreversible.
  4036. Args:
  4037. repo_id (`str`):
  4038. A namespace (user or an organization) and a repo name separated
  4039. by a `/`.
  4040. token (`bool` or `str`, *optional*):
  4041. A valid user access token (string). Defaults to the locally saved
  4042. token, which is the recommended method for authentication (see
  4043. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4044. To disable authentication, pass `False`.
  4045. repo_type (`str`, *optional*):
  4046. Set to `"dataset"` or `"space"` if uploading to a dataset or
  4047. space, `None` or `"model"` if uploading to a model.
  4048. missing_ok (`bool`, *optional*, defaults to `False`):
  4049. If `True`, do not raise an error if repo does not exist.
  4050. Raises:
  4051. [`~utils.RepositoryNotFoundError`]
  4052. If the repository to delete from cannot be found and `missing_ok` is set to False (default).
  4053. """
  4054. organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id)
  4055. path = f"{self.endpoint}/api/repos/delete"
  4056. if repo_type not in constants.REPO_TYPES_WITH_KERNEL:
  4057. raise ValueError("Invalid repo type")
  4058. json = {"name": name, "organization": organization}
  4059. if repo_type is not None:
  4060. json["type"] = repo_type
  4061. headers = self._build_hf_headers(token=token)
  4062. r = get_session().request("DELETE", path, headers=headers, json=json)
  4063. reset_xet_connection_info_cache_for_repo(repo_type, repo_id)
  4064. try:
  4065. hf_raise_for_status(r)
  4066. except RepositoryNotFoundError:
  4067. if not missing_ok:
  4068. raise
  4069. @validate_hf_hub_args
  4070. def update_repo_settings(
  4071. self,
  4072. repo_id: str,
  4073. *,
  4074. gated: Literal["auto", "manual", False] | None = None,
  4075. private: bool | None = None,
  4076. visibility: RepoVisibility_T | None = None,
  4077. token: str | bool | None = None,
  4078. repo_type: str | None = None,
  4079. ) -> None:
  4080. """
  4081. Update the settings of a repository, including gated access and visibility.
  4082. To give more control over how repos are used, the Hub allows repo authors to enable
  4083. access requests for their repos, and also to change the visibility of the repo.
  4084. Args:
  4085. repo_id (`str`):
  4086. A namespace (user or an organization) and a repo name separated by a /.
  4087. gated (`Literal["auto", "manual", False]`, *optional*):
  4088. The gated status for the repository. If set to `None` (default), the `gated` setting of the repository won't be updated.
  4089. * "auto": The repository is gated, and access requests are automatically approved or denied based on predefined criteria.
  4090. * "manual": The repository is gated, and access requests require manual approval.
  4091. * False : The repository is not gated, and anyone can access it.
  4092. private (`bool`, *optional*):
  4093. Whether the repository should be private. Cannot be passed together with `visibility`.
  4094. visibility (`Literal["public", "private", "protected"]`, *optional*):
  4095. Visibility of the repository. Can be `"public"` or `"private"`, or `"protected"` for Spaces.
  4096. token (`Union[str, bool, None]`, *optional*):
  4097. A valid user access token (string). Defaults to the locally saved token,
  4098. which is the recommended method for authentication (see
  4099. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4100. To disable authentication, pass False.
  4101. repo_type (`str`, *optional*):
  4102. The type of the repository to update settings from (`"model"`, `"dataset"` or `"space"`).
  4103. Defaults to `"model"`.
  4104. Raises:
  4105. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4106. If gated is not one of "auto", "manual", or False.
  4107. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4108. If repo_type is not one of the values in constants.REPO_TYPES.
  4109. [`~utils.HfHubHTTPError`]:
  4110. If the request to the Hugging Face Hub API fails.
  4111. [`~utils.RepositoryNotFoundError`]
  4112. If the repository to download from cannot be found. This may be because it doesn't exist,
  4113. or because it is set to `private` and you do not have access.
  4114. """
  4115. if repo_type not in constants.REPO_TYPES:
  4116. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  4117. if repo_type is None:
  4118. repo_type = constants.REPO_TYPE_MODEL # default repo type
  4119. resolved_visibility = _resolve_repo_visibility(private=private, visibility=visibility, repo_type=repo_type)
  4120. # Prepare the JSON payload for the PUT request
  4121. payload: dict = {}
  4122. if gated is not None:
  4123. if gated not in ["auto", "manual", False]:
  4124. raise ValueError(f"Invalid gated status, must be one of 'auto', 'manual', or False. Got '{gated}'.")
  4125. payload["gated"] = gated
  4126. if resolved_visibility is not None:
  4127. payload["visibility"] = resolved_visibility
  4128. if len(payload) == 0:
  4129. raise ValueError("At least one setting must be updated.")
  4130. # Build headers
  4131. headers = self._build_hf_headers(token=token)
  4132. r = get_session().put(
  4133. url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/settings",
  4134. headers=headers,
  4135. json=payload,
  4136. )
  4137. hf_raise_for_status(r)
  4138. def move_repo(
  4139. self,
  4140. from_id: str,
  4141. to_id: str,
  4142. *,
  4143. repo_type: str | None = None,
  4144. token: str | bool | None = None,
  4145. ):
  4146. """
  4147. Moving a repository from namespace1/repo_name1 to namespace2/repo_name2
  4148. Note there are certain limitations. For more information about moving
  4149. repositories, please see
  4150. https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.
  4151. Args:
  4152. from_id (`str`):
  4153. A namespace (user or an organization) and a repo name separated
  4154. by a `/`. Original repository identifier.
  4155. to_id (`str`):
  4156. A namespace (user or an organization) and a repo name separated
  4157. by a `/`. Final repository identifier.
  4158. repo_type (`str`, *optional*):
  4159. Set to `"dataset"` or `"space"` if uploading to a dataset or
  4160. space, `None` or `"model"` if uploading to a model. Default is
  4161. `None`.
  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. > [!TIP]
  4168. > Raises the following errors:
  4169. >
  4170. > - [`~utils.RepositoryNotFoundError`]
  4171. > If the repository to download from cannot be found. This may be because it doesn't exist,
  4172. > or because it is set to `private` and you do not have access.
  4173. """
  4174. if len(from_id.split("/")) != 2:
  4175. raise ValueError(f"Invalid repo_id: {from_id}. It should have a namespace (:namespace:/:repo_name:)")
  4176. if len(to_id.split("/")) != 2:
  4177. raise ValueError(f"Invalid repo_id: {to_id}. It should have a namespace (:namespace:/:repo_name:)")
  4178. if repo_type is None:
  4179. repo_type = constants.REPO_TYPE_MODEL # Hub won't accept `None`.
  4180. json = {"fromRepo": from_id, "toRepo": to_id, "type": repo_type}
  4181. path = f"{self.endpoint}/api/repos/move"
  4182. headers = self._build_hf_headers(token=token)
  4183. r = get_session().post(path, headers=headers, json=json)
  4184. try:
  4185. hf_raise_for_status(r)
  4186. except HfHubHTTPError as e:
  4187. e.append_to_message(
  4188. "\nFor additional documentation please see"
  4189. " https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo."
  4190. )
  4191. raise
  4192. @overload
  4193. def create_commit( # type: ignore
  4194. self,
  4195. repo_id: str,
  4196. operations: Iterable[CommitOperation],
  4197. *,
  4198. commit_message: str,
  4199. commit_description: str | None = None,
  4200. token: str | bool | None = None,
  4201. repo_type: str | None = None,
  4202. revision: str | None = None,
  4203. create_pr: bool | None = None,
  4204. num_threads: int = 5,
  4205. parent_commit: str | None = None,
  4206. run_as_future: Literal[False] = ...,
  4207. _hot_reload: bool | None = None,
  4208. ) -> CommitInfo: ...
  4209. @overload
  4210. def create_commit(
  4211. self,
  4212. repo_id: str,
  4213. operations: Iterable[CommitOperation],
  4214. *,
  4215. commit_message: str,
  4216. commit_description: str | None = None,
  4217. token: str | bool | None = None,
  4218. repo_type: str | None = None,
  4219. revision: str | None = None,
  4220. create_pr: bool | None = None,
  4221. num_threads: int = 5,
  4222. parent_commit: str | None = None,
  4223. run_as_future: Literal[True] = ...,
  4224. _hot_reload: bool | None = None,
  4225. ) -> Future[CommitInfo]: ...
  4226. @validate_hf_hub_args
  4227. @future_compatible
  4228. def create_commit(
  4229. self,
  4230. repo_id: str,
  4231. operations: Iterable[CommitOperation],
  4232. *,
  4233. commit_message: str,
  4234. commit_description: str | None = None,
  4235. token: str | bool | None = None,
  4236. repo_type: str | None = None,
  4237. revision: str | None = None,
  4238. create_pr: bool | None = None,
  4239. num_threads: int = 5,
  4240. parent_commit: str | None = None,
  4241. run_as_future: bool = False,
  4242. _hot_reload: bool | None = None,
  4243. ) -> CommitInfo | Future[CommitInfo]:
  4244. """
  4245. Creates a commit in the given repo, deleting & uploading files as needed.
  4246. > [!WARNING]
  4247. > The input list of `CommitOperation` will be mutated during the commit process. Do not reuse the same objects
  4248. > for multiple commits.
  4249. > [!WARNING]
  4250. > `create_commit` assumes that the repo already exists on the Hub. If you get a
  4251. > Client error 404, please make sure you are authenticated, that your token has the required permissions,
  4252. > and that `repo_id` and `repo_type` are set correctly. If repo does not exist,
  4253. > create it first using [`~hf_api.create_repo`].
  4254. > [!WARNING]
  4255. > `create_commit` is limited to 25k LFS files and a 1GB payload for regular files.
  4256. Args:
  4257. repo_id (`str`):
  4258. The repository in which the commit will be created, for example:
  4259. `"username/custom_transformers"`
  4260. operations (`Iterable` of [`~hf_api.CommitOperation`]):
  4261. An iterable of operations to include in the commit, either:
  4262. - [`~hf_api.CommitOperationAdd`] to upload a file
  4263. - [`~hf_api.CommitOperationDelete`] to delete a file
  4264. - [`~hf_api.CommitOperationCopy`] to copy a file
  4265. Operation objects will be mutated to include information relative to the upload. Do not reuse the
  4266. same objects for multiple commits.
  4267. commit_message (`str`):
  4268. The summary (first line) of the commit that will be created.
  4269. commit_description (`str`, *optional*):
  4270. The description of the commit that will be created
  4271. token (`bool` or `str`, *optional*):
  4272. A valid user access token (string). Defaults to the locally saved
  4273. token, which is the recommended method for authentication (see
  4274. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4275. To disable authentication, pass `False`.
  4276. repo_type (`str`, *optional*):
  4277. Set to `"dataset"` or `"space"` if uploading to a dataset or
  4278. space, `None` or `"model"` if uploading to a model. Default is
  4279. `None`.
  4280. revision (`str`, *optional*):
  4281. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4282. create_pr (`boolean`, *optional*):
  4283. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  4284. If `revision` is not set, PR is opened against the `"main"` branch. If
  4285. `revision` is set and is a branch, PR is opened against this branch. If
  4286. `revision` is set and is not a branch name (example: a commit oid), an
  4287. `RevisionNotFoundError` is returned by the server.
  4288. num_threads (`int`, *optional*):
  4289. Number of concurrent threads for uploading files. Defaults to 5.
  4290. Setting it to 2 means at most 2 files will be uploaded concurrently.
  4291. parent_commit (`str`, *optional*):
  4292. The OID / SHA of the parent commit, as a hexadecimal string.
  4293. Shorthands (7 first characters) are also supported. If specified and `create_pr` is `False`,
  4294. the commit will fail if `revision` does not point to `parent_commit`. If specified and `create_pr`
  4295. is `True`, the pull request will be created from `parent_commit`. Specifying `parent_commit`
  4296. ensures the repo has not changed before committing the changes, and can be especially useful
  4297. if the repo is updated / committed to concurrently.
  4298. run_as_future (`bool`, *optional*):
  4299. Whether or not to run this method in the background. Background jobs are run sequentially without
  4300. blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
  4301. object. Defaults to `False`.
  4302. Returns:
  4303. [`CommitInfo`] or `Future`:
  4304. Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
  4305. url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
  4306. contain the result when executed.
  4307. Raises:
  4308. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4309. If commit message is empty.
  4310. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4311. If parent commit is not a valid commit OID.
  4312. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4313. If a README.md file with an invalid metadata section is committed. In this case, the commit will fail
  4314. early, before trying to upload any file.
  4315. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4316. If `create_pr` is `True` and revision is neither `None` nor `"main"`.
  4317. [`~utils.RepositoryNotFoundError`]:
  4318. If repository is not found (error 404): wrong repo_id/repo_type, private
  4319. but not authenticated or repo does not exist.
  4320. """
  4321. if parent_commit is not None and not constants.REGEX_COMMIT_OID.fullmatch(parent_commit):
  4322. raise ValueError(
  4323. f"`parent_commit` is not a valid commit OID. It must match the following regex: {constants.REGEX_COMMIT_OID}"
  4324. )
  4325. if commit_message is None or len(commit_message) == 0:
  4326. raise ValueError("`commit_message` can't be empty, please pass a value.")
  4327. commit_description = commit_description if commit_description is not None else ""
  4328. repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL
  4329. if repo_type not in constants.REPO_TYPES:
  4330. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  4331. unquoted_revision = revision or constants.DEFAULT_REVISION
  4332. revision = quote(unquoted_revision, safe="")
  4333. create_pr = create_pr if create_pr is not None else False
  4334. _hot_reload = _hot_reload if _hot_reload is not None else False
  4335. headers = self._build_hf_headers(token=token)
  4336. operations = list(operations)
  4337. additions = [op for op in operations if isinstance(op, CommitOperationAdd)]
  4338. copies = [op for op in operations if isinstance(op, CommitOperationCopy)]
  4339. nb_additions = len(additions)
  4340. nb_copies = len(copies)
  4341. nb_deletions = len(operations) - nb_additions - nb_copies
  4342. for addition in additions:
  4343. if addition._is_committed:
  4344. raise ValueError(
  4345. f"CommitOperationAdd {addition} has already being committed and cannot be reused. Please create a"
  4346. " new CommitOperationAdd object if you want to create a new commit."
  4347. )
  4348. if repo_type != "dataset":
  4349. for addition in additions:
  4350. if addition.path_in_repo.endswith((".arrow", ".parquet")):
  4351. warnings.warn(
  4352. f"It seems that you are about to commit a data file ({addition.path_in_repo}) to a {repo_type}"
  4353. " repository. You are sure this is intended? If you are trying to upload a dataset, please"
  4354. " set `repo_type='dataset'` or `--repo-type=dataset` in a CLI."
  4355. )
  4356. logger.debug(
  4357. f"About to commit to the hub: {len(additions)} addition(s), {len(copies)} copie(s) and"
  4358. f" {nb_deletions} deletion(s)."
  4359. )
  4360. # If updating a README.md file, make sure the metadata format is valid
  4361. # It's better to fail early than to fail after all the files have been uploaded.
  4362. for addition in additions:
  4363. if addition.path_in_repo == "README.md":
  4364. with addition.as_file() as file:
  4365. content = file.read().decode()
  4366. self._validate_yaml(content, repo_type=repo_type, token=token)
  4367. # Skip other additions after `README.md` has been processed
  4368. break
  4369. # If updating twice the same file or update then delete a file in a single commit
  4370. _warn_on_overwriting_operations(operations)
  4371. self.preupload_lfs_files(
  4372. repo_id=repo_id,
  4373. additions=additions,
  4374. token=token,
  4375. repo_type=repo_type,
  4376. revision=unquoted_revision, # first-class methods take unquoted revision
  4377. create_pr=create_pr,
  4378. num_threads=num_threads,
  4379. free_memory=False, # do not remove `CommitOperationAdd.path_or_fileobj` on LFS files for "normal" users
  4380. )
  4381. files_to_copy = _fetch_files_to_copy(
  4382. copies=copies,
  4383. repo_type=repo_type,
  4384. repo_id=repo_id,
  4385. headers=headers,
  4386. revision=unquoted_revision,
  4387. endpoint=self.endpoint,
  4388. )
  4389. # Remove no-op operations (files that have not changed)
  4390. operations_without_no_op = []
  4391. for operation in operations:
  4392. if (
  4393. isinstance(operation, CommitOperationAdd)
  4394. and operation._remote_oid is not None
  4395. and operation._remote_oid == operation._local_oid
  4396. ):
  4397. # File already exists on the Hub and has not changed: we can skip it.
  4398. logger.debug(f"Skipping upload for '{operation.path_in_repo}' as the file has not changed.")
  4399. continue
  4400. if (
  4401. isinstance(operation, CommitOperationCopy)
  4402. and operation._dest_oid is not None
  4403. and operation._dest_oid == operation._src_oid
  4404. ):
  4405. # Source and destination files are identical - skip
  4406. logger.debug(
  4407. 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."
  4408. )
  4409. continue
  4410. operations_without_no_op.append(operation)
  4411. if len(operations) != len(operations_without_no_op):
  4412. logger.info(
  4413. f"Removing {len(operations) - len(operations_without_no_op)} file(s) from commit that have not changed."
  4414. )
  4415. # Return early if empty commit
  4416. if len(operations_without_no_op) == 0:
  4417. logger.warning("No files have been modified since last commit. Skipping to prevent empty commit.")
  4418. # Get latest commit info
  4419. try:
  4420. info = self.repo_info(repo_id=repo_id, repo_type=repo_type, revision=unquoted_revision, token=token)
  4421. except RepositoryNotFoundError as e:
  4422. e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE)
  4423. raise
  4424. # Return commit info based on latest commit
  4425. url_prefix = self.endpoint
  4426. if repo_type is not None and repo_type != constants.REPO_TYPE_MODEL:
  4427. url_prefix = f"{url_prefix}/{repo_type}s"
  4428. return CommitInfo(
  4429. commit_url=f"{url_prefix}/{repo_id}/commit/{info.sha}",
  4430. commit_message=commit_message,
  4431. commit_description=commit_description,
  4432. oid=info.sha, # type: ignore
  4433. _endpoint=self.endpoint,
  4434. )
  4435. commit_payload = _prepare_commit_payload(
  4436. operations=operations,
  4437. files_to_copy=files_to_copy,
  4438. commit_message=commit_message,
  4439. commit_description=commit_description,
  4440. parent_commit=parent_commit,
  4441. )
  4442. commit_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/commit/{revision}"
  4443. def _payload_as_ndjson() -> Iterable[bytes]:
  4444. for item in commit_payload:
  4445. yield json.dumps(item).encode()
  4446. yield b"\n"
  4447. headers = {
  4448. # See https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
  4449. "Content-Type": "application/x-ndjson",
  4450. **headers,
  4451. }
  4452. data = b"".join(_payload_as_ndjson())
  4453. params: dict[str, Any] = {}
  4454. if create_pr:
  4455. params["create_pr"] = "1"
  4456. if _hot_reload:
  4457. params["hot_reload"] = "1"
  4458. try:
  4459. commit_resp = get_session().post(url=commit_url, headers=headers, content=data, params=params)
  4460. hf_raise_for_status(commit_resp, endpoint_name="commit")
  4461. except RepositoryNotFoundError as e:
  4462. e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE)
  4463. raise
  4464. except RemoteEntryNotFoundError as e:
  4465. if nb_deletions > 0 and "A file with this name doesn't exist" in str(e):
  4466. e.append_to_message(
  4467. "\nMake sure to differentiate file and folder paths in delete"
  4468. " operations with a trailing '/' or using `is_folder=True/False`."
  4469. )
  4470. raise
  4471. # Mark additions as committed (cannot be reused in another commit)
  4472. for addition in additions:
  4473. addition._is_committed = True
  4474. commit_data = commit_resp.json()
  4475. return CommitInfo(
  4476. commit_url=commit_data["commitUrl"],
  4477. commit_message=commit_message,
  4478. commit_description=commit_description,
  4479. oid=commit_data["commitOid"],
  4480. pr_url=commit_data["pullRequestUrl"] if create_pr else None,
  4481. _endpoint=self.endpoint,
  4482. )
  4483. def preupload_lfs_files(
  4484. self,
  4485. repo_id: str,
  4486. additions: Iterable[CommitOperationAdd],
  4487. *,
  4488. token: str | bool | None = None,
  4489. repo_type: str | None = None,
  4490. revision: str | None = None,
  4491. create_pr: bool | None = None,
  4492. num_threads: int = 5,
  4493. free_memory: bool = True,
  4494. gitignore_content: str | None = None,
  4495. ):
  4496. """Pre-upload LFS files to S3 in preparation on a future commit.
  4497. This method is useful if you are generating the files to upload on-the-fly and you don't want to store them
  4498. in memory before uploading them all at once.
  4499. > [!WARNING]
  4500. > This is a power-user method. You shouldn't need to call it directly to make a normal commit.
  4501. > Use [`create_commit`] directly instead.
  4502. > [!WARNING]
  4503. > Commit operations will be mutated during the process. In particular, the attached `path_or_fileobj` will be
  4504. > removed after the upload to save memory (and replaced by an empty `bytes` object). Do not reuse the same
  4505. > objects except to pass them to [`create_commit`]. If you don't want to remove the attached content from the
  4506. > commit operation object, pass `free_memory=False`.
  4507. Args:
  4508. repo_id (`str`):
  4509. The repository in which you will commit the files, for example: `"username/custom_transformers"`.
  4510. operations (`Iterable` of [`CommitOperationAdd`]):
  4511. The list of files to upload. Warning: the objects in this list will be mutated to include information
  4512. relative to the upload. Do not reuse the same objects for multiple commits.
  4513. token (`bool` or `str`, *optional*):
  4514. A valid user access token (string). Defaults to the locally saved
  4515. token, which is the recommended method for authentication (see
  4516. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4517. To disable authentication, pass `False`.
  4518. repo_type (`str`, *optional*):
  4519. The type of repository to upload to (e.g. `"model"` -default-, `"dataset"` or `"space"`).
  4520. revision (`str`, *optional*):
  4521. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4522. create_pr (`boolean`, *optional*):
  4523. Whether or not you plan to create a Pull Request with that commit. Defaults to `False`.
  4524. num_threads (`int`, *optional*):
  4525. Number of concurrent threads for uploading files. Defaults to 5.
  4526. Setting it to 2 means at most 2 files will be uploaded concurrently.
  4527. gitignore_content (`str`, *optional*):
  4528. The content of the `.gitignore` file to know which files should be ignored. The order of priority
  4529. is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
  4530. in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
  4531. (if any).
  4532. Example:
  4533. ```py
  4534. >>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo
  4535. >>> repo_id = create_repo("test_preupload").repo_id
  4536. # Generate and preupload LFS files one by one
  4537. >>> operations = [] # List of all `CommitOperationAdd` objects that will be generated
  4538. >>> for i in range(5):
  4539. ... content = ... # generate binary content
  4540. ... addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content)
  4541. ... preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory
  4542. ... operations.append(addition)
  4543. # Create commit
  4544. >>> create_commit(repo_id, operations=operations, commit_message="Commit all shards")
  4545. ```
  4546. """
  4547. repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL
  4548. if repo_type not in constants.REPO_TYPES:
  4549. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  4550. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  4551. create_pr = create_pr if create_pr is not None else False
  4552. headers = self._build_hf_headers(token=token)
  4553. # Check if a `gitignore` file is being committed to the Hub.
  4554. additions = list(additions)
  4555. if gitignore_content is None:
  4556. for addition in additions:
  4557. if addition.path_in_repo == ".gitignore":
  4558. with addition.as_file() as f:
  4559. gitignore_content = f.read().decode()
  4560. break
  4561. # Filter out already uploaded files
  4562. new_additions = [addition for addition in additions if not addition._is_uploaded]
  4563. # Check which new files are LFS
  4564. # For some items, we might have already fetched the upload mode (in case of upload_large_folder)
  4565. additions_no_upload_mode = [addition for addition in new_additions if addition._upload_mode is None]
  4566. if len(additions_no_upload_mode) > 0:
  4567. try:
  4568. _fetch_upload_modes(
  4569. additions=additions_no_upload_mode,
  4570. repo_type=repo_type,
  4571. repo_id=repo_id,
  4572. headers=headers,
  4573. revision=revision,
  4574. endpoint=self.endpoint,
  4575. create_pr=create_pr or False,
  4576. gitignore_content=gitignore_content,
  4577. )
  4578. except RepositoryNotFoundError as e:
  4579. e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE)
  4580. raise
  4581. # Filter out regular files
  4582. new_lfs_additions = [addition for addition in new_additions if addition._upload_mode == "lfs"]
  4583. # Filter out files listed in .gitignore
  4584. new_lfs_additions_to_upload = []
  4585. for addition in new_lfs_additions:
  4586. if addition._should_ignore:
  4587. logger.debug(f"Skipping upload for LFS file '{addition.path_in_repo}' (ignored by gitignore file).")
  4588. else:
  4589. new_lfs_additions_to_upload.append(addition)
  4590. if len(new_lfs_additions) != len(new_lfs_additions_to_upload):
  4591. logger.info(
  4592. f"Skipped upload for {len(new_lfs_additions) - len(new_lfs_additions_to_upload)} LFS file(s) "
  4593. "(ignored by gitignore file)."
  4594. )
  4595. # If no LFS files remain to upload, keep previous behavior and log explicitly
  4596. if len(new_lfs_additions_to_upload) == 0:
  4597. logger.debug("No LFS files to upload.")
  4598. return
  4599. # Prepare upload parameters
  4600. upload_kwargs = {
  4601. "additions": new_lfs_additions_to_upload,
  4602. "repo_type": repo_type,
  4603. "repo_id": repo_id,
  4604. "headers": headers,
  4605. "endpoint": self.endpoint,
  4606. # If `create_pr`, we don't want to check user permission on the revision as users with read permission
  4607. # should still be able to create PRs even if they don't have write permission on the target branch of the
  4608. # PR (i.e. `revision`).
  4609. "revision": revision if not create_pr else None,
  4610. }
  4611. _upload_files(**upload_kwargs, num_threads=num_threads, create_pr=create_pr) # type: ignore [arg-type]
  4612. for addition in new_lfs_additions_to_upload:
  4613. addition._is_uploaded = True
  4614. if free_memory:
  4615. addition.path_or_fileobj = b""
  4616. @overload
  4617. def upload_file( # type: ignore
  4618. self,
  4619. *,
  4620. path_or_fileobj: str | Path | bytes | BinaryIO,
  4621. path_in_repo: str,
  4622. repo_id: str,
  4623. token: str | bool | None = None,
  4624. repo_type: str | None = None,
  4625. revision: str | None = None,
  4626. commit_message: str | None = None,
  4627. commit_description: str | None = None,
  4628. create_pr: bool | None = None,
  4629. parent_commit: str | None = None,
  4630. run_as_future: Literal[False] = ...,
  4631. _hot_reload: bool | None = None,
  4632. ) -> CommitInfo: ...
  4633. @overload
  4634. def upload_file(
  4635. self,
  4636. *,
  4637. path_or_fileobj: str | Path | bytes | BinaryIO,
  4638. path_in_repo: str,
  4639. repo_id: str,
  4640. token: str | bool | None = None,
  4641. repo_type: str | None = None,
  4642. revision: str | None = None,
  4643. commit_message: str | None = None,
  4644. commit_description: str | None = None,
  4645. create_pr: bool | None = None,
  4646. parent_commit: str | None = None,
  4647. run_as_future: Literal[True] = ...,
  4648. _hot_reload: bool | None = None,
  4649. ) -> Future[CommitInfo]: ...
  4650. @validate_hf_hub_args
  4651. @future_compatible
  4652. def upload_file(
  4653. self,
  4654. *,
  4655. path_or_fileobj: str | Path | bytes | BinaryIO,
  4656. path_in_repo: str,
  4657. repo_id: str,
  4658. token: str | bool | None = None,
  4659. repo_type: str | None = None,
  4660. revision: str | None = None,
  4661. commit_message: str | None = None,
  4662. commit_description: str | None = None,
  4663. create_pr: bool | None = None,
  4664. parent_commit: str | None = None,
  4665. run_as_future: bool = False,
  4666. _hot_reload: bool | None = None,
  4667. ) -> CommitInfo | Future[CommitInfo]:
  4668. """
  4669. Upload a local file (up to 50 GB) to the given repo. The upload is done
  4670. through a HTTP post request, and doesn't require git or git-lfs to be
  4671. installed.
  4672. Args:
  4673. path_or_fileobj (`str`, `Path`, `bytes`, or `IO`):
  4674. Path to a file on the local machine or binary data stream /
  4675. fileobj / buffer.
  4676. path_in_repo (`str`):
  4677. Relative filepath in the repo, for example:
  4678. `"checkpoints/1fec34a/weights.bin"`
  4679. repo_id (`str`):
  4680. The repository to which the file will be uploaded, for example:
  4681. `"username/custom_transformers"`
  4682. token (`bool` or `str`, *optional*):
  4683. A valid user access token (string). Defaults to the locally saved
  4684. token, which is the recommended method for authentication (see
  4685. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4686. To disable authentication, pass `False`.
  4687. repo_type (`str`, *optional*):
  4688. Set to `"dataset"` or `"space"` if uploading to a dataset or
  4689. space, `None` or `"model"` if uploading to a model. Default is
  4690. `None`.
  4691. revision (`str`, *optional*):
  4692. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4693. commit_message (`str`, *optional*):
  4694. The summary / title / first line of the generated commit
  4695. commit_description (`str` *optional*)
  4696. The description of the generated commit
  4697. create_pr (`boolean`, *optional*):
  4698. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  4699. If `revision` is not set, PR is opened against the `"main"` branch. If
  4700. `revision` is set and is a branch, PR is opened against this branch. If
  4701. `revision` is set and is not a branch name (example: a commit oid), an
  4702. `RevisionNotFoundError` is returned by the server.
  4703. parent_commit (`str`, *optional*):
  4704. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  4705. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  4706. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  4707. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  4708. especially useful if the repo is updated / committed to concurrently.
  4709. run_as_future (`bool`, *optional*):
  4710. Whether or not to run this method in the background. Background jobs are run sequentially without
  4711. blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
  4712. object. Defaults to `False`.
  4713. Returns:
  4714. [`CommitInfo`] or `Future`:
  4715. Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
  4716. url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
  4717. contain the result when executed.
  4718. > [!TIP]
  4719. > Raises the following errors:
  4720. >
  4721. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  4722. > if the HuggingFace API returned an error
  4723. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4724. > if some parameter value is invalid
  4725. > - [`~utils.RepositoryNotFoundError`]
  4726. > If the repository to download from cannot be found. This may be because it doesn't exist,
  4727. > or because it is set to `private` and you do not have access.
  4728. > - [`~utils.RevisionNotFoundError`]
  4729. > If the revision to download from cannot be found.
  4730. > [!WARNING]
  4731. > `upload_file` assumes that the repo already exists on the Hub. If you get a
  4732. > Client error 404, please make sure you are authenticated, that your token has the required permissions,
  4733. > and that `repo_id` and `repo_type` are set correctly. If repo does not exist,
  4734. > create it first using [`~hf_api.create_repo`].
  4735. Example:
  4736. ```python
  4737. >>> from huggingface_hub import upload_file
  4738. >>> with open("./local/filepath", "rb") as fobj:
  4739. ... upload_file(
  4740. ... path_or_fileobj=fileobj,
  4741. ... path_in_repo="remote/file/path.h5",
  4742. ... repo_id="username/my-dataset",
  4743. ... repo_type="dataset",
  4744. ... token="my_token",
  4745. ... )
  4746. >>> upload_file(
  4747. ... path_or_fileobj=".\\\\local\\\\file\\\\path",
  4748. ... path_in_repo="remote/file/path.h5",
  4749. ... repo_id="username/my-model",
  4750. ... token="my_token",
  4751. ... )
  4752. >>> upload_file(
  4753. ... path_or_fileobj=".\\\\local\\\\file\\\\path",
  4754. ... path_in_repo="remote/file/path.h5",
  4755. ... repo_id="username/my-model",
  4756. ... token="my_token",
  4757. ... create_pr=True,
  4758. ... )
  4759. ```
  4760. """
  4761. if repo_type not in constants.REPO_TYPES:
  4762. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  4763. commit_message = (
  4764. commit_message if commit_message is not None else f"Upload {path_in_repo} with huggingface_hub"
  4765. )
  4766. operation = CommitOperationAdd(
  4767. path_or_fileobj=path_or_fileobj,
  4768. path_in_repo=path_in_repo,
  4769. )
  4770. return self.create_commit(
  4771. repo_id=repo_id,
  4772. repo_type=repo_type,
  4773. operations=[operation],
  4774. commit_message=commit_message,
  4775. commit_description=commit_description,
  4776. token=token,
  4777. revision=revision,
  4778. create_pr=create_pr,
  4779. _hot_reload=_hot_reload,
  4780. parent_commit=parent_commit,
  4781. )
  4782. @overload
  4783. def upload_folder( # type: ignore
  4784. self,
  4785. *,
  4786. repo_id: str,
  4787. folder_path: str | Path,
  4788. path_in_repo: str | None = None,
  4789. commit_message: str | None = None,
  4790. commit_description: str | None = None,
  4791. token: str | bool | None = None,
  4792. repo_type: str | None = None,
  4793. revision: str | None = None,
  4794. create_pr: bool | None = None,
  4795. parent_commit: str | None = None,
  4796. allow_patterns: list[str] | str | None = None,
  4797. ignore_patterns: list[str] | str | None = None,
  4798. delete_patterns: list[str] | str | None = None,
  4799. run_as_future: Literal[False] = ...,
  4800. ) -> CommitInfo: ...
  4801. @overload
  4802. def upload_folder( # type: ignore
  4803. self,
  4804. *,
  4805. repo_id: str,
  4806. folder_path: str | Path,
  4807. path_in_repo: str | None = None,
  4808. commit_message: str | None = None,
  4809. commit_description: str | None = None,
  4810. token: str | bool | None = None,
  4811. repo_type: str | None = None,
  4812. revision: str | None = None,
  4813. create_pr: bool | None = None,
  4814. parent_commit: str | None = None,
  4815. allow_patterns: list[str] | str | None = None,
  4816. ignore_patterns: list[str] | str | None = None,
  4817. delete_patterns: list[str] | str | None = None,
  4818. run_as_future: Literal[True] = ...,
  4819. ) -> Future[CommitInfo]: ...
  4820. @validate_hf_hub_args
  4821. @future_compatible
  4822. def upload_folder(
  4823. self,
  4824. *,
  4825. repo_id: str,
  4826. folder_path: str | Path,
  4827. path_in_repo: str | None = None,
  4828. commit_message: str | None = None,
  4829. commit_description: str | None = None,
  4830. token: str | bool | None = None,
  4831. repo_type: str | None = None,
  4832. revision: str | None = None,
  4833. create_pr: bool | None = None,
  4834. parent_commit: str | None = None,
  4835. allow_patterns: list[str] | str | None = None,
  4836. ignore_patterns: list[str] | str | None = None,
  4837. delete_patterns: list[str] | str | None = None,
  4838. run_as_future: bool = False,
  4839. ) -> CommitInfo | Future[CommitInfo]:
  4840. """
  4841. Upload a local folder to the given repo. The upload is done through a HTTP requests, and doesn't require git or
  4842. git-lfs to be installed.
  4843. The structure of the folder will be preserved. Files with the same name already present in the repository will
  4844. be overwritten. Others will be left untouched.
  4845. Use the `allow_patterns` and `ignore_patterns` arguments to specify which files to upload. These parameters
  4846. accept either a single pattern or a list of patterns. Patterns are Standard Wildcards (globbing patterns) as
  4847. documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). If both `allow_patterns` and
  4848. `ignore_patterns` are provided, both constraints apply. By default, all files from the folder are uploaded.
  4849. Use the `delete_patterns` argument to specify remote files you want to delete. Input type is the same as for
  4850. `allow_patterns` (see above). If `path_in_repo` is also provided, the patterns are matched against paths
  4851. relative to this folder. For example, `upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*")`
  4852. will delete any remote file under `./experiment/logs/`. Note that the `.gitattributes` file will not be deleted
  4853. even if it matches the patterns.
  4854. Any `.git/` folder present in any subdirectory will be ignored. However, please be aware that the `.gitignore`
  4855. file is not taken into account.
  4856. Uses `HfApi.create_commit` under the hood.
  4857. Args:
  4858. repo_id (`str`):
  4859. The repository to which the file will be uploaded, for example:
  4860. `"username/custom_transformers"`
  4861. folder_path (`str` or `Path`):
  4862. Path to the folder to upload on the local file system
  4863. path_in_repo (`str`, *optional*):
  4864. Relative path of the directory in the repo, for example:
  4865. `"checkpoints/1fec34a/results"`. Will default to the root folder of the repository.
  4866. token (`bool` or `str`, *optional*):
  4867. A valid user access token (string). Defaults to the locally saved
  4868. token, which is the recommended method for authentication (see
  4869. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4870. To disable authentication, pass `False`.
  4871. repo_type (`str`, *optional*):
  4872. Set to `"dataset"` or `"space"` if uploading to a dataset or
  4873. space, `None` or `"model"` if uploading to a model. Default is
  4874. `None`.
  4875. revision (`str`, *optional*):
  4876. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4877. commit_message (`str`, *optional*):
  4878. The summary / title / first line of the generated commit. Defaults to:
  4879. `f"Upload {path_in_repo} with huggingface_hub"`
  4880. commit_description (`str` *optional*):
  4881. The description of the generated commit
  4882. create_pr (`boolean`, *optional*):
  4883. Whether or not to create a Pull Request with that commit. Defaults to `False`. If `revision` is not
  4884. set, PR is opened against the `"main"` branch. If `revision` is set and is a branch, PR is opened
  4885. against this branch. If `revision` is set and is not a branch name (example: a commit oid), an
  4886. `RevisionNotFoundError` is returned by the server.
  4887. parent_commit (`str`, *optional*):
  4888. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  4889. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  4890. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  4891. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  4892. especially useful if the repo is updated / committed to concurrently.
  4893. allow_patterns (`list[str]` or `str`, *optional*):
  4894. If provided, only files matching at least one pattern are uploaded.
  4895. ignore_patterns (`list[str]` or `str`, *optional*):
  4896. If provided, files matching any of the patterns are not uploaded.
  4897. delete_patterns (`list[str]` or `str`, *optional*):
  4898. If provided, remote files matching any of the patterns will be deleted from the repo while committing
  4899. new files. This is useful if you don't know which files have already been uploaded.
  4900. Note: to avoid discrepancies the `.gitattributes` file is not deleted even if it matches the pattern.
  4901. run_as_future (`bool`, *optional*):
  4902. Whether or not to run this method in the background. Background jobs are run sequentially without
  4903. blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
  4904. object. Defaults to `False`.
  4905. Returns:
  4906. [`CommitInfo`] or `Future`:
  4907. Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
  4908. url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
  4909. contain the result when executed.
  4910. > [!TIP]
  4911. > Raises the following errors:
  4912. >
  4913. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  4914. > if the HuggingFace API returned an error
  4915. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4916. > if some parameter value is invalid
  4917. > [!WARNING]
  4918. > `upload_folder` assumes that the repo already exists on the Hub. If you get a Client error 404, please make
  4919. > sure you are authenticated, that your token has the required permissions, and that `repo_id` and `repo_type`
  4920. > are set correctly. If repo does not exist, create it first using [`~hf_api.create_repo`].
  4921. > [!TIP]
  4922. > When dealing with a large folder (thousands of files or hundreds of GB), we recommend using [`~hf_api.upload_large_folder`] instead.
  4923. Example:
  4924. ```python
  4925. # Upload checkpoints folder except the log files
  4926. >>> upload_folder(
  4927. ... folder_path="local/checkpoints",
  4928. ... path_in_repo="remote/experiment/checkpoints",
  4929. ... repo_id="username/my-dataset",
  4930. ... repo_type="datasets",
  4931. ... token="my_token",
  4932. ... ignore_patterns="**/logs/*.txt",
  4933. ... )
  4934. # Upload checkpoints folder including logs while deleting existing logs from the repo
  4935. # Useful if you don't know exactly which log files have already being pushed
  4936. >>> upload_folder(
  4937. ... folder_path="local/checkpoints",
  4938. ... path_in_repo="remote/experiment/checkpoints",
  4939. ... repo_id="username/my-dataset",
  4940. ... repo_type="datasets",
  4941. ... token="my_token",
  4942. ... delete_patterns="**/logs/*.txt",
  4943. ... )
  4944. # Upload checkpoints folder while creating a PR
  4945. >>> upload_folder(
  4946. ... folder_path="local/checkpoints",
  4947. ... path_in_repo="remote/experiment/checkpoints",
  4948. ... repo_id="username/my-dataset",
  4949. ... repo_type="datasets",
  4950. ... token="my_token",
  4951. ... create_pr=True,
  4952. ... )
  4953. ```
  4954. """
  4955. if repo_type not in constants.REPO_TYPES:
  4956. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  4957. # By default, upload folder to the root directory in repo.
  4958. if path_in_repo is None:
  4959. path_in_repo = ""
  4960. # Do not upload .git folder
  4961. if ignore_patterns is None:
  4962. ignore_patterns = []
  4963. elif isinstance(ignore_patterns, str):
  4964. ignore_patterns = [ignore_patterns]
  4965. ignore_patterns += DEFAULT_IGNORE_PATTERNS
  4966. delete_operations = self._prepare_folder_deletions(
  4967. repo_id=repo_id,
  4968. repo_type=repo_type,
  4969. revision=constants.DEFAULT_REVISION if create_pr else revision,
  4970. token=token,
  4971. path_in_repo=path_in_repo,
  4972. delete_patterns=delete_patterns,
  4973. )
  4974. add_operations = self._prepare_upload_folder_additions(
  4975. folder_path,
  4976. path_in_repo,
  4977. allow_patterns=allow_patterns,
  4978. ignore_patterns=ignore_patterns,
  4979. token=token,
  4980. repo_type=repo_type,
  4981. )
  4982. # Optimize operations: if some files will be overwritten, we don't need to delete them first
  4983. if len(add_operations) > 0:
  4984. added_paths = {op.path_in_repo for op in add_operations}
  4985. delete_operations = [
  4986. delete_op for delete_op in delete_operations if delete_op.path_in_repo not in added_paths
  4987. ]
  4988. commit_operations = delete_operations + add_operations
  4989. commit_message = commit_message or "Upload folder using huggingface_hub"
  4990. return self.create_commit(
  4991. repo_type=repo_type,
  4992. repo_id=repo_id,
  4993. operations=commit_operations,
  4994. commit_message=commit_message,
  4995. commit_description=commit_description,
  4996. token=token,
  4997. revision=revision,
  4998. create_pr=create_pr,
  4999. parent_commit=parent_commit,
  5000. )
  5001. @validate_hf_hub_args
  5002. def delete_file(
  5003. self,
  5004. path_in_repo: str,
  5005. repo_id: str,
  5006. *,
  5007. token: str | bool | None = None,
  5008. repo_type: str | None = None,
  5009. revision: str | None = None,
  5010. commit_message: str | None = None,
  5011. commit_description: str | None = None,
  5012. create_pr: bool | None = None,
  5013. parent_commit: str | None = None,
  5014. ) -> CommitInfo:
  5015. """
  5016. Deletes a file in the given repo.
  5017. Args:
  5018. path_in_repo (`str`):
  5019. Relative filepath in the repo, for example:
  5020. `"checkpoints/1fec34a/weights.bin"`
  5021. repo_id (`str`):
  5022. The repository from which the file will be deleted, for example:
  5023. `"username/custom_transformers"`
  5024. token (`bool` or `str`, *optional*):
  5025. A valid user access token (string). Defaults to the locally saved
  5026. token, which is the recommended method for authentication (see
  5027. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5028. To disable authentication, pass `False`.
  5029. repo_type (`str`, *optional*):
  5030. Set to `"dataset"` or `"space"` if the file is in a dataset or
  5031. space, `None` or `"model"` if in a model. Default is `None`.
  5032. revision (`str`, *optional*):
  5033. The git revision to commit from. Defaults to the head of the `"main"` branch.
  5034. commit_message (`str`, *optional*):
  5035. The summary / title / first line of the generated commit. Defaults to
  5036. `f"Delete {path_in_repo} with huggingface_hub"`.
  5037. commit_description (`str` *optional*)
  5038. The description of the generated commit
  5039. create_pr (`boolean`, *optional*):
  5040. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  5041. If `revision` is not set, PR is opened against the `"main"` branch. If
  5042. `revision` is set and is a branch, PR is opened against this branch. If
  5043. `revision` is set and is not a branch name (example: a commit oid), an
  5044. `RevisionNotFoundError` is returned by the server.
  5045. parent_commit (`str`, *optional*):
  5046. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  5047. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  5048. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  5049. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  5050. especially useful if the repo is updated / committed to concurrently.
  5051. > [!TIP]
  5052. > Raises the following errors:
  5053. >
  5054. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  5055. > if the HuggingFace API returned an error
  5056. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5057. > if some parameter value is invalid
  5058. > - [`~utils.RepositoryNotFoundError`]
  5059. > If the repository to download from cannot be found. This may be because it doesn't exist,
  5060. > or because it is set to `private` and you do not have access.
  5061. > - [`~utils.RevisionNotFoundError`]
  5062. > If the revision to download from cannot be found.
  5063. > - [`~utils.EntryNotFoundError`]
  5064. > If the file to download cannot be found.
  5065. """
  5066. commit_message = (
  5067. commit_message if commit_message is not None else f"Delete {path_in_repo} with huggingface_hub"
  5068. )
  5069. operations = [CommitOperationDelete(path_in_repo=path_in_repo)]
  5070. return self.create_commit(
  5071. repo_id=repo_id,
  5072. repo_type=repo_type,
  5073. token=token,
  5074. operations=operations,
  5075. revision=revision,
  5076. commit_message=commit_message,
  5077. commit_description=commit_description,
  5078. create_pr=create_pr,
  5079. parent_commit=parent_commit,
  5080. )
  5081. @validate_hf_hub_args
  5082. def delete_files(
  5083. self,
  5084. repo_id: str,
  5085. delete_patterns: list[str],
  5086. *,
  5087. token: bool | str | None = None,
  5088. repo_type: str | None = None,
  5089. revision: str | None = None,
  5090. commit_message: str | None = None,
  5091. commit_description: str | None = None,
  5092. create_pr: bool | None = None,
  5093. parent_commit: str | None = None,
  5094. ) -> CommitInfo:
  5095. """
  5096. Delete files from a repository on the Hub.
  5097. If a folder path is provided, the entire folder is deleted as well as
  5098. all files it contained.
  5099. Args:
  5100. repo_id (`str`):
  5101. The repository from which the folder will be deleted, for example:
  5102. `"username/custom_transformers"`
  5103. delete_patterns (`list[str]`):
  5104. List of files or folders to delete. Each string can either be
  5105. a file path, a folder path, or a wildcard pattern. Patterns are Standard
  5106. Wildcards (globbing patterns) as documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm).
  5107. The pattern matching is based on [`fnmatch`](https://docs.python.org/3/library/fnmatch.html).
  5108. Note that `fnmatch` matches `*` across path boundaries, unlike traditional Unix shell globbing.
  5109. E.g. `["file.txt", "folder/", "data/*.parquet"]`
  5110. token (`bool` or `str`, *optional*):
  5111. A valid user access token (string). Defaults to the locally saved
  5112. token, which is the recommended method for authentication (see
  5113. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5114. To disable authentication, pass `False`.
  5115. to the stored token.
  5116. repo_type (`str`, *optional*):
  5117. Type of the repo to delete files from. Can be `"model"`,
  5118. `"dataset"` or `"space"`. Defaults to `"model"`.
  5119. revision (`str`, *optional*):
  5120. The git revision to commit from. Defaults to the head of the `"main"` branch.
  5121. commit_message (`str`, *optional*):
  5122. The summary (first line) of the generated commit. Defaults to
  5123. `f"Delete files using huggingface_hub"`.
  5124. commit_description (`str` *optional*)
  5125. The description of the generated commit.
  5126. create_pr (`boolean`, *optional*):
  5127. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  5128. If `revision` is not set, PR is opened against the `"main"` branch. If
  5129. `revision` is set and is a branch, PR is opened against this branch. If
  5130. `revision` is set and is not a branch name (example: a commit oid), an
  5131. `RevisionNotFoundError` is returned by the server.
  5132. parent_commit (`str`, *optional*):
  5133. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  5134. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  5135. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  5136. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  5137. especially useful if the repo is updated / committed to concurrently.
  5138. """
  5139. operations = self._prepare_folder_deletions(
  5140. repo_id=repo_id, repo_type=repo_type, delete_patterns=delete_patterns, path_in_repo="", revision=revision
  5141. )
  5142. if commit_message is None:
  5143. commit_message = f"Delete files {' '.join(delete_patterns)} with huggingface_hub"
  5144. return self.create_commit(
  5145. repo_id=repo_id,
  5146. repo_type=repo_type,
  5147. token=token,
  5148. operations=operations,
  5149. revision=revision,
  5150. commit_message=commit_message,
  5151. commit_description=commit_description,
  5152. create_pr=create_pr,
  5153. parent_commit=parent_commit,
  5154. )
  5155. @validate_hf_hub_args
  5156. def delete_folder(
  5157. self,
  5158. path_in_repo: str,
  5159. repo_id: str,
  5160. *,
  5161. token: bool | str | None = None,
  5162. repo_type: str | None = None,
  5163. revision: str | None = None,
  5164. commit_message: str | None = None,
  5165. commit_description: str | None = None,
  5166. create_pr: bool | None = None,
  5167. parent_commit: str | None = None,
  5168. ) -> CommitInfo:
  5169. """
  5170. Deletes a folder in the given repo.
  5171. Simple wrapper around [`create_commit`] method.
  5172. Args:
  5173. path_in_repo (`str`):
  5174. Relative folder path in the repo, for example: `"checkpoints/1fec34a"`.
  5175. repo_id (`str`):
  5176. The repository from which the folder will be deleted, for example:
  5177. `"username/custom_transformers"`
  5178. token (`bool` or `str`, *optional*):
  5179. A valid user access token (string). Defaults to the locally saved
  5180. token, which is the recommended method for authentication (see
  5181. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5182. To disable authentication, pass `False`.
  5183. to the stored token.
  5184. repo_type (`str`, *optional*):
  5185. Set to `"dataset"` or `"space"` if the folder is in a dataset or
  5186. space, `None` or `"model"` if in a model. Default is `None`.
  5187. revision (`str`, *optional*):
  5188. The git revision to commit from. Defaults to the head of the `"main"` branch.
  5189. commit_message (`str`, *optional*):
  5190. The summary / title / first line of the generated commit. Defaults to
  5191. `f"Delete folder {path_in_repo} with huggingface_hub"`.
  5192. commit_description (`str` *optional*)
  5193. The description of the generated commit.
  5194. create_pr (`boolean`, *optional*):
  5195. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  5196. If `revision` is not set, PR is opened against the `"main"` branch. If
  5197. `revision` is set and is a branch, PR is opened against this branch. If
  5198. `revision` is set and is not a branch name (example: a commit oid), an
  5199. `RevisionNotFoundError` is returned by the server.
  5200. parent_commit (`str`, *optional*):
  5201. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  5202. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  5203. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  5204. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  5205. especially useful if the repo is updated / committed to concurrently.
  5206. """
  5207. return self.create_commit(
  5208. repo_id=repo_id,
  5209. repo_type=repo_type,
  5210. token=token,
  5211. operations=[CommitOperationDelete(path_in_repo=path_in_repo, is_folder=True)],
  5212. revision=revision,
  5213. commit_message=(
  5214. commit_message if commit_message is not None else f"Delete folder {path_in_repo} with huggingface_hub"
  5215. ),
  5216. commit_description=commit_description,
  5217. create_pr=create_pr,
  5218. parent_commit=parent_commit,
  5219. )
  5220. def upload_large_folder(
  5221. self,
  5222. repo_id: str,
  5223. folder_path: str | Path,
  5224. *,
  5225. repo_type: str, # Repo type is required!
  5226. revision: str | None = None,
  5227. private: bool | None = None,
  5228. allow_patterns: list[str] | str | None = None,
  5229. ignore_patterns: list[str] | str | None = None,
  5230. num_workers: int | None = None,
  5231. print_report: bool = True,
  5232. print_report_every: int = 60,
  5233. ) -> None:
  5234. """Upload a large folder to the Hub in the most resilient way possible.
  5235. Several workers are started to upload files in an optimized way. Before being committed to a repo, files must be
  5236. hashed and be pre-uploaded if they are LFS files. Workers will perform these tasks for each file in the folder.
  5237. At each step, some metadata information about the upload process is saved in the folder under `.cache/.huggingface/`
  5238. to be able to resume the process if interrupted. The whole process might result in several commits.
  5239. Args:
  5240. repo_id (`str`):
  5241. The repository to which the file will be uploaded.
  5242. E.g. `"HuggingFaceTB/smollm-corpus"`.
  5243. folder_path (`str` or `Path`):
  5244. Path to the folder to upload on the local file system.
  5245. repo_type (`str`):
  5246. Type of the repository. Must be one of `"model"`, `"dataset"` or `"space"`.
  5247. Unlike in all other `HfApi` methods, `repo_type` is explicitly required here. This is to avoid
  5248. any mistake when uploading a large folder to the Hub, and therefore prevent from having to re-upload
  5249. everything.
  5250. revision (`str`, `optional`):
  5251. The branch to commit to. If not provided, the `main` branch will be used.
  5252. private (`bool`, `optional`):
  5253. Whether the repository should be private.
  5254. If `None` (default), the repo will be public unless the organization's default is private.
  5255. allow_patterns (`list[str]` or `str`, *optional*):
  5256. If provided, only files matching at least one pattern are uploaded.
  5257. ignore_patterns (`list[str]` or `str`, *optional*):
  5258. If provided, files matching any of the patterns are not uploaded.
  5259. num_workers (`int`, *optional*):
  5260. Number of workers to start. Defaults to half of CPU cores (minimum 1).
  5261. A higher number of workers may speed up the process if your machine allows it. However, on machines with a
  5262. slower connection, it is recommended to keep the number of workers low to ensure better resumability.
  5263. Indeed, partially uploaded files will have to be completely re-uploaded if the process is interrupted.
  5264. print_report (`bool`, *optional*):
  5265. Whether to print a report of the upload progress. Defaults to True.
  5266. Report is printed to `sys.stdout` every X seconds (60 by defaults) and overwrites the previous report.
  5267. print_report_every (`int`, *optional*):
  5268. Frequency at which the report is printed. Defaults to 60 seconds.
  5269. > [!TIP]
  5270. > A few things to keep in mind:
  5271. > - Repository limits still apply: https://huggingface.co/docs/hub/repositories-recommendations
  5272. > - Do not start several processes in parallel.
  5273. > - You can interrupt and resume the process at any time.
  5274. > - Do not upload the same folder to several repositories. If you need to do so, you must delete the local `.cache/.huggingface/` folder first.
  5275. > [!WARNING]
  5276. > While being much more robust to upload large folders, `upload_large_folder` is more limited than [`upload_folder`] feature-wise. In practice:
  5277. > - you cannot set a custom `path_in_repo`. If you want to upload to a subfolder, you need to set the proper structure locally.
  5278. > - you cannot set a custom `commit_message` and `commit_description` since multiple commits are created.
  5279. > - you cannot delete from the repo while uploading. Please make a separate commit first.
  5280. > - 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`.
  5281. **Technical details:**
  5282. `upload_large_folder` process is as follow:
  5283. 1. (Check parameters and setup.)
  5284. 2. Create repo if missing.
  5285. 3. List local files to upload.
  5286. 4. Run validation checks and display warnings if repository limits might be exceeded:
  5287. - Warns if the total number of files exceeds 100k (recommended limit).
  5288. - Warns if any folder contains more than 10k files (recommended limit).
  5289. - Warns about files larger than 20GB (recommended) or 50GB (hard limit).
  5290. 5. Start workers. Workers can perform the following tasks:
  5291. - Hash a file.
  5292. - Get upload mode (regular or LFS) for a list of files.
  5293. - Pre-upload an LFS file.
  5294. - Commit a bunch of files.
  5295. Once a worker finishes a task, it will move on to the next task based on the priority list (see below) until
  5296. all files are uploaded and committed.
  5297. 6. While workers are up, regularly print a report to sys.stdout.
  5298. Order of priority:
  5299. 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file).
  5300. 2. Commit if at least 150 files are ready to commit.
  5301. 3. Get upload mode if at least 10 files have been hashed.
  5302. 4. Pre-upload LFS file if at least 1 file and no worker is pre-uploading.
  5303. 5. Hash file if at least 1 file and no worker is hashing.
  5304. 6. Get upload mode if at least 1 file and no worker is getting upload mode.
  5305. 7. Pre-upload LFS file if at least 1 file.
  5306. 8. Hash file if at least 1 file to hash.
  5307. 9. Get upload mode if at least 1 file to get upload mode.
  5308. 10. Commit if at least 1 file to commit and at least 1 min since last commit attempt.
  5309. 11. Commit if at least 1 file to commit and all other queues are empty.
  5310. Special rules:
  5311. - Only one worker can commit at a time.
  5312. - If no tasks are available, the worker waits for 10 seconds before checking again.
  5313. """
  5314. return upload_large_folder_internal(
  5315. self,
  5316. repo_id=repo_id,
  5317. folder_path=folder_path,
  5318. repo_type=repo_type,
  5319. revision=revision,
  5320. private=private,
  5321. allow_patterns=allow_patterns,
  5322. ignore_patterns=ignore_patterns,
  5323. num_workers=num_workers,
  5324. print_report=print_report,
  5325. print_report_every=print_report_every,
  5326. )
  5327. @validate_hf_hub_args
  5328. def get_hf_file_metadata(
  5329. self,
  5330. *,
  5331. url: str,
  5332. token: bool | str | None = None,
  5333. timeout: float | None = constants.HF_HUB_ETAG_TIMEOUT,
  5334. ) -> HfFileMetadata:
  5335. """Fetch metadata of a file versioned on the Hub for a given url.
  5336. Args:
  5337. url (`str`):
  5338. File url, for example returned by [`hf_hub_url`].
  5339. token (`bool` or `str`, *optional*):
  5340. A valid user access token (string). Defaults to the locally saved
  5341. token, which is the recommended method for authentication (see
  5342. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5343. To disable authentication, pass `False`.
  5344. timeout (`float`, *optional*, defaults to 10):
  5345. How many seconds to wait for the server to send metadata before giving up.
  5346. Returns:
  5347. A [`HfFileMetadata`] object containing metadata such as location, etag, size and commit_hash.
  5348. """
  5349. if token is None:
  5350. # Cannot do `token = token or self.token` as token can be `False`.
  5351. token = self.token
  5352. return get_hf_file_metadata(
  5353. url=url,
  5354. token=token,
  5355. timeout=timeout,
  5356. library_name=self.library_name,
  5357. library_version=self.library_version,
  5358. user_agent=self.user_agent,
  5359. endpoint=self.endpoint,
  5360. )
  5361. @overload
  5362. def hf_hub_download(
  5363. self,
  5364. repo_id: str,
  5365. filename: str,
  5366. *,
  5367. subfolder: str | None = None,
  5368. repo_type: str | None = None,
  5369. revision: str | None = None,
  5370. cache_dir: str | Path | None = None,
  5371. local_dir: str | Path | None = None,
  5372. force_download: bool = False,
  5373. etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
  5374. token: bool | str | None = None,
  5375. local_files_only: bool = False,
  5376. tqdm_class: type[base_tqdm] | None = None,
  5377. dry_run: Literal[False] = False,
  5378. ) -> str: ...
  5379. @overload
  5380. def hf_hub_download(
  5381. self,
  5382. repo_id: str,
  5383. filename: str,
  5384. *,
  5385. subfolder: str | None = None,
  5386. repo_type: str | None = None,
  5387. revision: str | None = None,
  5388. cache_dir: str | Path | None = None,
  5389. local_dir: str | Path | None = None,
  5390. force_download: bool = False,
  5391. etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
  5392. token: bool | str | None = None,
  5393. local_files_only: bool = False,
  5394. tqdm_class: type[base_tqdm] | None = None,
  5395. dry_run: Literal[True],
  5396. ) -> DryRunFileInfo: ...
  5397. @validate_hf_hub_args
  5398. def hf_hub_download(
  5399. self,
  5400. repo_id: str,
  5401. filename: str,
  5402. *,
  5403. subfolder: str | None = None,
  5404. repo_type: str | None = None,
  5405. revision: str | None = None,
  5406. cache_dir: str | Path | None = None,
  5407. local_dir: str | Path | None = None,
  5408. force_download: bool = False,
  5409. etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
  5410. token: bool | str | None = None,
  5411. local_files_only: bool = False,
  5412. tqdm_class: type[base_tqdm] | None = None,
  5413. dry_run: bool = False,
  5414. ) -> str | DryRunFileInfo:
  5415. """Download a given file if it's not already present in the local cache.
  5416. The new cache file layout looks like this:
  5417. - The cache directory contains one subfolder per repo_id (namespaced by repo type)
  5418. - inside each repo folder:
  5419. - refs is a list of the latest known revision => commit_hash pairs
  5420. - blobs contains the actual file blobs (identified by their git-sha or sha256, depending on
  5421. whether they're LFS files or not)
  5422. - snapshots contains one subfolder per commit, each "commit" contains the subset of the files
  5423. that have been resolved at that particular commit. Each filename is a symlink to the blob
  5424. at that particular commit.
  5425. ```
  5426. [ 96] .
  5427. └── [ 160] models--julien-c--EsperBERTo-small
  5428. ├── [ 160] blobs
  5429. │ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
  5430. │ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e
  5431. │ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812
  5432. ├── [ 96] refs
  5433. │ └── [ 40] main
  5434. └── [ 128] snapshots
  5435. ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
  5436. │ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
  5437. │ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
  5438. └── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48
  5439. ├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
  5440. └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
  5441. ```
  5442. If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
  5443. option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
  5444. to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
  5445. cache-system, it's optimized for regularly pulling the latest version of a repository.
  5446. Args:
  5447. repo_id (`str`):
  5448. A user or an organization name and a repo name separated by a `/`.
  5449. filename (`str`):
  5450. The name of the file in the repo.
  5451. subfolder (`str`, *optional*):
  5452. An optional value corresponding to a folder inside the repository.
  5453. repo_type (`str`, *optional*):
  5454. Set to `"dataset"` or `"space"` if downloading from a dataset or space,
  5455. `None` or `"model"` if downloading from a model. Default is `None`.
  5456. revision (`str`, *optional*):
  5457. An optional Git revision id which can be a branch name, a tag, or a
  5458. commit hash.
  5459. cache_dir (`str`, `Path`, *optional*):
  5460. Path to the folder where cached files are stored.
  5461. local_dir (`str` or `Path`, *optional*):
  5462. If provided, the downloaded file will be placed under this directory.
  5463. force_download (`bool`, *optional*, defaults to `False`):
  5464. Whether the file should be downloaded even if it already exists in
  5465. the local cache.
  5466. etag_timeout (`float`, *optional*, defaults to `10`):
  5467. When fetching ETag, how many seconds to wait for the server to send
  5468. data before giving up which is passed to `httpx.request`.
  5469. token (`bool` or `str`, *optional*):
  5470. A valid user access token (string). Defaults to the locally saved
  5471. token, which is the recommended method for authentication (see
  5472. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5473. To disable authentication, pass `False`.
  5474. local_files_only (`bool`, *optional*, defaults to `False`):
  5475. If `True`, avoid downloading the file and return the path to the
  5476. local cached file if it exists.
  5477. tqdm_class (`tqdm`, *optional*):
  5478. If provided, overwrites the default behavior for the progress bar. Passed
  5479. argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
  5480. Defaults to the custom HF progress bar that can be disabled by setting
  5481. `HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
  5482. dry_run (`bool`, *optional*, defaults to `False`):
  5483. If `True`, perform a dry run without actually downloading the file. Returns a
  5484. [`DryRunFileInfo`] object containing information about what would be downloaded.
  5485. Returns:
  5486. `str` or [`DryRunFileInfo`]:
  5487. - If `dry_run=False`: Local path of file or if networking is off, last version of file cached on disk.
  5488. - If `dry_run=True`: A [`DryRunFileInfo`] object containing download information.
  5489. Raises:
  5490. [`~utils.RepositoryNotFoundError`]
  5491. If the repository to download from cannot be found. This may be because it doesn't exist,
  5492. or because it is set to `private` and you do not have access.
  5493. [`~utils.RevisionNotFoundError`]
  5494. If the revision to download from cannot be found.
  5495. [`~utils.RemoteEntryNotFoundError`]
  5496. If the file to download cannot be found.
  5497. [`~utils.LocalEntryNotFoundError`]
  5498. If network is disabled or unavailable and file is not found in cache.
  5499. [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
  5500. If `token=True` but the token cannot be found.
  5501. [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
  5502. If ETag cannot be determined.
  5503. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5504. If some parameter value is invalid.
  5505. """
  5506. from .file_download import hf_hub_download
  5507. if token is None:
  5508. # Cannot do `token = token or self.token` as token can be `False`.
  5509. token = self.token
  5510. return hf_hub_download(
  5511. repo_id=repo_id,
  5512. filename=filename,
  5513. subfolder=subfolder,
  5514. repo_type=repo_type,
  5515. revision=revision,
  5516. endpoint=self.endpoint,
  5517. library_name=self.library_name,
  5518. library_version=self.library_version,
  5519. cache_dir=cache_dir,
  5520. local_dir=local_dir,
  5521. user_agent=self.user_agent,
  5522. force_download=force_download,
  5523. etag_timeout=etag_timeout,
  5524. token=token,
  5525. headers=self.headers,
  5526. local_files_only=local_files_only,
  5527. tqdm_class=tqdm_class,
  5528. dry_run=dry_run,
  5529. )
  5530. @overload
  5531. def snapshot_download(
  5532. self,
  5533. repo_id: str,
  5534. *,
  5535. repo_type: str | None = None,
  5536. revision: str | None = None,
  5537. cache_dir: str | Path | None = None,
  5538. local_dir: str | Path | None = None,
  5539. etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
  5540. force_download: bool = False,
  5541. token: bool | str | None = None,
  5542. local_files_only: bool = False,
  5543. allow_patterns: list[str] | str | None = None,
  5544. ignore_patterns: list[str] | str | None = None,
  5545. max_workers: int = 8,
  5546. tqdm_class: type[base_tqdm] | None = None,
  5547. dry_run: Literal[False] = False,
  5548. ) -> str: ...
  5549. @overload
  5550. def snapshot_download(
  5551. self,
  5552. repo_id: str,
  5553. *,
  5554. repo_type: str | None = None,
  5555. revision: str | None = None,
  5556. cache_dir: str | Path | None = None,
  5557. local_dir: str | Path | None = None,
  5558. etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
  5559. force_download: bool = False,
  5560. token: bool | str | None = None,
  5561. local_files_only: bool = False,
  5562. allow_patterns: list[str] | str | None = None,
  5563. ignore_patterns: list[str] | str | None = None,
  5564. max_workers: int = 8,
  5565. tqdm_class: type[base_tqdm] | None = None,
  5566. dry_run: Literal[True],
  5567. ) -> list[DryRunFileInfo]: ...
  5568. @validate_hf_hub_args
  5569. def snapshot_download(
  5570. self,
  5571. repo_id: str,
  5572. *,
  5573. repo_type: str | None = None,
  5574. revision: str | None = None,
  5575. cache_dir: str | Path | None = None,
  5576. local_dir: str | Path | None = None,
  5577. etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
  5578. force_download: bool = False,
  5579. token: bool | str | None = None,
  5580. local_files_only: bool = False,
  5581. allow_patterns: list[str] | str | None = None,
  5582. ignore_patterns: list[str] | str | None = None,
  5583. max_workers: int = 8,
  5584. tqdm_class: type[base_tqdm] | None = None,
  5585. dry_run: bool = False,
  5586. ) -> str | list[DryRunFileInfo]:
  5587. """Download repo files.
  5588. Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from
  5589. a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order
  5590. to keep their actual filename relative to that folder. You can also filter which files to download using
  5591. `allow_patterns` and `ignore_patterns`.
  5592. If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
  5593. option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
  5594. to store some metadata related to the downloaded files.While this mechanism is not as robust as the main
  5595. cache-system, it's optimized for regularly pulling the latest version of a repository.
  5596. An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly
  5597. configured. It is also not possible to filter which files to download when cloning a repository using git.
  5598. Args:
  5599. repo_id (`str`):
  5600. A user or an organization name and a repo name separated by a `/`.
  5601. repo_type (`str`, *optional*):
  5602. Set to `"dataset"` or `"space"` if downloading from a dataset or space,
  5603. `None` or `"model"` if downloading from a model. Default is `None`.
  5604. revision (`str`, *optional*):
  5605. An optional Git revision id which can be a branch name, a tag, or a
  5606. commit hash.
  5607. cache_dir (`str`, `Path`, *optional*):
  5608. Path to the folder where cached files are stored.
  5609. local_dir (`str` or `Path`, *optional*):
  5610. If provided, the downloaded files will be placed under this directory.
  5611. etag_timeout (`float`, *optional*, defaults to `10`):
  5612. When fetching ETag, how many seconds to wait for the server to send
  5613. data before giving up which is passed to `httpx.request`.
  5614. force_download (`bool`, *optional*, defaults to `False`):
  5615. Whether the file should be downloaded even if it already exists in the local cache.
  5616. token (`bool` or `str`, *optional*):
  5617. A valid user access token (string). Defaults to the locally saved
  5618. token, which is the recommended method for authentication (see
  5619. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5620. To disable authentication, pass `False`.
  5621. local_files_only (`bool`, *optional*, defaults to `False`):
  5622. If `True`, avoid downloading the file and return the path to the
  5623. local cached file if it exists.
  5624. allow_patterns (`list[str]` or `str`, *optional*):
  5625. If provided, only files matching at least one pattern are downloaded.
  5626. ignore_patterns (`list[str]` or `str`, *optional*):
  5627. If provided, files matching any of the patterns are not downloaded.
  5628. max_workers (`int`, *optional*):
  5629. Number of concurrent threads to download files (1 thread = 1 file download).
  5630. Defaults to 8.
  5631. tqdm_class (`tqdm`, *optional*):
  5632. If provided, overwrites the default behavior for the progress bar. Passed
  5633. argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
  5634. Note that the `tqdm_class` is not passed to each individual download.
  5635. Defaults to the custom HF progress bar that can be disabled by setting
  5636. `HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
  5637. dry_run (`bool`, *optional*, defaults to `False`):
  5638. If `True`, perform a dry run without actually downloading the files. Returns a list of
  5639. [`DryRunFileInfo`] objects containing information about what would be downloaded.
  5640. Returns:
  5641. `str` or list of [`DryRunFileInfo`]:
  5642. - If `dry_run=False`: Folder path of the repo snapshot.
  5643. - If `dry_run=True`: A list of [`DryRunFileInfo`] objects containing download information.
  5644. Raises:
  5645. [`~utils.RepositoryNotFoundError`]
  5646. If the repository to download from cannot be found. This may be because it doesn't exist,
  5647. or because it is set to `private` and you do not have access.
  5648. [`~utils.RevisionNotFoundError`]
  5649. If the revision to download from cannot be found.
  5650. [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
  5651. If `token=True` and the token cannot be found.
  5652. [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if
  5653. ETag cannot be determined.
  5654. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5655. if some parameter value is invalid.
  5656. """
  5657. from ._snapshot_download import snapshot_download
  5658. if token is None:
  5659. # Cannot do `token = token or self.token` as token can be `False`.
  5660. token = self.token
  5661. return snapshot_download(
  5662. repo_id=repo_id,
  5663. repo_type=repo_type,
  5664. revision=revision,
  5665. endpoint=self.endpoint,
  5666. cache_dir=cache_dir,
  5667. local_dir=local_dir,
  5668. library_name=self.library_name,
  5669. library_version=self.library_version,
  5670. user_agent=self.user_agent,
  5671. etag_timeout=etag_timeout,
  5672. force_download=force_download,
  5673. token=token,
  5674. local_files_only=local_files_only,
  5675. allow_patterns=allow_patterns,
  5676. ignore_patterns=ignore_patterns,
  5677. max_workers=max_workers,
  5678. tqdm_class=tqdm_class,
  5679. headers=self.headers,
  5680. dry_run=dry_run,
  5681. )
  5682. def get_safetensors_metadata(
  5683. self,
  5684. repo_id: str,
  5685. *,
  5686. repo_type: str | None = None,
  5687. revision: str | None = None,
  5688. token: bool | str | None = None,
  5689. ) -> SafetensorsRepoMetadata:
  5690. """
  5691. Parse metadata for a safetensors repo on the Hub.
  5692. We first check if the repo has a single safetensors file or a sharded safetensors repo. If it's a single
  5693. safetensors file, we parse the metadata from this file. If it's a sharded safetensors repo, we parse the
  5694. metadata from the index file and then parse the metadata from each shard.
  5695. To parse metadata from a single safetensors file, use [`parse_safetensors_file_metadata`].
  5696. For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
  5697. Args:
  5698. repo_id (`str`):
  5699. A user or an organization name and a repo name separated by a `/`.
  5700. repo_type (`str`, *optional*):
  5701. Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
  5702. model. Default is `None`.
  5703. revision (`str`, *optional*):
  5704. The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
  5705. head of the `"main"` branch.
  5706. token (`bool` or `str`, *optional*):
  5707. A valid user access token (string). Defaults to the locally saved
  5708. token, which is the recommended method for authentication (see
  5709. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5710. To disable authentication, pass `False`.
  5711. Returns:
  5712. [`SafetensorsRepoMetadata`]: information related to safetensors repo.
  5713. Raises:
  5714. [`NotASafetensorsRepoError`]
  5715. If the repo is not a safetensors repo i.e. doesn't have either a
  5716. `model.safetensors` or a `model.safetensors.index.json` file.
  5717. [`SafetensorsParsingError`]
  5718. If a safetensors file header couldn't be parsed correctly.
  5719. Example:
  5720. ```py
  5721. # Parse repo with single weights file
  5722. >>> metadata = get_safetensors_metadata("bigscience/bloomz-560m")
  5723. >>> metadata
  5724. SafetensorsRepoMetadata(
  5725. metadata=None,
  5726. sharded=False,
  5727. weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...},
  5728. files_metadata={'model.safetensors': SafetensorsFileMetadata(...)}
  5729. )
  5730. >>> metadata.files_metadata["model.safetensors"].metadata
  5731. {'format': 'pt'}
  5732. # Parse repo with sharded model
  5733. >>> metadata = get_safetensors_metadata("bigscience/bloom")
  5734. Parse safetensors files: 100%|██████████████████████████████████████████| 72/72 [00:12<00:00, 5.78it/s]
  5735. >>> metadata
  5736. SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...})
  5737. >>> len(metadata.files_metadata)
  5738. 72 # All safetensors files have been fetched
  5739. # Parse repo with sharded model
  5740. >>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5")
  5741. NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files.
  5742. ```
  5743. """
  5744. if self.file_exists( # Single safetensors file => non-sharded model
  5745. repo_id=repo_id,
  5746. filename=constants.SAFETENSORS_SINGLE_FILE,
  5747. repo_type=repo_type,
  5748. revision=revision,
  5749. token=token,
  5750. ):
  5751. file_metadata = self.parse_safetensors_file_metadata(
  5752. repo_id=repo_id,
  5753. filename=constants.SAFETENSORS_SINGLE_FILE,
  5754. repo_type=repo_type,
  5755. revision=revision,
  5756. token=token,
  5757. )
  5758. return SafetensorsRepoMetadata(
  5759. metadata=None,
  5760. sharded=False,
  5761. weight_map={
  5762. tensor_name: constants.SAFETENSORS_SINGLE_FILE for tensor_name in file_metadata.tensors.keys()
  5763. },
  5764. files_metadata={constants.SAFETENSORS_SINGLE_FILE: file_metadata},
  5765. )
  5766. elif self.file_exists( # Multiple safetensors files => sharded with index
  5767. repo_id=repo_id,
  5768. filename=constants.SAFETENSORS_INDEX_FILE,
  5769. repo_type=repo_type,
  5770. revision=revision,
  5771. token=token,
  5772. ):
  5773. # Fetch index
  5774. index_file = self.hf_hub_download(
  5775. repo_id=repo_id,
  5776. filename=constants.SAFETENSORS_INDEX_FILE,
  5777. repo_type=repo_type,
  5778. revision=revision,
  5779. token=token,
  5780. )
  5781. with open(index_file) as f:
  5782. index = json.load(f)
  5783. weight_map = index.get("weight_map", {})
  5784. # Fetch metadata per shard
  5785. files_metadata = {}
  5786. def _parse(filename: str) -> None:
  5787. files_metadata[filename] = self.parse_safetensors_file_metadata(
  5788. repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, token=token
  5789. )
  5790. thread_map(
  5791. _parse,
  5792. set(weight_map.values()),
  5793. desc="Parse safetensors files",
  5794. tqdm_class=hf_tqdm,
  5795. )
  5796. return SafetensorsRepoMetadata(
  5797. metadata=index.get("metadata", None),
  5798. sharded=True,
  5799. weight_map=weight_map,
  5800. files_metadata=files_metadata,
  5801. )
  5802. else:
  5803. # Not a safetensors repo
  5804. raise NotASafetensorsRepoError(
  5805. f"'{repo_id}' is not a safetensors repo. Couldn't find '{constants.SAFETENSORS_INDEX_FILE}' or '{constants.SAFETENSORS_SINGLE_FILE}' files."
  5806. )
  5807. def parse_safetensors_file_metadata(
  5808. self,
  5809. repo_id: str,
  5810. filename: str,
  5811. *,
  5812. repo_type: str | None = None,
  5813. revision: str | None = None,
  5814. token: bool | str | None = None,
  5815. ) -> SafetensorsFileMetadata:
  5816. """
  5817. Parse metadata from a safetensors file on the Hub.
  5818. To parse metadata from all safetensors files in a repo at once, use [`get_safetensors_metadata`].
  5819. For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
  5820. Args:
  5821. repo_id (`str`):
  5822. A user or an organization name and a repo name separated by a `/`.
  5823. filename (`str`):
  5824. The name of the file in the repo.
  5825. repo_type (`str`, *optional*):
  5826. Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
  5827. model. Default is `None`.
  5828. revision (`str`, *optional*):
  5829. The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
  5830. head of the `"main"` branch.
  5831. token (`bool` or `str`, *optional*):
  5832. A valid user access token (string). Defaults to the locally saved
  5833. token, which is the recommended method for authentication (see
  5834. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5835. To disable authentication, pass `False`.
  5836. Returns:
  5837. [`SafetensorsFileMetadata`]: information related to a safetensors file.
  5838. Raises:
  5839. [`NotASafetensorsRepoError`]:
  5840. If the repo is not a safetensors repo i.e. doesn't have either a
  5841. `model.safetensors` or a `model.safetensors.index.json` file.
  5842. [`SafetensorsParsingError`]:
  5843. If a safetensors file header couldn't be parsed correctly.
  5844. """
  5845. url = hf_hub_url(
  5846. repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, endpoint=self.endpoint
  5847. )
  5848. _headers = self._build_hf_headers(token=token)
  5849. context_msg = f"repo '{repo_id}', revision '{revision or constants.DEFAULT_REVISION}'"
  5850. # 1. Fetch first 100kb
  5851. # Empirically, 97% of safetensors files have a metadata size < 100kb (over the top 1000 models on the Hub).
  5852. # We assume fetching 100kb is faster than making 2 GET requests. Therefore we always fetch the first 100kb to
  5853. # avoid the 2nd GET in most cases.
  5854. # See https://github.com/huggingface/huggingface_hub/pull/1855#discussion_r1404286419.
  5855. response = get_session().get(url, headers={**_headers, "range": "bytes=0-100000"})
  5856. hf_raise_for_status(response)
  5857. # 2. Parse and validate metadata size using shared helper
  5858. metadata_size = _get_safetensors_metadata_size(response.content[:8], filename, context_msg)
  5859. # 3.a. Get metadata from payload
  5860. if metadata_size <= 100000:
  5861. metadata_as_bytes = response.content[8 : 8 + metadata_size]
  5862. else: # 3.b. Request full metadata
  5863. response = get_session().get(url, headers={**_headers, "range": f"bytes=8-{metadata_size + 7}"})
  5864. hf_raise_for_status(response)
  5865. metadata_as_bytes = response.content
  5866. # 4. Parse json header using shared helper
  5867. return _parse_safetensors_header(metadata_as_bytes, filename, context_msg)
  5868. @validate_hf_hub_args
  5869. def create_branch(
  5870. self,
  5871. repo_id: str,
  5872. *,
  5873. branch: str,
  5874. revision: str | None = None,
  5875. token: bool | str | None = None,
  5876. repo_type: str | None = None,
  5877. exist_ok: bool = False,
  5878. ) -> None:
  5879. """
  5880. Create a new branch for a repo on the Hub, starting from the specified revision (defaults to `main`).
  5881. To find a revision suiting your needs, you can use [`list_repo_refs`] or [`list_repo_commits`].
  5882. Args:
  5883. repo_id (`str`):
  5884. The repository in which the branch will be created.
  5885. Example: `"user/my-cool-model"`.
  5886. branch (`str`):
  5887. The name of the branch to create.
  5888. revision (`str`, *optional*):
  5889. The git revision to create the branch from. It can be a branch name or
  5890. the OID/SHA of a commit, as a hexadecimal string. Defaults to the head
  5891. of the `"main"` branch.
  5892. token (`bool` or `str`, *optional*):
  5893. A valid user access token (string). Defaults to the locally saved
  5894. token, which is the recommended method for authentication (see
  5895. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5896. To disable authentication, pass `False`.
  5897. repo_type (`str`, *optional*):
  5898. Set to `"dataset"` or `"space"` if creating a branch on a dataset or
  5899. space, `None` or `"model"` if tagging a model. Default is `None`.
  5900. exist_ok (`bool`, *optional*, defaults to `False`):
  5901. If `True`, do not raise an error if branch already exists.
  5902. Raises:
  5903. [`~utils.RepositoryNotFoundError`]:
  5904. If repository is not found (error 404): wrong repo_id/repo_type, private
  5905. but not authenticated or repo does not exist.
  5906. [`~utils.BadRequestError`]:
  5907. If invalid reference for a branch. Ex: `refs/pr/5` or 'refs/foo/bar'.
  5908. [`~utils.HfHubHTTPError`]:
  5909. If the branch already exists on the repo (error 409) and `exist_ok` is
  5910. set to `False`.
  5911. """
  5912. if repo_type is None:
  5913. repo_type = constants.REPO_TYPE_MODEL
  5914. branch = quote(branch, safe="")
  5915. # Prepare request
  5916. branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}"
  5917. headers = self._build_hf_headers(token=token)
  5918. payload = {}
  5919. if revision is not None:
  5920. payload["startingPoint"] = revision
  5921. # Create branch
  5922. response = get_session().post(url=branch_url, headers=headers, json=payload)
  5923. try:
  5924. hf_raise_for_status(response)
  5925. except HfHubHTTPError as e:
  5926. if exist_ok and e.response.status_code == 409:
  5927. return
  5928. elif exist_ok and e.response.status_code == 403:
  5929. # No write permission on the namespace but branch might already exist
  5930. try:
  5931. refs = self.list_repo_refs(repo_id=repo_id, repo_type=repo_type, token=token)
  5932. for branch_ref in refs.branches:
  5933. if branch_ref.name == branch:
  5934. return # Branch already exists => do not raise
  5935. except HfHubHTTPError:
  5936. pass # We raise the original error if the branch does not exist
  5937. raise
  5938. @validate_hf_hub_args
  5939. def delete_branch(
  5940. self,
  5941. repo_id: str,
  5942. *,
  5943. branch: str,
  5944. token: bool | str | None = None,
  5945. repo_type: str | None = None,
  5946. ) -> None:
  5947. """
  5948. Delete a branch from a repo on the Hub.
  5949. Args:
  5950. repo_id (`str`):
  5951. The repository in which a branch will be deleted.
  5952. Example: `"user/my-cool-model"`.
  5953. branch (`str`):
  5954. The name of the branch to delete.
  5955. token (`bool` or `str`, *optional*):
  5956. A valid user access token (string). Defaults to the locally saved
  5957. token, which is the recommended method for authentication (see
  5958. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5959. To disable authentication, pass `False`.
  5960. repo_type (`str`, *optional*):
  5961. Set to `"dataset"` or `"space"` if creating a branch on a dataset or
  5962. space, `None` or `"model"` if tagging a model. Default is `None`.
  5963. Raises:
  5964. [`~utils.RepositoryNotFoundError`]:
  5965. If repository is not found (error 404): wrong repo_id/repo_type, private
  5966. but not authenticated or repo does not exist.
  5967. [`~utils.HfHubHTTPError`]:
  5968. If trying to delete a protected branch. Ex: `main` cannot be deleted.
  5969. [`~utils.HfHubHTTPError`]:
  5970. If trying to delete a branch that does not exist.
  5971. """
  5972. if repo_type is None:
  5973. repo_type = constants.REPO_TYPE_MODEL
  5974. branch = quote(branch, safe="")
  5975. # Prepare request
  5976. branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}"
  5977. headers = self._build_hf_headers(token=token)
  5978. # Delete branch
  5979. response = get_session().delete(url=branch_url, headers=headers)
  5980. hf_raise_for_status(response)
  5981. @validate_hf_hub_args
  5982. def create_tag(
  5983. self,
  5984. repo_id: str,
  5985. *,
  5986. tag: str,
  5987. tag_message: str | None = None,
  5988. revision: str | None = None,
  5989. token: bool | str | None = None,
  5990. repo_type: str | None = None,
  5991. exist_ok: bool = False,
  5992. ) -> None:
  5993. """
  5994. Tag a given commit of a repo on the Hub.
  5995. Args:
  5996. repo_id (`str`):
  5997. The repository in which a commit will be tagged.
  5998. Example: `"user/my-cool-model"`.
  5999. tag (`str`):
  6000. The name of the tag to create.
  6001. tag_message (`str`, *optional*):
  6002. The description of the tag to create.
  6003. revision (`str`, *optional*):
  6004. The git revision to tag. It can be a branch name or the OID/SHA of a
  6005. commit, as a hexadecimal string. Shorthands (7 first characters) are
  6006. also supported. Defaults to the head of the `"main"` branch.
  6007. token (`bool` or `str`, *optional*):
  6008. A valid user access token (string). Defaults to the locally saved
  6009. token, which is the recommended method for authentication (see
  6010. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6011. To disable authentication, pass `False`.
  6012. repo_type (`str`, *optional*):
  6013. Set to `"dataset"` or `"space"` if tagging a dataset or
  6014. space, `None` or `"model"` if tagging a model. Default is
  6015. `None`.
  6016. exist_ok (`bool`, *optional*, defaults to `False`):
  6017. If `True`, do not raise an error if tag already exists.
  6018. Raises:
  6019. [`~utils.RepositoryNotFoundError`]:
  6020. If repository is not found (error 404): wrong repo_id/repo_type, private
  6021. but not authenticated or repo does not exist.
  6022. [`~utils.RevisionNotFoundError`]:
  6023. If revision is not found (error 404) on the repo.
  6024. [`~utils.HfHubHTTPError`]:
  6025. If the branch already exists on the repo (error 409) and `exist_ok` is
  6026. set to `False`.
  6027. """
  6028. if repo_type is None:
  6029. repo_type = constants.REPO_TYPE_MODEL
  6030. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  6031. # Prepare request
  6032. tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{revision}"
  6033. headers = self._build_hf_headers(token=token)
  6034. payload = {"tag": tag}
  6035. if tag_message is not None:
  6036. payload["message"] = tag_message
  6037. # Tag
  6038. response = get_session().post(url=tag_url, headers=headers, json=payload)
  6039. try:
  6040. hf_raise_for_status(response)
  6041. except HfHubHTTPError as e:
  6042. if not (e.response.status_code == 409 and exist_ok):
  6043. raise
  6044. @validate_hf_hub_args
  6045. def delete_tag(
  6046. self,
  6047. repo_id: str,
  6048. *,
  6049. tag: str,
  6050. token: bool | str | None = None,
  6051. repo_type: str | None = None,
  6052. ) -> None:
  6053. """
  6054. Delete a tag from a repo on the Hub.
  6055. Args:
  6056. repo_id (`str`):
  6057. The repository in which a tag will be deleted.
  6058. Example: `"user/my-cool-model"`.
  6059. tag (`str`):
  6060. The name of the tag to delete.
  6061. token (`bool` or `str`, *optional*):
  6062. A valid user access token (string). Defaults to the locally saved
  6063. token, which is the recommended method for authentication (see
  6064. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6065. To disable authentication, pass `False`.
  6066. repo_type (`str`, *optional*):
  6067. Set to `"dataset"` or `"space"` if tagging a dataset or space, `None` or
  6068. `"model"` if tagging a model. Default is `None`.
  6069. Raises:
  6070. [`~utils.RepositoryNotFoundError`]:
  6071. If repository is not found (error 404): wrong repo_id/repo_type, private
  6072. but not authenticated or repo does not exist.
  6073. [`~utils.RevisionNotFoundError`]:
  6074. If tag is not found.
  6075. """
  6076. if repo_type is None:
  6077. repo_type = constants.REPO_TYPE_MODEL
  6078. tag = quote(tag, safe="")
  6079. # Prepare request
  6080. tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{tag}"
  6081. headers = self._build_hf_headers(token=token)
  6082. # Un-tag
  6083. response = get_session().delete(url=tag_url, headers=headers)
  6084. hf_raise_for_status(response)
  6085. @validate_hf_hub_args
  6086. def get_full_repo_name(
  6087. self,
  6088. model_id: str,
  6089. *,
  6090. organization: str | None = None,
  6091. token: bool | str | None = None,
  6092. ):
  6093. """
  6094. Returns the repository name for a given model ID and optional
  6095. organization.
  6096. Args:
  6097. model_id (`str`):
  6098. The name of the model.
  6099. organization (`str`, *optional*):
  6100. If passed, the repository name will be in the organization
  6101. namespace instead of the user namespace.
  6102. token (`bool` or `str`, *optional*):
  6103. A valid user access token (string). Defaults to the locally saved
  6104. token, which is the recommended method for authentication (see
  6105. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6106. To disable authentication, pass `False`.
  6107. Returns:
  6108. `str`: The repository name in the user's namespace
  6109. ({username}/{model_id}) if no organization is passed, and under the
  6110. organization namespace ({organization}/{model_id}) otherwise.
  6111. """
  6112. if organization is None:
  6113. if "/" in model_id:
  6114. username = model_id.split("/")[0]
  6115. else:
  6116. username = self.whoami(token=token)["name"] # type: ignore
  6117. return f"{username}/{model_id}"
  6118. else:
  6119. return f"{organization}/{model_id}"
  6120. @validate_hf_hub_args
  6121. def get_repo_discussions(
  6122. self,
  6123. repo_id: str,
  6124. *,
  6125. author: str | None = None,
  6126. discussion_type: constants.DiscussionTypeFilter | None = None,
  6127. discussion_status: constants.DiscussionStatusFilter | None = None,
  6128. repo_type: str | None = None,
  6129. token: bool | str | None = None,
  6130. ) -> Iterator[Discussion]:
  6131. """
  6132. Fetches Discussions and Pull Requests for the given repo.
  6133. Args:
  6134. repo_id (`str`):
  6135. A namespace (user or an organization) and a repo name separated
  6136. by a `/`.
  6137. author (`str`, *optional*):
  6138. Pass a value to filter by discussion author. `None` means no filter.
  6139. Default is `None`.
  6140. discussion_type (`str`, *optional*):
  6141. Set to `"pull_request"` to fetch only pull requests, `"discussion"`
  6142. to fetch only discussions. Set to `"all"` or `None` to fetch both.
  6143. Default is `None`.
  6144. discussion_status (`str`, *optional*):
  6145. Set to `"open"` (respectively `"closed"`) to fetch only open
  6146. (respectively closed) discussions. Set to `"all"` or `None`
  6147. to fetch both.
  6148. Default is `None`.
  6149. repo_type (`str`, *optional*):
  6150. Set to `"dataset"` or `"space"` if fetching from a dataset or
  6151. space, `None` or `"model"` if fetching from a model. Default is
  6152. `None`.
  6153. token (`bool` or `str`, *optional*):
  6154. A valid user access token (string). Defaults to the locally saved
  6155. token, which is the recommended method for authentication (see
  6156. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6157. To disable authentication, pass `False`.
  6158. Returns:
  6159. `Iterator[Discussion]`: An iterator of [`Discussion`] objects.
  6160. Example:
  6161. Collecting all discussions of a repo in a list:
  6162. ```python
  6163. >>> from huggingface_hub import get_repo_discussions
  6164. >>> discussions_list = list(get_repo_discussions(repo_id="bert-base-uncased"))
  6165. ```
  6166. Iterating over discussions of a repo:
  6167. ```python
  6168. >>> from huggingface_hub import get_repo_discussions
  6169. >>> for discussion in get_repo_discussions(repo_id="bert-base-uncased"):
  6170. ... print(discussion.num, discussion.title)
  6171. ```
  6172. """
  6173. if repo_type not in constants.REPO_TYPES:
  6174. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  6175. if repo_type is None:
  6176. repo_type = constants.REPO_TYPE_MODEL
  6177. if discussion_type is not None and discussion_type not in constants.DISCUSSION_TYPES:
  6178. raise ValueError(f"Invalid discussion_type, must be one of {constants.DISCUSSION_TYPES}")
  6179. if discussion_status is not None and discussion_status not in constants.DISCUSSION_STATUS:
  6180. raise ValueError(f"Invalid discussion_status, must be one of {constants.DISCUSSION_STATUS}")
  6181. headers = self._build_hf_headers(token=token)
  6182. path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions"
  6183. params: dict[str, str | int] = {}
  6184. if discussion_type is not None:
  6185. params["type"] = discussion_type
  6186. if discussion_status is not None:
  6187. params["status"] = discussion_status
  6188. if author is not None:
  6189. params["author"] = author
  6190. def _fetch_discussion_page(page_index: int):
  6191. params["p"] = page_index
  6192. resp = get_session().get(path, headers=headers, params=params)
  6193. hf_raise_for_status(resp)
  6194. paginated_discussions = resp.json()
  6195. total = paginated_discussions["count"]
  6196. start = paginated_discussions["start"]
  6197. discussions = paginated_discussions["discussions"]
  6198. has_next = (start + len(discussions)) < total
  6199. return discussions, has_next
  6200. has_next, page_index = True, 0
  6201. while has_next:
  6202. discussions, has_next = _fetch_discussion_page(page_index=page_index)
  6203. for discussion in discussions:
  6204. yield Discussion(
  6205. title=discussion["title"],
  6206. num=discussion["num"],
  6207. author=discussion.get("author", {}).get("name", "deleted"),
  6208. created_at=parse_datetime(discussion["createdAt"]),
  6209. status=discussion["status"],
  6210. repo_id=discussion["repo"]["name"],
  6211. repo_type=discussion["repo"]["type"],
  6212. is_pull_request=discussion["isPullRequest"],
  6213. endpoint=self.endpoint,
  6214. )
  6215. page_index = page_index + 1
  6216. @validate_hf_hub_args
  6217. def get_discussion_details(
  6218. self,
  6219. repo_id: str,
  6220. discussion_num: int,
  6221. *,
  6222. repo_type: str | None = None,
  6223. token: bool | str | None = None,
  6224. ) -> DiscussionWithDetails:
  6225. """Fetches a Discussion's / Pull Request 's details from the Hub.
  6226. Args:
  6227. repo_id (`str`):
  6228. A namespace (user or an organization) and a repo name separated
  6229. by a `/`.
  6230. discussion_num (`int`):
  6231. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6232. repo_type (`str`, *optional*):
  6233. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6234. space, `None` or `"model"` if uploading to a model. Default is
  6235. `None`.
  6236. token (`bool` or `str`, *optional*):
  6237. A valid user access token (string). Defaults to the locally saved
  6238. token, which is the recommended method for authentication (see
  6239. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6240. To disable authentication, pass `False`.
  6241. Returns: [`DiscussionWithDetails`]
  6242. > [!TIP]
  6243. > Raises the following errors:
  6244. >
  6245. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6246. > if the HuggingFace API returned an error
  6247. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6248. > if some parameter value is invalid
  6249. > - [`~utils.RepositoryNotFoundError`]
  6250. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6251. > or because it is set to `private` and you do not have access.
  6252. """
  6253. if not isinstance(discussion_num, int) or discussion_num <= 0:
  6254. raise ValueError("Invalid discussion_num, must be a positive integer")
  6255. if repo_type not in constants.REPO_TYPES:
  6256. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  6257. if repo_type is None:
  6258. repo_type = constants.REPO_TYPE_MODEL
  6259. path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions/{discussion_num}"
  6260. headers = self._build_hf_headers(token=token)
  6261. resp = get_session().get(path, params={"diff": "1"}, headers=headers)
  6262. hf_raise_for_status(resp)
  6263. discussion_details = resp.json()
  6264. is_pull_request = discussion_details["isPullRequest"]
  6265. target_branch = discussion_details["changes"]["base"] if is_pull_request else None
  6266. conflicting_files = discussion_details["filesWithConflicts"] if is_pull_request else None
  6267. merge_commit_oid = discussion_details["changes"].get("mergeCommitId", None) if is_pull_request else None
  6268. return DiscussionWithDetails(
  6269. title=discussion_details["title"],
  6270. num=discussion_details["num"],
  6271. author=discussion_details.get("author", {}).get("name", "deleted"),
  6272. created_at=parse_datetime(discussion_details["createdAt"]),
  6273. status=discussion_details["status"],
  6274. repo_id=discussion_details["repo"]["name"],
  6275. repo_type=discussion_details["repo"]["type"],
  6276. is_pull_request=discussion_details["isPullRequest"],
  6277. events=[deserialize_event(evt) for evt in discussion_details["events"]],
  6278. conflicting_files=conflicting_files,
  6279. target_branch=target_branch,
  6280. merge_commit_oid=merge_commit_oid,
  6281. diff=discussion_details.get("diff"),
  6282. endpoint=self.endpoint,
  6283. )
  6284. @validate_hf_hub_args
  6285. def create_discussion(
  6286. self,
  6287. repo_id: str,
  6288. title: str,
  6289. *,
  6290. token: bool | str | None = None,
  6291. description: str | None = None,
  6292. repo_type: str | None = None,
  6293. pull_request: bool = False,
  6294. ) -> DiscussionWithDetails:
  6295. """Creates a Discussion or Pull Request.
  6296. Pull Requests created programmatically will be in `"draft"` status.
  6297. Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`].
  6298. Args:
  6299. repo_id (`str`):
  6300. A namespace (user or an organization) and a repo name separated
  6301. by a `/`.
  6302. title (`str`):
  6303. The title of the discussion. It can be up to 200 characters long,
  6304. and must be at least 3 characters long. Leading and trailing whitespaces
  6305. will be stripped.
  6306. token (`bool` or `str`, *optional*):
  6307. A valid user access token (string). Defaults to the locally saved
  6308. token, which is the recommended method for authentication (see
  6309. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6310. To disable authentication, pass `False`.
  6311. description (`str`, *optional*):
  6312. An optional description for the Pull Request.
  6313. Defaults to `"Discussion opened with the huggingface_hub Python library"`
  6314. pull_request (`bool`, *optional*):
  6315. Whether to create a Pull Request or discussion. If `True`, creates a Pull Request.
  6316. If `False`, creates a discussion. Defaults to `False`.
  6317. repo_type (`str`, *optional*):
  6318. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6319. space, `None` or `"model"` if uploading to a model. Default is
  6320. `None`.
  6321. Returns: [`DiscussionWithDetails`]
  6322. > [!TIP]
  6323. > Raises the following errors:
  6324. >
  6325. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6326. > if the HuggingFace API returned an error
  6327. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6328. > if some parameter value is invalid
  6329. > - [`~utils.RepositoryNotFoundError`]
  6330. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6331. > or because it is set to `private` and you do not have access."""
  6332. if repo_type not in constants.REPO_TYPES:
  6333. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  6334. if repo_type is None:
  6335. repo_type = constants.REPO_TYPE_MODEL
  6336. if description is not None:
  6337. description = description.strip()
  6338. description = (
  6339. description
  6340. if description
  6341. else (
  6342. f"{'Pull Request' if pull_request else 'Discussion'} opened with the"
  6343. " [huggingface_hub Python"
  6344. " library](https://huggingface.co/docs/huggingface_hub)"
  6345. )
  6346. )
  6347. headers = self._build_hf_headers(token=token)
  6348. resp = get_session().post(
  6349. f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions",
  6350. json={
  6351. "title": title.strip(),
  6352. "description": description,
  6353. "pullRequest": pull_request,
  6354. },
  6355. headers=headers,
  6356. )
  6357. hf_raise_for_status(resp)
  6358. num = resp.json()["num"]
  6359. return self.get_discussion_details(
  6360. repo_id=repo_id,
  6361. repo_type=repo_type,
  6362. discussion_num=num,
  6363. token=token,
  6364. )
  6365. @validate_hf_hub_args
  6366. def create_pull_request(
  6367. self,
  6368. repo_id: str,
  6369. title: str,
  6370. *,
  6371. token: bool | str | None = None,
  6372. description: str | None = None,
  6373. repo_type: str | None = None,
  6374. ) -> DiscussionWithDetails:
  6375. """Creates a Pull Request . Pull Requests created programmatically will be in `"draft"` status.
  6376. Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`];
  6377. This is a wrapper around [`HfApi.create_discussion`].
  6378. Args:
  6379. repo_id (`str`):
  6380. A namespace (user or an organization) and a repo name separated
  6381. by a `/`.
  6382. title (`str`):
  6383. The title of the discussion. It can be up to 200 characters long,
  6384. and must be at least 3 characters long. Leading and trailing whitespaces
  6385. will be stripped.
  6386. token (`bool` or `str`, *optional*):
  6387. A valid user access token (string). Defaults to the locally saved
  6388. token, which is the recommended method for authentication (see
  6389. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6390. To disable authentication, pass `False`.
  6391. description (`str`, *optional*):
  6392. An optional description for the Pull Request.
  6393. Defaults to `"Discussion opened with the huggingface_hub Python library"`
  6394. repo_type (`str`, *optional*):
  6395. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6396. space, `None` or `"model"` if uploading to a model. Default is
  6397. `None`.
  6398. Returns: [`DiscussionWithDetails`]
  6399. > [!TIP]
  6400. > Raises the following errors:
  6401. >
  6402. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6403. > if the HuggingFace API returned an error
  6404. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6405. > if some parameter value is invalid
  6406. > - [`~utils.RepositoryNotFoundError`]
  6407. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6408. > or because it is set to `private` and you do not have access."""
  6409. return self.create_discussion(
  6410. repo_id=repo_id,
  6411. title=title,
  6412. token=token,
  6413. description=description,
  6414. repo_type=repo_type,
  6415. pull_request=True,
  6416. )
  6417. def _post_discussion_changes(
  6418. self,
  6419. *,
  6420. repo_id: str,
  6421. discussion_num: int,
  6422. resource: str,
  6423. body: dict | None = None,
  6424. token: bool | str | None = None,
  6425. repo_type: str | None = None,
  6426. ) -> httpx.Response:
  6427. """Internal utility to POST changes to a Discussion or Pull Request"""
  6428. if not isinstance(discussion_num, int) or discussion_num <= 0:
  6429. raise ValueError("Invalid discussion_num, must be a positive integer")
  6430. if repo_type not in constants.REPO_TYPES:
  6431. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  6432. if repo_type is None:
  6433. repo_type = constants.REPO_TYPE_MODEL
  6434. repo_id = f"{repo_type}s/{repo_id}"
  6435. path = f"{self.endpoint}/api/{repo_id}/discussions/{discussion_num}/{resource}"
  6436. headers = self._build_hf_headers(token=token)
  6437. resp = get_session().post(path, headers=headers, json=body)
  6438. hf_raise_for_status(resp)
  6439. return resp
  6440. @validate_hf_hub_args
  6441. def comment_discussion(
  6442. self,
  6443. repo_id: str,
  6444. discussion_num: int,
  6445. comment: str,
  6446. *,
  6447. token: bool | str | None = None,
  6448. repo_type: str | None = None,
  6449. ) -> DiscussionComment:
  6450. """Creates a new comment on the given Discussion.
  6451. Args:
  6452. repo_id (`str`):
  6453. A namespace (user or an organization) and a repo name separated
  6454. by a `/`.
  6455. discussion_num (`int`):
  6456. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6457. comment (`str`):
  6458. The content of the comment to create. Comments support markdown formatting.
  6459. repo_type (`str`, *optional*):
  6460. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6461. space, `None` or `"model"` if uploading to a model. Default is
  6462. `None`.
  6463. token (`bool` or `str`, *optional*):
  6464. A valid user access token (string). Defaults to the locally saved
  6465. token, which is the recommended method for authentication (see
  6466. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6467. To disable authentication, pass `False`.
  6468. Returns:
  6469. [`DiscussionComment`]: the newly created comment
  6470. Examples:
  6471. ```python
  6472. >>> comment = \"\"\"
  6473. ... Hello @otheruser!
  6474. ...
  6475. ... # This is a title
  6476. ...
  6477. ... **This is bold**, *this is italic* and ~this is strikethrough~
  6478. ... And [this](http://url) is a link
  6479. ... \"\"\"
  6480. >>> HfApi().comment_discussion(
  6481. ... repo_id="username/repo_name",
  6482. ... discussion_num=34
  6483. ... comment=comment
  6484. ... )
  6485. # DiscussionComment(id='deadbeef0000000', type='comment', ...)
  6486. ```
  6487. > [!TIP]
  6488. > Raises the following errors:
  6489. >
  6490. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6491. > if the HuggingFace API returned an error
  6492. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6493. > if some parameter value is invalid
  6494. > - [`~utils.RepositoryNotFoundError`]
  6495. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6496. > or because it is set to `private` and you do not have access.
  6497. """
  6498. resp = self._post_discussion_changes(
  6499. repo_id=repo_id,
  6500. repo_type=repo_type,
  6501. discussion_num=discussion_num,
  6502. token=token,
  6503. resource="comment",
  6504. body={"comment": comment},
  6505. )
  6506. return deserialize_event(resp.json()["newMessage"]) # type: ignore
  6507. @validate_hf_hub_args
  6508. def rename_discussion(
  6509. self,
  6510. repo_id: str,
  6511. discussion_num: int,
  6512. new_title: str,
  6513. *,
  6514. token: bool | str | None = None,
  6515. repo_type: str | None = None,
  6516. ) -> DiscussionTitleChange:
  6517. """Renames a Discussion.
  6518. Args:
  6519. repo_id (`str`):
  6520. A namespace (user or an organization) and a repo name separated
  6521. by a `/`.
  6522. discussion_num (`int`):
  6523. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6524. new_title (`str`):
  6525. The new title for the discussion
  6526. repo_type (`str`, *optional*):
  6527. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6528. space, `None` or `"model"` if uploading to a model. Default is
  6529. `None`.
  6530. token (`bool` or `str`, *optional*):
  6531. A valid user access token (string). Defaults to the locally saved
  6532. token, which is the recommended method for authentication (see
  6533. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6534. To disable authentication, pass `False`.
  6535. Returns:
  6536. [`DiscussionTitleChange`]: the title change event
  6537. Examples:
  6538. ```python
  6539. >>> new_title = "New title, fixing a typo"
  6540. >>> HfApi().rename_discussion(
  6541. ... repo_id="username/repo_name",
  6542. ... discussion_num=34
  6543. ... new_title=new_title
  6544. ... )
  6545. # DiscussionTitleChange(id='deadbeef0000000', type='title-change', ...)
  6546. ```
  6547. > [!TIP]
  6548. > Raises the following errors:
  6549. >
  6550. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6551. > if the HuggingFace API returned an error
  6552. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6553. > if some parameter value is invalid
  6554. > - [`~utils.RepositoryNotFoundError`]
  6555. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6556. > or because it is set to `private` and you do not have access.
  6557. """
  6558. resp = self._post_discussion_changes(
  6559. repo_id=repo_id,
  6560. repo_type=repo_type,
  6561. discussion_num=discussion_num,
  6562. token=token,
  6563. resource="title",
  6564. body={"title": new_title},
  6565. )
  6566. return deserialize_event(resp.json()["newTitle"]) # type: ignore
  6567. @validate_hf_hub_args
  6568. def change_discussion_status(
  6569. self,
  6570. repo_id: str,
  6571. discussion_num: int,
  6572. new_status: Literal["open", "closed"],
  6573. *,
  6574. token: bool | str | None = None,
  6575. comment: str | None = None,
  6576. repo_type: str | None = None,
  6577. ) -> DiscussionStatusChange:
  6578. """Closes or re-opens a Discussion or Pull Request.
  6579. Args:
  6580. repo_id (`str`):
  6581. A namespace (user or an organization) and a repo name separated
  6582. by a `/`.
  6583. discussion_num (`int`):
  6584. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6585. new_status (`str`):
  6586. The new status for the discussion, either `"open"` or `"closed"`.
  6587. comment (`str`, *optional*):
  6588. An optional comment to post with the status change.
  6589. repo_type (`str`, *optional*):
  6590. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6591. space, `None` or `"model"` if uploading to a model. Default is
  6592. `None`.
  6593. token (`bool` or `str`, *optional*):
  6594. A valid user access token (string). Defaults to the locally saved
  6595. token, which is the recommended method for authentication (see
  6596. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6597. To disable authentication, pass `False`.
  6598. Returns:
  6599. [`DiscussionStatusChange`]: the status change event
  6600. Examples:
  6601. ```python
  6602. >>> new_title = "New title, fixing a typo"
  6603. >>> HfApi().rename_discussion(
  6604. ... repo_id="username/repo_name",
  6605. ... discussion_num=34
  6606. ... new_title=new_title
  6607. ... )
  6608. # DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...)
  6609. ```
  6610. > [!TIP]
  6611. > Raises the following errors:
  6612. >
  6613. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6614. > if the HuggingFace API returned an error
  6615. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6616. > if some parameter value is invalid
  6617. > - [`~utils.RepositoryNotFoundError`]
  6618. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6619. > or because it is set to `private` and you do not have access.
  6620. """
  6621. if new_status not in ["open", "closed"]:
  6622. raise ValueError("Invalid status, valid statuses are: 'open' and 'closed'")
  6623. body: dict[str, str] = {"status": new_status}
  6624. if comment and comment.strip():
  6625. body["comment"] = comment.strip()
  6626. resp = self._post_discussion_changes(
  6627. repo_id=repo_id,
  6628. repo_type=repo_type,
  6629. discussion_num=discussion_num,
  6630. token=token,
  6631. resource="status",
  6632. body=body,
  6633. )
  6634. return deserialize_event(resp.json()["newStatus"]) # type: ignore
  6635. @validate_hf_hub_args
  6636. def merge_pull_request(
  6637. self,
  6638. repo_id: str,
  6639. discussion_num: int,
  6640. *,
  6641. token: bool | str | None = None,
  6642. comment: str | None = None,
  6643. repo_type: str | None = None,
  6644. ):
  6645. """Merges a Pull Request.
  6646. Args:
  6647. repo_id (`str`):
  6648. A namespace (user or an organization) and a repo name separated
  6649. by a `/`.
  6650. discussion_num (`int`):
  6651. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6652. comment (`str`, *optional*):
  6653. An optional comment to post with the status change.
  6654. repo_type (`str`, *optional*):
  6655. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6656. space, `None` or `"model"` if uploading to a model. Default is
  6657. `None`.
  6658. token (`bool` or `str`, *optional*):
  6659. A valid user access token (string). Defaults to the locally saved
  6660. token, which is the recommended method for authentication (see
  6661. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6662. To disable authentication, pass `False`.
  6663. Returns:
  6664. [`DiscussionStatusChange`]: the status change event
  6665. > [!TIP]
  6666. > Raises the following errors:
  6667. >
  6668. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6669. > if the HuggingFace API returned an error
  6670. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6671. > if some parameter value is invalid
  6672. > - [`~utils.RepositoryNotFoundError`]
  6673. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6674. > or because it is set to `private` and you do not have access.
  6675. """
  6676. self._post_discussion_changes(
  6677. repo_id=repo_id,
  6678. repo_type=repo_type,
  6679. discussion_num=discussion_num,
  6680. token=token,
  6681. resource="merge",
  6682. body={"comment": comment.strip()} if comment and comment.strip() else None,
  6683. )
  6684. @validate_hf_hub_args
  6685. def edit_discussion_comment(
  6686. self,
  6687. repo_id: str,
  6688. discussion_num: int,
  6689. comment_id: str,
  6690. new_content: str,
  6691. *,
  6692. token: bool | str | None = None,
  6693. repo_type: str | None = None,
  6694. ) -> DiscussionComment:
  6695. """Edits a comment on a Discussion / Pull Request.
  6696. Args:
  6697. repo_id (`str`):
  6698. A namespace (user or an organization) and a repo name separated
  6699. by a `/`.
  6700. discussion_num (`int`):
  6701. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6702. comment_id (`str`):
  6703. The ID of the comment to edit.
  6704. new_content (`str`):
  6705. The new content of the comment. Comments support markdown formatting.
  6706. repo_type (`str`, *optional*):
  6707. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6708. space, `None` or `"model"` if uploading to a model. Default is
  6709. `None`.
  6710. token (`bool` or `str`, *optional*):
  6711. A valid user access token (string). Defaults to the locally saved
  6712. token, which is the recommended method for authentication (see
  6713. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6714. To disable authentication, pass `False`.
  6715. Returns:
  6716. [`DiscussionComment`]: the edited comment
  6717. > [!TIP]
  6718. > Raises the following errors:
  6719. >
  6720. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6721. > if the HuggingFace API returned an error
  6722. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6723. > if some parameter value is invalid
  6724. > - [`~utils.RepositoryNotFoundError`]
  6725. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6726. > or because it is set to `private` and you do not have access.
  6727. """
  6728. resp = self._post_discussion_changes(
  6729. repo_id=repo_id,
  6730. repo_type=repo_type,
  6731. discussion_num=discussion_num,
  6732. token=token,
  6733. resource=f"comment/{comment_id.lower()}/edit",
  6734. body={"content": new_content},
  6735. )
  6736. return deserialize_event(resp.json()["updatedComment"]) # type: ignore
  6737. @validate_hf_hub_args
  6738. def hide_discussion_comment(
  6739. self,
  6740. repo_id: str,
  6741. discussion_num: int,
  6742. comment_id: str,
  6743. *,
  6744. token: bool | str | None = None,
  6745. repo_type: str | None = None,
  6746. ) -> DiscussionComment:
  6747. """Hides a comment on a Discussion / Pull Request.
  6748. > [!WARNING]
  6749. > Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.
  6750. Args:
  6751. repo_id (`str`):
  6752. A namespace (user or an organization) and a repo name separated
  6753. by a `/`.
  6754. discussion_num (`int`):
  6755. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6756. comment_id (`str`):
  6757. The ID of the comment to edit.
  6758. repo_type (`str`, *optional*):
  6759. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6760. space, `None` or `"model"` if uploading to a model. Default is
  6761. `None`.
  6762. token (`bool` or `str`, *optional*):
  6763. A valid user access token (string). Defaults to the locally saved
  6764. token, which is the recommended method for authentication (see
  6765. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6766. To disable authentication, pass `False`.
  6767. Returns:
  6768. [`DiscussionComment`]: the hidden comment
  6769. > [!TIP]
  6770. > Raises the following errors:
  6771. >
  6772. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6773. > if the HuggingFace API returned an error
  6774. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6775. > if some parameter value is invalid
  6776. > - [`~utils.RepositoryNotFoundError`]
  6777. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6778. > or because it is set to `private` and you do not have access.
  6779. """
  6780. warnings.warn(
  6781. "Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.",
  6782. UserWarning,
  6783. )
  6784. resp = self._post_discussion_changes(
  6785. repo_id=repo_id,
  6786. repo_type=repo_type,
  6787. discussion_num=discussion_num,
  6788. token=token,
  6789. resource=f"comment/{comment_id.lower()}/hide",
  6790. )
  6791. return deserialize_event(resp.json()["updatedComment"]) # type: ignore
  6792. @validate_hf_hub_args
  6793. def add_space_secret(
  6794. self,
  6795. repo_id: str,
  6796. key: str,
  6797. value: str,
  6798. *,
  6799. description: str | None = None,
  6800. token: bool | str | None = None,
  6801. ) -> None:
  6802. """Adds or updates a secret in a Space.
  6803. Secrets allow to set secret keys or tokens to a Space without hardcoding them.
  6804. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  6805. Args:
  6806. repo_id (`str`):
  6807. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6808. key (`str`):
  6809. Secret key. Example: `"GITHUB_API_KEY"`
  6810. value (`str`):
  6811. Secret value. Example: `"your_github_api_key"`.
  6812. description (`str`, *optional*):
  6813. Secret description. Example: `"Github API key to access the Github API"`.
  6814. token (`bool` or `str`, *optional*):
  6815. A valid user access token (string). Defaults to the locally saved
  6816. token, which is the recommended method for authentication (see
  6817. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6818. To disable authentication, pass `False`.
  6819. """
  6820. payload = {"key": key, "value": value}
  6821. if description is not None:
  6822. payload["description"] = description
  6823. r = get_session().post(
  6824. f"{self.endpoint}/api/spaces/{repo_id}/secrets",
  6825. headers=self._build_hf_headers(token=token),
  6826. json=payload,
  6827. )
  6828. hf_raise_for_status(r)
  6829. @validate_hf_hub_args
  6830. def delete_space_secret(self, repo_id: str, key: str, *, token: bool | str | None = None) -> None:
  6831. """Deletes a secret from a Space.
  6832. Secrets allow to set secret keys or tokens to a Space without hardcoding them.
  6833. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  6834. Args:
  6835. repo_id (`str`):
  6836. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6837. key (`str`):
  6838. Secret key. Example: `"GITHUB_API_KEY"`.
  6839. token (`bool` or `str`, *optional*):
  6840. A valid user access token (string). Defaults to the locally saved
  6841. token, which is the recommended method for authentication (see
  6842. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6843. To disable authentication, pass `False`.
  6844. """
  6845. r = get_session().request(
  6846. "DELETE",
  6847. f"{self.endpoint}/api/spaces/{repo_id}/secrets",
  6848. headers=self._build_hf_headers(token=token),
  6849. json={"key": key},
  6850. )
  6851. hf_raise_for_status(r)
  6852. @validate_hf_hub_args
  6853. def get_space_variables(self, repo_id: str, *, token: bool | str | None = None) -> dict[str, SpaceVariable]:
  6854. """Gets all variables from a Space.
  6855. Variables allow to set environment variables to a Space without hardcoding them.
  6856. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
  6857. Args:
  6858. repo_id (`str`):
  6859. ID of the repo to query. Example: `"bigcode/in-the-stack"`.
  6860. token (`bool` or `str`, *optional*):
  6861. A valid user access token (string). Defaults to the locally saved
  6862. token, which is the recommended method for authentication (see
  6863. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6864. To disable authentication, pass `False`.
  6865. """
  6866. r = get_session().get(
  6867. f"{self.endpoint}/api/spaces/{repo_id}/variables",
  6868. headers=self._build_hf_headers(token=token),
  6869. )
  6870. hf_raise_for_status(r)
  6871. return {k: SpaceVariable(k, v) for k, v in r.json().items()}
  6872. @validate_hf_hub_args
  6873. def add_space_variable(
  6874. self,
  6875. repo_id: str,
  6876. key: str,
  6877. value: str,
  6878. *,
  6879. description: str | None = None,
  6880. token: bool | str | None = None,
  6881. ) -> dict[str, SpaceVariable]:
  6882. """Adds or updates a variable in a Space.
  6883. Variables allow to set environment variables to a Space without hardcoding them.
  6884. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
  6885. Args:
  6886. repo_id (`str`):
  6887. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6888. key (`str`):
  6889. Variable key. Example: `"MODEL_REPO_ID"`
  6890. value (`str`):
  6891. Variable value. Example: `"the_model_repo_id"`.
  6892. description (`str`):
  6893. Description of the variable. Example: `"Model Repo ID of the implemented model"`.
  6894. token (`bool` or `str`, *optional*):
  6895. A valid user access token (string). Defaults to the locally saved
  6896. token, which is the recommended method for authentication (see
  6897. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6898. To disable authentication, pass `False`.
  6899. """
  6900. payload = {"key": key, "value": value}
  6901. if description is not None:
  6902. payload["description"] = description
  6903. r = get_session().post(
  6904. f"{self.endpoint}/api/spaces/{repo_id}/variables",
  6905. headers=self._build_hf_headers(token=token),
  6906. json=payload,
  6907. )
  6908. hf_raise_for_status(r)
  6909. return {k: SpaceVariable(k, v) for k, v in r.json().items()}
  6910. @validate_hf_hub_args
  6911. def delete_space_variable(
  6912. self, repo_id: str, key: str, *, token: bool | str | None = None
  6913. ) -> dict[str, SpaceVariable]:
  6914. """Deletes a variable from a Space.
  6915. Variables allow to set environment variables to a Space without hardcoding them.
  6916. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
  6917. Args:
  6918. repo_id (`str`):
  6919. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6920. key (`str`):
  6921. Variable key. Example: `"MODEL_REPO_ID"`
  6922. token (`bool` or `str`, *optional*):
  6923. A valid user access token (string). Defaults to the locally saved
  6924. token, which is the recommended method for authentication (see
  6925. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6926. To disable authentication, pass `False`.
  6927. """
  6928. r = get_session().request(
  6929. "DELETE",
  6930. f"{self.endpoint}/api/spaces/{repo_id}/variables",
  6931. headers=self._build_hf_headers(token=token),
  6932. json={"key": key},
  6933. )
  6934. hf_raise_for_status(r)
  6935. return {k: SpaceVariable(k, v) for k, v in r.json().items()}
  6936. @validate_hf_hub_args
  6937. def get_space_runtime(self, repo_id: str, *, token: bool | str | None = None) -> SpaceRuntime:
  6938. """Gets runtime information about a Space.
  6939. Args:
  6940. repo_id (`str`):
  6941. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6942. token (`bool` or `str`, *optional*):
  6943. A valid user access token (string). Defaults to the locally saved
  6944. token, which is the recommended method for authentication (see
  6945. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6946. To disable authentication, pass `False`.
  6947. Returns:
  6948. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  6949. """
  6950. r = get_session().get(
  6951. f"{self.endpoint}/api/spaces/{repo_id}/runtime", headers=self._build_hf_headers(token=token)
  6952. )
  6953. hf_raise_for_status(r)
  6954. return SpaceRuntime(r.json())
  6955. @validate_hf_hub_args
  6956. def request_space_hardware(
  6957. self,
  6958. repo_id: str,
  6959. hardware: SpaceHardware,
  6960. *,
  6961. token: bool | str | None = None,
  6962. sleep_time: int | None = None,
  6963. ) -> SpaceRuntime:
  6964. """Request new hardware for a Space.
  6965. Args:
  6966. repo_id (`str`):
  6967. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6968. hardware (`str` or [`SpaceHardware`]):
  6969. Hardware on which to run the Space. Example: `"t4-medium"`.
  6970. token (`bool` or `str`, *optional*):
  6971. A valid user access token (string). Defaults to the locally saved
  6972. token, which is the recommended method for authentication (see
  6973. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6974. To disable authentication, pass `False`.
  6975. sleep_time (`int`, *optional*):
  6976. Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
  6977. your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
  6978. the sleep time (value is fixed to 48 hours of inactivity).
  6979. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  6980. Returns:
  6981. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  6982. > [!TIP]
  6983. > It is also possible to request hardware directly when creating the Space repo! See [`create_repo`] for details.
  6984. """
  6985. if sleep_time is not None and hardware == SpaceHardware.CPU_BASIC:
  6986. warnings.warn(
  6987. "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
  6988. " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
  6989. " you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
  6990. UserWarning,
  6991. )
  6992. payload: dict[str, Any] = {"flavor": hardware}
  6993. if sleep_time is not None:
  6994. payload["sleepTimeSeconds"] = sleep_time
  6995. r = get_session().post(
  6996. f"{self.endpoint}/api/spaces/{repo_id}/hardware",
  6997. headers=self._build_hf_headers(token=token),
  6998. json=payload,
  6999. )
  7000. hf_raise_for_status(r)
  7001. return SpaceRuntime(r.json())
  7002. @validate_hf_hub_args
  7003. def set_space_sleep_time(self, repo_id: str, sleep_time: int, *, token: bool | str | None = None) -> SpaceRuntime:
  7004. """Set a custom sleep time for a Space running on upgraded hardware..
  7005. Your Space will go to sleep after X seconds of inactivity. You are not billed when your Space is in "sleep"
  7006. mode. If a new visitor lands on your Space, it will "wake it up". Only upgraded hardware can have a
  7007. configurable sleep time. To know more about the sleep stage, please refer to
  7008. https://huggingface.co/docs/hub/spaces-gpus#sleep-time.
  7009. Args:
  7010. repo_id (`str`):
  7011. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  7012. sleep_time (`int`, *optional*):
  7013. Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
  7014. your Space to pause (default behavior for upgraded hardware). For free hardware, you can't configure
  7015. the sleep time (value is fixed to 48 hours of inactivity).
  7016. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  7017. token (`bool` or `str`, *optional*):
  7018. A valid user access token (string). Defaults to the locally saved
  7019. token, which is the recommended method for authentication (see
  7020. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7021. To disable authentication, pass `False`.
  7022. Returns:
  7023. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  7024. > [!TIP]
  7025. > It is also possible to set a custom sleep time when requesting hardware with [`request_space_hardware`].
  7026. """
  7027. r = get_session().post(
  7028. f"{self.endpoint}/api/spaces/{repo_id}/sleeptime",
  7029. headers=self._build_hf_headers(token=token),
  7030. json={"seconds": sleep_time},
  7031. )
  7032. hf_raise_for_status(r)
  7033. runtime = SpaceRuntime(r.json())
  7034. hardware = runtime.requested_hardware or runtime.hardware
  7035. if hardware == SpaceHardware.CPU_BASIC:
  7036. warnings.warn(
  7037. "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
  7038. " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
  7039. " you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
  7040. UserWarning,
  7041. )
  7042. return runtime
  7043. @validate_hf_hub_args
  7044. def pause_space(self, repo_id: str, *, token: bool | str | None = None) -> SpaceRuntime:
  7045. """Pause your Space.
  7046. A paused Space stops executing until manually restarted by its owner. This is different from the sleeping
  7047. state in which free Spaces go after 48h of inactivity. Paused time is not billed to your account, no matter the
  7048. hardware you've selected. To restart your Space, use [`restart_space`] and go to your Space settings page.
  7049. For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause).
  7050. Args:
  7051. repo_id (`str`):
  7052. ID of the Space to pause. Example: `"Salesforce/BLIP2"`.
  7053. token (`bool` or `str`, *optional*):
  7054. A valid user access token (string). Defaults to the locally saved
  7055. token, which is the recommended method for authentication (see
  7056. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7057. To disable authentication, pass `False`.
  7058. Returns:
  7059. [`SpaceRuntime`]: Runtime information about your Space including `stage=PAUSED` and requested hardware.
  7060. Raises:
  7061. [`~utils.RepositoryNotFoundError`]:
  7062. If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
  7063. are not authenticated.
  7064. [`~utils.HfHubHTTPError`]:
  7065. 403 Forbidden: only the owner of a Space can pause it. If you want to manage a Space that you don't
  7066. own, either ask the owner by opening a Discussion or duplicate the Space.
  7067. [`~utils.BadRequestError`]:
  7068. If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
  7069. a static Space, you can set it to private.
  7070. """
  7071. r = get_session().post(
  7072. f"{self.endpoint}/api/spaces/{repo_id}/pause", headers=self._build_hf_headers(token=token)
  7073. )
  7074. hf_raise_for_status(r)
  7075. return SpaceRuntime(r.json())
  7076. @validate_hf_hub_args
  7077. def enable_space_dev_mode(self, repo_id: str, *, token: bool | str | None = None) -> SpaceRuntime:
  7078. """Enable dev mode on a Space.
  7079. Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you
  7080. to restart your application without stopping the Space container itself. This feature is available as part of
  7081. a PRO or Team & Enterprise plan. See https://huggingface.co/docs/hub/spaces-dev-mode for more details.
  7082. Args:
  7083. repo_id (`str`):
  7084. ID of the Space to enable dev mode. Example: `"Salesforce/BLIP2"`.
  7085. token (`bool` or `str`, *optional*):
  7086. A valid user access token (string). Defaults to the locally saved
  7087. token, which is the recommended method for authentication (see
  7088. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7089. To disable authentication, pass `False`.
  7090. Returns:
  7091. [`SpaceRuntime`]: Runtime information about your Space.
  7092. Raises:
  7093. [`~utils.RepositoryNotFoundError`]:
  7094. If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
  7095. are not authenticated.
  7096. [`~utils.HfHubHTTPError`]:
  7097. 403 Forbidden: only the owner of a Space can set dev mode. If you want to handle a Space that you don't
  7098. own, either ask the owner by opening a Discussion or duplicate the Space.
  7099. [`~utils.BadRequestError`]:
  7100. If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
  7101. a static Space, you can set it to private.
  7102. """
  7103. r = get_session().post(
  7104. f"{self.endpoint}/api/spaces/{repo_id}/dev-mode",
  7105. headers=self._build_hf_headers(token=token),
  7106. json={"enabled": True},
  7107. )
  7108. hf_raise_for_status(r)
  7109. return SpaceRuntime(r.json())
  7110. @validate_hf_hub_args
  7111. def disable_space_dev_mode(
  7112. self,
  7113. repo_id: str,
  7114. *,
  7115. token: bool | str | None = None,
  7116. ) -> SpaceRuntime:
  7117. """Disable dev mode on a Space.
  7118. Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you
  7119. to restart your application without stopping the Space container itself. This feature is available as part of
  7120. a PRO or Team & Enterprise plan. See https://huggingface.co/docs/hub/spaces-dev-mode for more details.
  7121. Args:
  7122. repo_id (`str`):
  7123. ID of the Space to disable dev mode. Example: `"Salesforce/BLIP2"`.
  7124. token (`bool` or `str`, *optional*):
  7125. A valid user access token (string). Defaults to the locally saved
  7126. token, which is the recommended method for authentication (see
  7127. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7128. To disable authentication, pass `False`.
  7129. Returns:
  7130. [`SpaceRuntime`]: Runtime information about your Space.
  7131. Raises:
  7132. [`~utils.RepositoryNotFoundError`]:
  7133. If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
  7134. are not authenticated.
  7135. [`~utils.HfHubHTTPError`]:
  7136. 403 Forbidden: only the owner of a Space can set dev mode. If you want to handle a Space that you don't
  7137. own, either ask the owner by opening a Discussion or duplicate the Space.
  7138. [`~utils.BadRequestError`]:
  7139. If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
  7140. a static Space, you can set it to private.
  7141. """
  7142. r = get_session().post(
  7143. f"{self.endpoint}/api/spaces/{repo_id}/dev-mode",
  7144. headers=self._build_hf_headers(token=token),
  7145. json={"enabled": False},
  7146. )
  7147. hf_raise_for_status(r)
  7148. return SpaceRuntime(r.json())
  7149. @validate_hf_hub_args
  7150. def restart_space(
  7151. self, repo_id: str, *, token: bool | str | None = None, factory_reboot: bool = False
  7152. ) -> SpaceRuntime:
  7153. """Restart your Space.
  7154. This is the only way to programmatically restart a Space if you've put it on Pause (see [`pause_space`]). You
  7155. must be the owner of the Space to restart it. If you are using an upgraded hardware, your account will be
  7156. billed as soon as the Space is restarted. You can trigger a restart no matter the current state of a Space.
  7157. For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause).
  7158. Args:
  7159. repo_id (`str`):
  7160. ID of the Space to restart. Example: `"Salesforce/BLIP2"`.
  7161. token (`bool` or `str`, *optional*):
  7162. A valid user access token (string). Defaults to the locally saved
  7163. token, which is the recommended method for authentication (see
  7164. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7165. To disable authentication, pass `False`.
  7166. factory_reboot (`bool`, *optional*):
  7167. If `True`, the Space will be rebuilt from scratch without caching any requirements.
  7168. Returns:
  7169. [`SpaceRuntime`]: Runtime information about your Space.
  7170. Raises:
  7171. [`~utils.RepositoryNotFoundError`]:
  7172. If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
  7173. are not authenticated.
  7174. [`~utils.HfHubHTTPError`]:
  7175. 403 Forbidden: only the owner of a Space can restart it. If you want to restart a Space that you don't
  7176. own, either ask the owner by opening a Discussion or duplicate the Space.
  7177. [`~utils.BadRequestError`]:
  7178. If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
  7179. a static Space, you can set it to private.
  7180. """
  7181. params = {}
  7182. if factory_reboot:
  7183. params["factory"] = "true"
  7184. r = get_session().post(
  7185. f"{self.endpoint}/api/spaces/{repo_id}/restart", headers=self._build_hf_headers(token=token), params=params
  7186. )
  7187. hf_raise_for_status(r)
  7188. return SpaceRuntime(r.json())
  7189. def _stream_sse_events(
  7190. self,
  7191. *,
  7192. url: str,
  7193. log_label: str,
  7194. timeout: int,
  7195. follow: bool,
  7196. token: bool | str | None = None,
  7197. skip_previous_events_on_retry: bool = True,
  7198. tolerated_status_codes: tuple[int, ...] = (),
  7199. tolerated_exception_types: tuple[type[Exception], ...] = (),
  7200. on_iteration_end: Callable[[], bool] | None = None,
  7201. ) -> Iterable[dict[str, Any]]:
  7202. # Shared SSE streaming loop with retry/backoff and event-index dedup.
  7203. # Used by Spaces logs and Jobs logs/metrics. Two retry styles:
  7204. # - on_iteration_end is None: retries are the only backstop (Spaces).
  7205. # - on_iteration_end is set: it polls authoritative state after every
  7206. # failed iteration; ReadTimeouts/tolerated errors fall through to it
  7207. # instead of consuming retries (Jobs).
  7208. nb_tries = 0
  7209. max_retries = 5 if follow else 0
  7210. min_wait_time = 1
  7211. max_wait_time = 10
  7212. sleep_time = 0
  7213. start_event_idx = 0
  7214. error_to_retry: Exception | None = None
  7215. while True:
  7216. if error_to_retry is not None:
  7217. logger.warning(f"'{error_to_retry}' thrown while requesting {log_label}")
  7218. logger.warning(f"Retrying in {sleep_time}s [Retry {nb_tries}/{max_retries}].")
  7219. error_to_retry = None
  7220. time.sleep(sleep_time)
  7221. try:
  7222. with get_session().stream(
  7223. "GET",
  7224. url,
  7225. headers=self._build_hf_headers(token=token),
  7226. timeout=timeout,
  7227. ) as response:
  7228. if response.status_code == 200:
  7229. event_idx = -1
  7230. for line in response.iter_lines():
  7231. if line and line.startswith("data: {"):
  7232. event_idx += 1
  7233. if event_idx >= start_event_idx:
  7234. if skip_previous_events_on_retry:
  7235. start_event_idx += 1
  7236. yield json.loads(line[len("data: ") :])
  7237. break
  7238. elif response.status_code not in tolerated_status_codes:
  7239. hf_raise_for_status(response)
  7240. except HfHubHTTPError:
  7241. # Permanent HTTP error (404/403/...). Never retry — fail fast.
  7242. raise
  7243. except httpx.DecodingError:
  7244. # Response ended prematurely.
  7245. break
  7246. except KeyboardInterrupt:
  7247. break
  7248. except (httpx.HTTPError, httpcore.TimeoutException) as err:
  7249. is_no_new_line_timeout = isinstance(err, (httpx.ReadTimeout, httpcore.ReadTimeout))
  7250. if is_no_new_line_timeout and not follow:
  7251. break # no-follow: timeout means the buffer is drained
  7252. if on_iteration_end is not None:
  7253. # Authoritative-state mode: ReadTimeouts and tolerated errors
  7254. # fall through to the post-iteration check without consuming
  7255. # retries. Note: ReadTimeout is handled here regardless of
  7256. # `tolerated_exception_types` — entries in that tuple only
  7257. # fire for non-timeout errors.
  7258. if is_no_new_line_timeout or type(err) in tolerated_exception_types:
  7259. pass
  7260. elif nb_tries >= max_retries:
  7261. raise
  7262. else:
  7263. nb_tries += 1
  7264. sleep_time = min(max_wait_time, max(min_wait_time, sleep_time * 2))
  7265. error_to_retry = err
  7266. else:
  7267. # Retry-only mode: every error in follow mode burns a retry.
  7268. if nb_tries >= max_retries:
  7269. if is_no_new_line_timeout:
  7270. break # follow mode, silent stream, retries exhausted: give up
  7271. raise
  7272. nb_tries += 1
  7273. sleep_time = min(max_wait_time, max(min_wait_time, sleep_time * 2))
  7274. error_to_retry = err
  7275. if on_iteration_end is not None and on_iteration_end():
  7276. break
  7277. def _fetch_space_logs_sse(
  7278. self,
  7279. *,
  7280. repo_id: str,
  7281. build: bool,
  7282. timeout: int,
  7283. follow: bool,
  7284. token: bool | str | None = None,
  7285. ) -> Iterable[dict[str, Any]]:
  7286. log_type = "build" if build else "run"
  7287. yield from self._stream_sse_events(
  7288. url=f"{self.endpoint}/api/spaces/{repo_id}/logs/{log_type}",
  7289. log_label=f"spaces /logs/{log_type} for repo_id={repo_id!r}",
  7290. timeout=timeout,
  7291. follow=follow,
  7292. token=token,
  7293. )
  7294. @validate_hf_hub_args
  7295. def fetch_space_logs(
  7296. self,
  7297. repo_id: str,
  7298. *,
  7299. build: bool = False,
  7300. follow: bool = False,
  7301. token: bool | str | None = None,
  7302. ) -> Iterable[str]:
  7303. """Fetch the run or build logs of a Space on the Hub.
  7304. Useful for debugging a Space that is failing to build or crashing at runtime,
  7305. especially from a script or agentic workflow where reading logs in a browser
  7306. is not an option.
  7307. Args:
  7308. repo_id (`str`):
  7309. ID of the Space. Example: `"bigcode/in-the-stack"`.
  7310. build (`bool`, *optional*, defaults to `False`):
  7311. If `True`, fetch the container build logs (useful when a Space is stuck
  7312. in `BUILD_ERROR`). If `False` (default), fetch the run logs, i.e. the
  7313. stdout/stderr of the running application.
  7314. follow (`bool`, *optional*, defaults to `False`):
  7315. If `True`, stream logs in real-time (blocking) until the server closes
  7316. the stream or `KeyboardInterrupt` is raised. If `False` (default), fetch
  7317. only the currently buffered logs and return immediately (non-blocking,
  7318. like `docker logs`).
  7319. token (`bool` or `str`, *optional*):
  7320. A valid user access token. Defaults to the locally saved token, which is
  7321. the recommended authentication method. Set to `False` to disable
  7322. authentication. See
  7323. https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  7324. Returns:
  7325. `Iterable[str]`: A generator yielding log lines as they become available.
  7326. Example:
  7327. ```python
  7328. >>> from huggingface_hub import fetch_space_logs
  7329. >>> # Non-blocking: print currently available run logs and exit.
  7330. >>> for line in fetch_space_logs("username/my-space"):
  7331. ... print(line, end="")
  7332. >>> # Debug a build failure:
  7333. >>> for line in fetch_space_logs("username/my-space", build=True):
  7334. ... print(line, end="")
  7335. >>> # Stream run logs until the server closes the stream.
  7336. >>> for line in fetch_space_logs("username/my-space", follow=True):
  7337. ... print(line, end="")
  7338. ```
  7339. """
  7340. # - Spaces /logs/{run|build} is SSE with `data: {"data": "...", "timestamp": "..."}` events.
  7341. # - Keep-alives are sent as empty `data:` messages (skipped by the `data: {` filter).
  7342. # - In no-follow mode we use a short read timeout to drain the buffer and return.
  7343. timeout = 120 if follow else 5
  7344. for event in self._fetch_space_logs_sse(
  7345. repo_id=repo_id,
  7346. build=build,
  7347. timeout=timeout,
  7348. follow=follow,
  7349. token=token,
  7350. ):
  7351. yield event["data"]
  7352. @_deprecate_arguments(
  7353. version="2.0",
  7354. deprecated_args={"space_storage"},
  7355. custom_message="Use `space_volumes` to mount volumes on a Space.",
  7356. )
  7357. @validate_hf_hub_args
  7358. def duplicate_repo(
  7359. self,
  7360. from_id: str,
  7361. to_id: str | None = None,
  7362. *,
  7363. repo_type: str | None = None,
  7364. private: bool | None = None,
  7365. visibility: RepoVisibility_T | None = None,
  7366. token: bool | str | None = None,
  7367. exist_ok: bool = False,
  7368. space_hardware: SpaceHardware | None = None,
  7369. space_storage: SpaceStorage | None = None,
  7370. space_sleep_time: int | None = None,
  7371. space_secrets: list[dict[str, str]] | None = None,
  7372. space_variables: list[dict[str, str]] | None = None,
  7373. space_volumes: list[Volume] | None = None,
  7374. ) -> RepoUrl:
  7375. """Duplicate a repo on the Hub (model, dataset, or Space).
  7376. This performs a server-side copy that preserves full git history and LFS objects
  7377. without requiring a local download/upload round-trip.
  7378. Args:
  7379. from_id (`str`):
  7380. ID of the repo to duplicate. Example: `"openai/gdpval"`.
  7381. to_id (`str`, *optional*):
  7382. ID of the new repo. Example: `"myorg/my-gdpval"`. If not provided, the new
  7383. repo will have the same name as the original repo, but in your account.
  7384. repo_type (`str`, *optional*):
  7385. Set to `"dataset"` or `"space"` if duplicating a dataset or Space,
  7386. `None` or `"model"` if duplicating a model. Default is `None`.
  7387. private (`bool`, *optional*):
  7388. Whether the new repo should be private or not. Defaults to the same
  7389. privacy as the original repo. Cannot be passed together with `visibility`.
  7390. visibility (`Literal["public", "private", "protected"]`, *optional*):
  7391. Visibility of the new repo. Can be `"public"` or `"private"`, or `"protected"` for Spaces. Defaults
  7392. to the same visibility as the original repo.
  7393. token (`bool` or `str`, *optional*):
  7394. A valid user access token (string). Defaults to the locally saved
  7395. token, which is the recommended method for authentication (see
  7396. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7397. To disable authentication, pass `False`.
  7398. exist_ok (`bool`, *optional*, defaults to `False`):
  7399. If `True`, do not raise an error if repo already exists.
  7400. space_hardware (`SpaceHardware` or `str`, *optional*):
  7401. Choice of Hardware if repo_type is "space". Example: `"t4-medium"`. See
  7402. [`SpaceHardware`] for a complete list.
  7403. space_storage (`SpaceStorage` or `str`, *optional*):
  7404. <Deprecated, use `set_space_volumes` instead> Choice of persistent storage tier if repo_type is "space". Example:
  7405. `"small"`. See [`SpaceStorage`] for a complete list.
  7406. space_sleep_time (`int`, *optional*):
  7407. Number of seconds of inactivity to wait before a Space is put to sleep.
  7408. Set to `-1` if you don't want your Space to sleep (default behavior for
  7409. upgraded hardware). For free hardware, you can't configure the sleep time
  7410. (value is fixed to 48 hours of inactivity). Only applicable if repo_type is "space".
  7411. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  7412. space_secrets (`list[dict[str, str]]`, *optional*):
  7413. A list of secret keys to set in your Space. Each item is in the form
  7414. `{"key": ..., "value": ..., "description": ...}` where description is optional.
  7415. Only applicable if repo_type is "space".
  7416. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  7417. space_variables (`list[dict[str, str]]`, *optional*):
  7418. A list of public environment variables to set in your Space. Each item is in
  7419. the form `{"key": ..., "value": ..., "description": ...}` where description
  7420. is optional. Only applicable if repo_type is "space".
  7421. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
  7422. space_volumes (`list[Volume]`, *optional*):
  7423. A list of [`Volume`] objects to mount in the Space at duplication time. Each volume has a `type`
  7424. (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), a `source` (repo or bucket ID), a `mount_path`
  7425. (path inside the container), and optional `revision`, `read_only`, and `path` fields.
  7426. Only applicable if repo_type is "space".
  7427. Returns:
  7428. [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
  7429. attributes like `endpoint`, `repo_type` and `repo_id`.
  7430. Raises:
  7431. [`~utils.RepositoryNotFoundError`]:
  7432. If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist,
  7433. or because it is set to `private` and you do not have access.
  7434. [`HfHubHTTPError`]:
  7435. If the HuggingFace API returned an error
  7436. Example:
  7437. ```python
  7438. >>> from huggingface_hub import duplicate_repo
  7439. # Duplicate a model to your account
  7440. >>> duplicate_repo("google/gemma-7b")
  7441. RepoUrl('https://huggingface.co/nateraw/gemma-7b',...)
  7442. # Duplicate a dataset with a custom name
  7443. >>> duplicate_repo("openai/gdpval", to_id="myorg/my-gdpval", repo_type="dataset")
  7444. RepoUrl('https://huggingface.co/datasets/myorg/my-gdpval',...)
  7445. # Duplicate a Space with custom hardware
  7446. >>> duplicate_repo("multimodalart/dreambooth-training", repo_type="space", space_hardware="t4-medium")
  7447. RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)
  7448. ```
  7449. """
  7450. if repo_type not in constants.REPO_TYPES:
  7451. raise ValueError("Invalid repo type")
  7452. resolved_visibility = _resolve_repo_visibility(private=private, visibility=visibility, repo_type=repo_type)
  7453. # Map repo_type to API path segment
  7454. api_prefix = {
  7455. None: "models",
  7456. constants.REPO_TYPE_MODEL: "models",
  7457. constants.REPO_TYPE_DATASET: "datasets",
  7458. constants.REPO_TYPE_SPACE: "spaces",
  7459. }[repo_type]
  7460. # Parse to_id if provided
  7461. parsed_to_id = RepoUrl(to_id) if to_id is not None else None
  7462. # Infer target repo_id
  7463. to_namespace = (
  7464. parsed_to_id.namespace
  7465. if parsed_to_id is not None and parsed_to_id.namespace is not None
  7466. else self.whoami(token)["name"]
  7467. )
  7468. to_repo_name = parsed_to_id.repo_name if to_id is not None else RepoUrl(from_id).repo_name # type: ignore
  7469. payload: dict[str, Any] = {"repository": f"{to_namespace}/{to_repo_name}"}
  7470. if resolved_visibility is not None:
  7471. payload["visibility"] = resolved_visibility
  7472. # Space-specific options
  7473. space_args: list[tuple[str, str, Any]] = [
  7474. # input arg, payload key, value
  7475. ("space_hardware", "hardware", space_hardware),
  7476. ("space_storage", "storageTier", space_storage),
  7477. ("space_sleep_time", "sleepTimeSeconds", space_sleep_time),
  7478. ("space_secrets", "secrets", space_secrets),
  7479. ("space_variables", "variables", space_variables),
  7480. ("space_volumes", "volumes", [v.to_dict() for v in space_volumes] if space_volumes else None),
  7481. ]
  7482. if repo_type == "space":
  7483. for _, key, value in space_args:
  7484. if value is not None:
  7485. payload[key] = value
  7486. if space_sleep_time is not None and space_hardware == SpaceHardware.CPU_BASIC:
  7487. warnings.warn(
  7488. "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
  7489. " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
  7490. " you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
  7491. UserWarning,
  7492. )
  7493. else:
  7494. if provided_space_args := [arg for arg, _, value in space_args if value is not None]:
  7495. warnings.warn(f"Ignoring provided {', '.join(provided_space_args)} because repo_type is not 'space'.")
  7496. r = get_session().post(
  7497. f"{self.endpoint}/api/{api_prefix}/{from_id}/duplicate",
  7498. headers=self._build_hf_headers(token=token),
  7499. json=payload,
  7500. )
  7501. try:
  7502. hf_raise_for_status(r)
  7503. except HfHubHTTPError as err:
  7504. if exist_ok and err.response.status_code == 409:
  7505. pass
  7506. else:
  7507. raise
  7508. return RepoUrl(r.json()["url"], endpoint=self.endpoint)
  7509. @_deprecate_method(version="2.0", message="Use `duplicate_repo` instead.")
  7510. @validate_hf_hub_args
  7511. def duplicate_space(
  7512. self,
  7513. from_id: str,
  7514. to_id: str | None = None,
  7515. *,
  7516. private: bool | None = None,
  7517. visibility: RepoVisibility_T | None = None,
  7518. token: bool | str | None = None,
  7519. exist_ok: bool = False,
  7520. hardware: SpaceHardware | None = None,
  7521. storage: SpaceStorage | None = None,
  7522. sleep_time: int | None = None,
  7523. secrets: list[dict[str, str]] | None = None,
  7524. variables: list[dict[str, str]] | None = None,
  7525. ) -> RepoUrl:
  7526. """Duplicate a Space.
  7527. Programmatically duplicate a Space. The new Space will be created in your account and will be in the same state
  7528. as the original Space (running or paused). You can duplicate a Space no matter the current state of a Space.
  7529. Args:
  7530. from_id (`str`):
  7531. ID of the Space to duplicate. Example: `"pharma/CLIP-Interrogator"`.
  7532. to_id (`str`, *optional*):
  7533. ID of the new Space. Example: `"dog/CLIP-Interrogator"`. If not provided, the new Space will have the same
  7534. name as the original Space, but in your account.
  7535. private (`bool`, *optional*):
  7536. Whether the new Space should be private or not. Defaults to the same privacy as the original Space. Cannot be passed together with `visibility`.
  7537. visibility (`Literal["public", "private", "protected"]`, *optional*):
  7538. Visibility of the new Space. Can be `"public"`, `"private"`, or `"protected"`. Defaults to the same
  7539. visibility as the original Space.
  7540. token (`bool` or `str`, *optional*):
  7541. A valid user access token (string). Defaults to the locally saved
  7542. token, which is the recommended method for authentication (see
  7543. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7544. To disable authentication, pass `False`.
  7545. exist_ok (`bool`, *optional*, defaults to `False`):
  7546. If `True`, do not raise an error if repo already exists.
  7547. hardware (`SpaceHardware` or `str`, *optional*):
  7548. Choice of Hardware. Example: `"t4-medium"`. See [`SpaceHardware`] for a complete list.
  7549. storage (`SpaceStorage` or `str`, *optional*):
  7550. Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
  7551. sleep_time (`int`, *optional*):
  7552. Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
  7553. your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
  7554. the sleep time (value is fixed to 48 hours of inactivity).
  7555. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  7556. secrets (`list[dict[str, str]]`, *optional*):
  7557. A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
  7558. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  7559. variables (`list[dict[str, str]]`, *optional*):
  7560. A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
  7561. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
  7562. Returns:
  7563. [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
  7564. attributes like `endpoint`, `repo_type` and `repo_id`.
  7565. Raises:
  7566. [`~utils.RepositoryNotFoundError`]:
  7567. If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist,
  7568. or because it is set to `private` and you do not have access.
  7569. [`HfHubHTTPError`]:
  7570. If the HuggingFace API returned an error
  7571. Example:
  7572. ```python
  7573. >>> from huggingface_hub import duplicate_space
  7574. # Duplicate a Space to your account
  7575. >>> duplicate_space("multimodalart/dreambooth-training")
  7576. RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)
  7577. # Can set custom destination id and visibility flag.
  7578. >>> duplicate_space("multimodalart/dreambooth-training", to_id="my-dreambooth", visibility="private")
  7579. RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...)
  7580. ```
  7581. > [!WARNING]
  7582. > `duplicate_space` is deprecated and will be removed in version 2.0. Use [`~HfApi.duplicate_repo`] instead.
  7583. """
  7584. kwargs: dict[str, Any] = {}
  7585. if to_id is not None:
  7586. kwargs["to_id"] = to_id
  7587. return self.duplicate_repo(
  7588. from_id=from_id,
  7589. repo_type="space",
  7590. private=private,
  7591. visibility=visibility,
  7592. token=token,
  7593. exist_ok=exist_ok,
  7594. space_hardware=hardware,
  7595. space_storage=storage,
  7596. space_sleep_time=sleep_time,
  7597. space_secrets=secrets,
  7598. space_variables=variables,
  7599. **kwargs,
  7600. )
  7601. @_deprecate_method(version="2.0", message="Use `set_space_volumes` instead.")
  7602. @validate_hf_hub_args
  7603. def request_space_storage(
  7604. self,
  7605. repo_id: str,
  7606. storage: SpaceStorage,
  7607. *,
  7608. token: bool | str | None = None,
  7609. ) -> SpaceRuntime:
  7610. """Request persistent storage for a Space.
  7611. > [!WARNING]
  7612. > `request_space_storage` is deprecated and will be removed in version 2.0. Use [`set_space_volumes`] instead.
  7613. Args:
  7614. repo_id (`str`):
  7615. ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`.
  7616. storage (`str` or [`SpaceStorage`]):
  7617. Storage tier. Either 'small', 'medium', or 'large'.
  7618. token (`bool` or `str`, *optional*):
  7619. A valid user access token (string). Defaults to the locally saved
  7620. token, which is the recommended method for authentication (see
  7621. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7622. To disable authentication, pass `False`.
  7623. Returns:
  7624. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  7625. """
  7626. payload: dict[str, SpaceStorage] = {"tier": storage}
  7627. r = get_session().post(
  7628. f"{self.endpoint}/api/spaces/{repo_id}/storage",
  7629. headers=self._build_hf_headers(token=token),
  7630. json=payload,
  7631. )
  7632. hf_raise_for_status(r)
  7633. return SpaceRuntime(r.json())
  7634. @_deprecate_method(version="2.0", message="Use `delete_space_volumes` instead.")
  7635. @validate_hf_hub_args
  7636. def delete_space_storage(
  7637. self,
  7638. repo_id: str,
  7639. *,
  7640. token: bool | str | None = None,
  7641. ) -> SpaceRuntime:
  7642. """Delete persistent storage for a Space.
  7643. > [!WARNING]
  7644. > `delete_space_storage` is deprecated and will be removed in version 2.0. Use [`delete_space_volumes`] instead.
  7645. Args:
  7646. repo_id (`str`):
  7647. ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`.
  7648. token (`bool` or `str`, *optional*):
  7649. A valid user access token (string). Defaults to the locally saved
  7650. token, which is the recommended method for authentication (see
  7651. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7652. To disable authentication, pass `False`.
  7653. Returns:
  7654. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  7655. Raises:
  7656. [`BadRequestError`]
  7657. If space has no persistent storage.
  7658. """
  7659. r = get_session().delete(
  7660. f"{self.endpoint}/api/spaces/{repo_id}/storage",
  7661. headers=self._build_hf_headers(token=token),
  7662. )
  7663. hf_raise_for_status(r)
  7664. return SpaceRuntime(r.json())
  7665. @validate_hf_hub_args
  7666. def set_space_volumes(
  7667. self,
  7668. repo_id: str,
  7669. volumes: list[Volume],
  7670. *,
  7671. token: bool | str | None = None,
  7672. ) -> None:
  7673. """Set volumes for a Space.
  7674. Sets (or replaces) the list of volumes mounted in the Space. Each volume gives the Space's container access
  7675. to a Hub resource (model, dataset, or storage bucket).
  7676. Args:
  7677. repo_id (`str`):
  7678. ID of the Space to update. Example: `"username/my-space"`.
  7679. volumes (`list[Volume]`):
  7680. List of [`Volume`] objects to mount. Each volume has a `type` (`"bucket"`, `"model"`, `"dataset"`, or
  7681. `"space"`), a `source` (repo or bucket ID), a `mount_path` (path inside the container), and optional
  7682. `revision`, `read_only`, and `path` fields.
  7683. token (`bool` or `str`, *optional*):
  7684. A valid user access token (string). Defaults to the locally saved
  7685. token, which is the recommended method for authentication (see
  7686. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7687. To disable authentication, pass `False`.
  7688. Raises:
  7689. [`BadRequestError`]:
  7690. If the Space is a static Space (volumes are not supported on static Spaces).
  7691. Example:
  7692. ```python
  7693. >>> from huggingface_hub import HfApi, Volume
  7694. >>> api = HfApi()
  7695. >>> api.set_space_volumes(
  7696. ... "username/my-space",
  7697. ... volumes=[
  7698. ... Volume(type="model", source="username/my-model", mount_path="/models", read_only=True),
  7699. ... Volume(type="bucket", source="username/my-bucket", mount_path="/data"),
  7700. ... ],
  7701. ... )
  7702. ```
  7703. """
  7704. payload = {"volumes": [vol.to_dict() for vol in volumes]}
  7705. r = get_session().put(
  7706. f"{self.endpoint}/api/spaces/{repo_id}/volumes",
  7707. headers=self._build_hf_headers(token=token),
  7708. json=payload,
  7709. )
  7710. hf_raise_for_status(r)
  7711. @validate_hf_hub_args
  7712. def delete_space_volumes(
  7713. self,
  7714. repo_id: str,
  7715. *,
  7716. token: bool | str | None = None,
  7717. ) -> None:
  7718. """Remove all volumes from a Space.
  7719. Args:
  7720. repo_id (`str`):
  7721. ID of the Space to update. Example: `"username/my-space"`.
  7722. token (`bool` or `str`, *optional*):
  7723. A valid user access token (string). Defaults to the locally saved
  7724. token, which is the recommended method for authentication (see
  7725. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7726. To disable authentication, pass `False`.
  7727. Raises:
  7728. [`BadRequestError`]:
  7729. If the Space has no volumes attached.
  7730. Example:
  7731. ```python
  7732. >>> from huggingface_hub import HfApi
  7733. >>> api = HfApi()
  7734. >>> api.delete_space_volumes("username/my-space")
  7735. ```
  7736. """
  7737. r = get_session().delete(
  7738. f"{self.endpoint}/api/spaces/{repo_id}/volumes",
  7739. headers=self._build_hf_headers(token=token),
  7740. )
  7741. hf_raise_for_status(r)
  7742. #######################
  7743. # Inference Endpoints #
  7744. #######################
  7745. def list_inference_endpoints(
  7746. self, namespace: str | None = None, *, token: bool | str | None = None
  7747. ) -> list[InferenceEndpoint]:
  7748. """Lists all inference endpoints for the given namespace.
  7749. Args:
  7750. namespace (`str`, *optional*):
  7751. The namespace to list endpoints for. Defaults to the current user. Set to `"*"` to list all endpoints
  7752. from all namespaces (i.e. personal namespace and all orgs the user belongs to).
  7753. token (`bool` or `str`, *optional*):
  7754. A valid user access token (string). Defaults to the locally saved
  7755. token, which is the recommended method for authentication (see
  7756. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7757. To disable authentication, pass `False`.
  7758. Returns:
  7759. list[`InferenceEndpoint`]: A list of all inference endpoints for the given namespace.
  7760. Example:
  7761. ```python
  7762. >>> from huggingface_hub import HfApi
  7763. >>> api = HfApi()
  7764. >>> api.list_inference_endpoints()
  7765. [InferenceEndpoint(name='my-endpoint', ...), ...]
  7766. ```
  7767. """
  7768. # Special case: list all endpoints for all namespaces the user has access to
  7769. if namespace == "*":
  7770. user = self.whoami(token=token)
  7771. # List personal endpoints first
  7772. endpoints: list[InferenceEndpoint] = list_inference_endpoints(namespace=self._get_namespace(token=token))
  7773. # Then list endpoints for all orgs the user belongs to and ignore 401 errors (no billing or no access)
  7774. for org in user.get("orgs", []):
  7775. try:
  7776. endpoints += list_inference_endpoints(namespace=org["name"], token=token)
  7777. except HfHubHTTPError as error:
  7778. if error.response.status_code == 401: # Either no billing or user don't have access)
  7779. logger.debug("Cannot list Inference Endpoints for org '%s': %s", org["name"], error)
  7780. pass
  7781. return endpoints
  7782. # Normal case: list endpoints for a specific namespace
  7783. namespace = namespace or self._get_namespace(token=token)
  7784. response = get_session().get(
  7785. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}",
  7786. headers=self._build_hf_headers(token=token),
  7787. )
  7788. hf_raise_for_status(response)
  7789. return [
  7790. InferenceEndpoint.from_raw(endpoint, namespace=namespace, token=token)
  7791. for endpoint in response.json()["items"]
  7792. ]
  7793. def create_inference_endpoint(
  7794. self,
  7795. name: str,
  7796. *,
  7797. repository: str,
  7798. framework: str,
  7799. accelerator: str,
  7800. instance_size: str,
  7801. instance_type: str,
  7802. region: str,
  7803. vendor: str,
  7804. account_id: str | None = None,
  7805. min_replica: int = 1,
  7806. max_replica: int = 1,
  7807. scaling_metric: InferenceEndpointScalingMetric | None = None,
  7808. scaling_threshold: float | None = None,
  7809. scale_to_zero_timeout: int | None = None,
  7810. revision: str | None = None,
  7811. task: str | None = None,
  7812. custom_image: dict | None = None,
  7813. env: dict[str, str] | None = None,
  7814. secrets: dict[str, str] | None = None,
  7815. type: InferenceEndpointType = InferenceEndpointType.PROTECTED,
  7816. domain: str | None = None,
  7817. path: str | None = None,
  7818. cache_http_responses: bool | None = None,
  7819. tags: list[str] | None = None,
  7820. namespace: str | None = None,
  7821. token: bool | str | None = None,
  7822. ) -> InferenceEndpoint:
  7823. """Create a new Inference Endpoint.
  7824. Args:
  7825. name (`str`):
  7826. The unique name for the new Inference Endpoint.
  7827. repository (`str`):
  7828. The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
  7829. framework (`str`):
  7830. The machine learning framework used for the model (e.g. `"custom"`).
  7831. accelerator (`str`):
  7832. The hardware accelerator to be used for inference (e.g. `"cpu"`).
  7833. instance_size (`str`):
  7834. The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
  7835. instance_type (`str`):
  7836. The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
  7837. region (`str`):
  7838. The cloud region in which the Inference Endpoint will be created (e.g. `"us-east-1"`).
  7839. vendor (`str`):
  7840. The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. `"aws"`).
  7841. account_id (`str`, *optional*):
  7842. The account ID used to link a VPC to a private Inference Endpoint (if applicable).
  7843. min_replica (`int`, *optional*):
  7844. The minimum number of replicas (instances) to keep running for the Inference Endpoint. To enable
  7845. scaling to zero, set this value to 0 and adjust `scale_to_zero_timeout` accordingly. Defaults to 1.
  7846. max_replica (`int`, *optional*):
  7847. The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to 1.
  7848. scaling_metric (`str` or [`InferenceEndpointScalingMetric `], *optional*):
  7849. The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided. Defaults to
  7850. None (meaning: let the HF Endpoints service specify the metric).
  7851. scaling_threshold (`float`, *optional*):
  7852. The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.
  7853. Defaults to None (meaning: let the HF Endpoints service specify the threshold).
  7854. scale_to_zero_timeout (`int`, *optional*):
  7855. The duration in minutes before an inactive endpoint is scaled to zero, or no scaling to zero if
  7856. set to None and `min_replica` is not 0. Defaults to None.
  7857. revision (`str`, *optional*):
  7858. The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
  7859. task (`str`, *optional*):
  7860. The task on which to deploy the model (e.g. `"text-classification"`).
  7861. custom_image (`dict`, *optional*):
  7862. A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
  7863. Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
  7864. env (`dict[str, str]`, *optional*):
  7865. Non-secret environment variables to inject in the container environment.
  7866. secrets (`dict[str, str]`, *optional*):
  7867. Secret values to inject in the container environment.
  7868. type ([`InferenceEndpointType]`, *optional*):
  7869. The type of the Inference Endpoint, which can be `"protected"` (default), `"public"` or `"private"`.
  7870. domain (`str`, *optional*):
  7871. 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"`).
  7872. path (`str`, *optional*):
  7873. The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`).
  7874. cache_http_responses (`bool`, *optional*):
  7875. Whether to cache HTTP responses from the Inference Endpoint. Defaults to `False`.
  7876. tags (`list[str]`, *optional*):
  7877. A list of tags to associate with the Inference Endpoint.
  7878. namespace (`str`, *optional*):
  7879. The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.
  7880. token (`bool` or `str`, *optional*):
  7881. A valid user access token (string). Defaults to the locally saved
  7882. token, which is the recommended method for authentication (see
  7883. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7884. To disable authentication, pass `False`.
  7885. Returns:
  7886. [`InferenceEndpoint`]: information about the updated Inference Endpoint.
  7887. Example:
  7888. ```python
  7889. >>> from huggingface_hub import HfApi
  7890. >>> api = HfApi()
  7891. >>> endpoint = api.create_inference_endpoint(
  7892. ... "my-endpoint-name",
  7893. ... repository="gpt2",
  7894. ... framework="pytorch",
  7895. ... task="text-generation",
  7896. ... accelerator="cpu",
  7897. ... vendor="aws",
  7898. ... region="us-east-1",
  7899. ... type="protected",
  7900. ... instance_size="x2",
  7901. ... instance_type="intel-icl",
  7902. ... )
  7903. >>> endpoint
  7904. InferenceEndpoint(name='my-endpoint-name', status="pending",...)
  7905. # Run inference on the endpoint
  7906. >>> endpoint.client.text_generation(...)
  7907. "..."
  7908. ```
  7909. ```python
  7910. # Start an Inference Endpoint running Zephyr-7b-beta on TGI
  7911. >>> from huggingface_hub import HfApi
  7912. >>> api = HfApi()
  7913. >>> endpoint = api.create_inference_endpoint(
  7914. ... "aws-zephyr-7b-beta-0486",
  7915. ... repository="HuggingFaceH4/zephyr-7b-beta",
  7916. ... framework="pytorch",
  7917. ... task="text-generation",
  7918. ... accelerator="gpu",
  7919. ... vendor="aws",
  7920. ... region="us-east-1",
  7921. ... type="protected",
  7922. ... instance_size="x1",
  7923. ... instance_type="nvidia-a10g",
  7924. ... env={
  7925. ... "MAX_BATCH_PREFILL_TOKENS": "2048",
  7926. ... "MAX_INPUT_LENGTH": "1024",
  7927. ... "MAX_TOTAL_TOKENS": "1512",
  7928. ... "MODEL_ID": "/repository"
  7929. ... },
  7930. ... custom_image={
  7931. ... "health_route": "/health",
  7932. ... "url": "ghcr.io/huggingface/text-generation-inference:1.1.0",
  7933. ... },
  7934. ... secrets={"MY_SECRET_KEY": "secret_value"},
  7935. ... tags=["dev", "text-generation"],
  7936. ... )
  7937. ```
  7938. ```python
  7939. # Start an Inference Endpoint running ProsusAI/finbert while scaling to zero in 15 minutes
  7940. >>> from huggingface_hub import HfApi
  7941. >>> api = HfApi()
  7942. >>> endpoint = api.create_inference_endpoint(
  7943. ... "finbert-classifier",
  7944. ... repository="ProsusAI/finbert",
  7945. ... framework="pytorch",
  7946. ... task="text-classification",
  7947. ... min_replica=0,
  7948. ... scale_to_zero_timeout=15,
  7949. ... accelerator="cpu",
  7950. ... vendor="aws",
  7951. ... region="us-east-1",
  7952. ... type="protected",
  7953. ... instance_size="x2",
  7954. ... instance_type="intel-icl",
  7955. ... )
  7956. >>> endpoint.wait(timeout=300)
  7957. # Run inference on the endpoint
  7958. >>> endpoint.client.text_generation(...)
  7959. TextClassificationOutputElement(label='positive', score=0.8983615040779114)
  7960. ```
  7961. """
  7962. namespace = namespace or self._get_namespace(token=token)
  7963. if custom_image is not None:
  7964. image = (
  7965. custom_image
  7966. if next(iter(custom_image)) in constants.INFERENCE_ENDPOINT_IMAGE_KEYS
  7967. else {"custom": custom_image}
  7968. )
  7969. else:
  7970. image = {"huggingface": {}}
  7971. payload: dict = {
  7972. "accountId": account_id,
  7973. "compute": {
  7974. "accelerator": accelerator,
  7975. "instanceSize": instance_size,
  7976. "instanceType": instance_type,
  7977. "scaling": {
  7978. "maxReplica": max_replica,
  7979. "minReplica": min_replica,
  7980. "scaleToZeroTimeout": scale_to_zero_timeout,
  7981. },
  7982. },
  7983. "model": {
  7984. "framework": framework,
  7985. "repository": repository,
  7986. "revision": revision,
  7987. "task": task,
  7988. "image": image,
  7989. },
  7990. "name": name,
  7991. "provider": {
  7992. "region": region,
  7993. "vendor": vendor,
  7994. },
  7995. "type": type,
  7996. }
  7997. if scaling_metric:
  7998. payload["compute"]["scaling"]["measure"] = {scaling_metric: scaling_threshold} # type: ignore
  7999. if env:
  8000. payload["model"]["env"] = env
  8001. if secrets:
  8002. payload["model"]["secrets"] = secrets
  8003. if domain is not None or path is not None:
  8004. payload["route"] = {}
  8005. if domain is not None:
  8006. payload["route"]["domain"] = domain
  8007. if path is not None:
  8008. payload["route"]["path"] = path
  8009. if cache_http_responses is not None:
  8010. payload["cacheHttpResponses"] = cache_http_responses
  8011. if tags is not None:
  8012. payload["tags"] = tags
  8013. response = get_session().post(
  8014. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}",
  8015. headers=self._build_hf_headers(token=token),
  8016. json=payload,
  8017. )
  8018. hf_raise_for_status(response)
  8019. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  8020. @experimental
  8021. @validate_hf_hub_args
  8022. def create_inference_endpoint_from_catalog(
  8023. self,
  8024. repo_id: str,
  8025. *,
  8026. name: str | None = None,
  8027. accelerator: Literal["cpu", "gpu", "neuron"] | str | None = None,
  8028. token: bool | str | None = None,
  8029. namespace: str | None = None,
  8030. ) -> InferenceEndpoint:
  8031. """Create a new Inference Endpoint from a model in the Hugging Face Inference Catalog.
  8032. The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference
  8033. and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list
  8034. of available models in the catalog.
  8035. Args:
  8036. repo_id (`str`):
  8037. The ID of the model in the catalog to deploy as an Inference Endpoint.
  8038. name (`str`, *optional*):
  8039. The unique name for the new Inference Endpoint. If not provided, a random name will be generated.
  8040. accelerator (`str`, *optional*):
  8041. The hardware accelerator to be used for inference. Possible values include `"cpu"`, `"gpu"`, and
  8042. `"neuron"`. If not provided, the server will use a default appropriate for the model.
  8043. token (`bool` or `str`, *optional*):
  8044. A valid user access token (string). Defaults to the locally saved
  8045. token, which is the recommended method for authentication (see
  8046. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8047. namespace (`str`, *optional*):
  8048. The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.
  8049. Returns:
  8050. [`InferenceEndpoint`]: information about the new Inference Endpoint.
  8051. > [!WARNING]
  8052. > `create_inference_endpoint_from_catalog` is experimental. Its API is subject to change in the future. Please provide feedback
  8053. > if you have any suggestions or requests.
  8054. """
  8055. token = token or self.token or get_token()
  8056. payload: dict = {
  8057. "namespace": namespace or self._get_namespace(token=token),
  8058. "repoId": repo_id,
  8059. }
  8060. if name is not None:
  8061. payload["endpointName"] = name
  8062. if accelerator is not None:
  8063. payload["accelerator"] = accelerator
  8064. response = get_session().post(
  8065. f"{constants.INFERENCE_CATALOG_ENDPOINT}/deploy",
  8066. headers=self._build_hf_headers(token=token),
  8067. json=payload,
  8068. )
  8069. hf_raise_for_status(response)
  8070. data = response.json()["endpoint"]
  8071. return InferenceEndpoint.from_raw(data, namespace=data["name"], token=token)
  8072. @experimental
  8073. @validate_hf_hub_args
  8074. def list_inference_catalog(self, *, token: bool | str | None = None) -> list[str]:
  8075. """List models available in the Hugging Face Inference Catalog.
  8076. The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference
  8077. and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list
  8078. of available models in the catalog.
  8079. Use [`create_inference_endpoint_from_catalog`] to deploy a model from the catalog.
  8080. Args:
  8081. token (`bool` or `str`, *optional*):
  8082. A valid user access token (string). Defaults to the locally saved
  8083. token, which is the recommended method for authentication (see
  8084. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8085. Returns:
  8086. List[`str`]: A list of model IDs available in the catalog.
  8087. > [!WARNING]
  8088. > `list_inference_catalog` is experimental. Its API is subject to change in the future. Please provide feedback
  8089. > if you have any suggestions or requests.
  8090. """
  8091. response = get_session().get(
  8092. f"{constants.INFERENCE_CATALOG_ENDPOINT}/repo-list",
  8093. headers=self._build_hf_headers(token=token),
  8094. )
  8095. hf_raise_for_status(response)
  8096. return response.json()["models"]
  8097. def get_inference_endpoint(
  8098. self, name: str, *, namespace: str | None = None, token: bool | str | None = None
  8099. ) -> InferenceEndpoint:
  8100. """Get information about an Inference Endpoint.
  8101. Args:
  8102. name (`str`):
  8103. The name of the Inference Endpoint to retrieve information about.
  8104. namespace (`str`, *optional*):
  8105. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  8106. token (`bool` or `str`, *optional*):
  8107. A valid user access token (string). Defaults to the locally saved
  8108. token, which is the recommended method for authentication (see
  8109. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8110. To disable authentication, pass `False`.
  8111. Returns:
  8112. [`InferenceEndpoint`]: information about the requested Inference Endpoint.
  8113. Example:
  8114. ```python
  8115. >>> from huggingface_hub import HfApi
  8116. >>> api = HfApi()
  8117. >>> endpoint = api.get_inference_endpoint("my-text-to-image")
  8118. >>> endpoint
  8119. InferenceEndpoint(name='my-text-to-image', ...)
  8120. # Get status
  8121. >>> endpoint.status
  8122. 'running'
  8123. >>> endpoint.url
  8124. 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
  8125. # Run inference
  8126. >>> endpoint.client.text_to_image(...)
  8127. ```
  8128. """
  8129. namespace = namespace or self._get_namespace(token=token)
  8130. response = get_session().get(
  8131. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}",
  8132. headers=self._build_hf_headers(token=token),
  8133. )
  8134. hf_raise_for_status(response)
  8135. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  8136. def update_inference_endpoint(
  8137. self,
  8138. name: str,
  8139. *,
  8140. # Compute update
  8141. accelerator: str | None = None,
  8142. instance_size: str | None = None,
  8143. instance_type: str | None = None,
  8144. min_replica: int | None = None,
  8145. max_replica: int | None = None,
  8146. scale_to_zero_timeout: int | None = None,
  8147. scaling_metric: InferenceEndpointScalingMetric | None = None,
  8148. scaling_threshold: float | None = None,
  8149. # Model update
  8150. repository: str | None = None,
  8151. framework: str | None = None,
  8152. revision: str | None = None,
  8153. task: str | None = None,
  8154. custom_image: dict | None = None,
  8155. env: dict[str, str] | None = None,
  8156. secrets: dict[str, str] | None = None,
  8157. # Route update
  8158. domain: str | None = None,
  8159. path: str | None = None,
  8160. # Other
  8161. cache_http_responses: bool | None = None,
  8162. tags: list[str] | None = None,
  8163. namespace: str | None = None,
  8164. token: bool | str | None = None,
  8165. ) -> InferenceEndpoint:
  8166. """Update an Inference Endpoint.
  8167. This method allows the update of either the compute configuration, the deployed model, the route, or any combination.
  8168. All arguments are optional but at least one must be provided.
  8169. For convenience, you can also update an Inference Endpoint using [`InferenceEndpoint.update`].
  8170. Args:
  8171. name (`str`):
  8172. The name of the Inference Endpoint to update.
  8173. accelerator (`str`, *optional*):
  8174. The hardware accelerator to be used for inference (e.g. `"cpu"`).
  8175. instance_size (`str`, *optional*):
  8176. The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
  8177. instance_type (`str`, *optional*):
  8178. The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
  8179. min_replica (`int`, *optional*):
  8180. The minimum number of replicas (instances) to keep running for the Inference Endpoint.
  8181. max_replica (`int`, *optional*):
  8182. The maximum number of replicas (instances) to scale to for the Inference Endpoint.
  8183. scale_to_zero_timeout (`int`, *optional*):
  8184. The duration in minutes before an inactive endpoint is scaled to zero.
  8185. scaling_metric (`str` or [`InferenceEndpointScalingMetric `], *optional*):
  8186. The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided.
  8187. Defaults to None.
  8188. scaling_threshold (`float`, *optional*):
  8189. The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.
  8190. Defaults to None.
  8191. repository (`str`, *optional*):
  8192. The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
  8193. framework (`str`, *optional*):
  8194. The machine learning framework used for the model (e.g. `"custom"`).
  8195. revision (`str`, *optional*):
  8196. The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
  8197. task (`str`, *optional*):
  8198. The task on which to deploy the model (e.g. `"text-classification"`).
  8199. custom_image (`dict`, *optional*):
  8200. A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
  8201. Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
  8202. env (`dict[str, str]`, *optional*):
  8203. Non-secret environment variables to inject in the container environment
  8204. secrets (`dict[str, str]`, *optional*):
  8205. Secret values to inject in the container environment.
  8206. domain (`str`, *optional*):
  8207. 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"`).
  8208. path (`str`, *optional*):
  8209. The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`).
  8210. cache_http_responses (`bool`, *optional*):
  8211. Whether to cache HTTP responses from the Inference Endpoint.
  8212. tags (`list[str]`, *optional*):
  8213. A list of tags to associate with the Inference Endpoint.
  8214. namespace (`str`, *optional*):
  8215. The namespace where the Inference Endpoint will be updated. Defaults to the current user's namespace.
  8216. token (`bool` or `str`, *optional*):
  8217. A valid user access token (string). Defaults to the locally saved
  8218. token, which is the recommended method for authentication (see
  8219. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8220. To disable authentication, pass `False`.
  8221. Returns:
  8222. [`InferenceEndpoint`]: information about the updated Inference Endpoint.
  8223. """
  8224. namespace = namespace or self._get_namespace(token=token)
  8225. # Populate only the fields that are not None
  8226. payload: dict = defaultdict(lambda: defaultdict(dict))
  8227. if accelerator is not None:
  8228. payload["compute"]["accelerator"] = accelerator
  8229. if instance_size is not None:
  8230. payload["compute"]["instanceSize"] = instance_size
  8231. if instance_type is not None:
  8232. payload["compute"]["instanceType"] = instance_type
  8233. if max_replica is not None:
  8234. payload["compute"]["scaling"]["maxReplica"] = max_replica
  8235. if min_replica is not None:
  8236. payload["compute"]["scaling"]["minReplica"] = min_replica
  8237. if scale_to_zero_timeout is not None:
  8238. payload["compute"]["scaling"]["scaleToZeroTimeout"] = scale_to_zero_timeout
  8239. if scaling_metric:
  8240. payload["compute"]["scaling"]["measure"] = {scaling_metric: scaling_threshold}
  8241. if repository is not None:
  8242. payload["model"]["repository"] = repository
  8243. if framework is not None:
  8244. payload["model"]["framework"] = framework
  8245. if revision is not None:
  8246. payload["model"]["revision"] = revision
  8247. if task is not None:
  8248. payload["model"]["task"] = task
  8249. if custom_image is not None:
  8250. payload["model"]["image"] = {"custom": custom_image}
  8251. if env is not None:
  8252. payload["model"]["env"] = env
  8253. if secrets is not None:
  8254. payload["model"]["secrets"] = secrets
  8255. if domain is not None:
  8256. payload["route"]["domain"] = domain
  8257. if path is not None:
  8258. payload["route"]["path"] = path
  8259. if cache_http_responses is not None:
  8260. payload["cacheHttpResponses"] = cache_http_responses
  8261. if tags is not None:
  8262. payload["tags"] = tags
  8263. response = get_session().put(
  8264. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}",
  8265. headers=self._build_hf_headers(token=token),
  8266. json=payload,
  8267. )
  8268. hf_raise_for_status(response)
  8269. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  8270. def delete_inference_endpoint(
  8271. self, name: str, *, namespace: str | None = None, token: bool | str | None = None
  8272. ) -> None:
  8273. """Delete an Inference Endpoint.
  8274. This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
  8275. to pause it with [`pause_inference_endpoint`] or scale it to zero with [`scale_to_zero_inference_endpoint`].
  8276. For convenience, you can also delete an Inference Endpoint using [`InferenceEndpoint.delete`].
  8277. Args:
  8278. name (`str`):
  8279. The name of the Inference Endpoint to delete.
  8280. namespace (`str`, *optional*):
  8281. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  8282. token (`bool` or `str`, *optional*):
  8283. A valid user access token (string). Defaults to the locally saved
  8284. token, which is the recommended method for authentication (see
  8285. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8286. To disable authentication, pass `False`.
  8287. """
  8288. namespace = namespace or self._get_namespace(token=token)
  8289. response = get_session().delete(
  8290. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}",
  8291. headers=self._build_hf_headers(token=token),
  8292. )
  8293. hf_raise_for_status(response)
  8294. def pause_inference_endpoint(
  8295. self, name: str, *, namespace: str | None = None, token: bool | str | None = None
  8296. ) -> InferenceEndpoint:
  8297. """Pause an Inference Endpoint.
  8298. A paused Inference Endpoint will not be charged. It can be resumed at any time using [`resume_inference_endpoint`].
  8299. This is different than scaling the Inference Endpoint to zero with [`scale_to_zero_inference_endpoint`], which
  8300. would be automatically restarted when a request is made to it.
  8301. For convenience, you can also pause an Inference Endpoint using [`pause_inference_endpoint`].
  8302. Args:
  8303. name (`str`):
  8304. The name of the Inference Endpoint to pause.
  8305. namespace (`str`, *optional*):
  8306. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  8307. token (`bool` or `str`, *optional*):
  8308. A valid user access token (string). Defaults to the locally saved
  8309. token, which is the recommended method for authentication (see
  8310. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8311. To disable authentication, pass `False`.
  8312. Returns:
  8313. [`InferenceEndpoint`]: information about the paused Inference Endpoint.
  8314. """
  8315. namespace = namespace or self._get_namespace(token=token)
  8316. response = get_session().post(
  8317. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/pause",
  8318. headers=self._build_hf_headers(token=token),
  8319. )
  8320. hf_raise_for_status(response)
  8321. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  8322. def resume_inference_endpoint(
  8323. self,
  8324. name: str,
  8325. *,
  8326. namespace: str | None = None,
  8327. running_ok: bool = True,
  8328. token: bool | str | None = None,
  8329. ) -> InferenceEndpoint:
  8330. """Resume an Inference Endpoint.
  8331. For convenience, you can also resume an Inference Endpoint using [`InferenceEndpoint.resume`].
  8332. Args:
  8333. name (`str`):
  8334. The name of the Inference Endpoint to resume.
  8335. namespace (`str`, *optional*):
  8336. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  8337. running_ok (`bool`, *optional*):
  8338. If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to
  8339. `True`.
  8340. token (`bool` or `str`, *optional*):
  8341. A valid user access token (string). Defaults to the locally saved
  8342. token, which is the recommended method for authentication (see
  8343. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8344. To disable authentication, pass `False`.
  8345. Returns:
  8346. [`InferenceEndpoint`]: information about the resumed Inference Endpoint.
  8347. """
  8348. namespace = namespace or self._get_namespace(token=token)
  8349. response = get_session().post(
  8350. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/resume",
  8351. headers=self._build_hf_headers(token=token),
  8352. )
  8353. try:
  8354. hf_raise_for_status(response)
  8355. except HfHubHTTPError as error:
  8356. # If already running (and it's ok), then fetch current status and return
  8357. if running_ok and error.response.status_code == 400 and "already running" in error.response.text:
  8358. return self.get_inference_endpoint(name, namespace=namespace, token=token)
  8359. # Otherwise, raise the error
  8360. raise
  8361. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  8362. def scale_to_zero_inference_endpoint(
  8363. self, name: str, *, namespace: str | None = None, token: bool | str | None = None
  8364. ) -> InferenceEndpoint:
  8365. """Scale Inference Endpoint to zero.
  8366. An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a
  8367. cold start delay. This is different than pausing the Inference Endpoint with [`pause_inference_endpoint`], which
  8368. would require a manual resume with [`resume_inference_endpoint`].
  8369. For convenience, you can also scale an Inference Endpoint to zero using [`InferenceEndpoint.scale_to_zero`].
  8370. Args:
  8371. name (`str`):
  8372. The name of the Inference Endpoint to scale to zero.
  8373. namespace (`str`, *optional*):
  8374. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  8375. token (`bool` or `str`, *optional*):
  8376. A valid user access token (string). Defaults to the locally saved
  8377. token, which is the recommended method for authentication (see
  8378. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8379. To disable authentication, pass `False`.
  8380. Returns:
  8381. [`InferenceEndpoint`]: information about the scaled-to-zero Inference Endpoint.
  8382. """
  8383. namespace = namespace or self._get_namespace(token=token)
  8384. response = get_session().post(
  8385. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/scale-to-zero",
  8386. headers=self._build_hf_headers(token=token),
  8387. )
  8388. hf_raise_for_status(response)
  8389. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  8390. def _get_namespace(self, token: bool | str | None = None) -> str:
  8391. """Get the default namespace for the current user."""
  8392. me = self.whoami(token=token)
  8393. if me["type"] == "user":
  8394. return me["name"]
  8395. else:
  8396. raise ValueError(
  8397. "Cannot determine default namespace. You must provide a 'namespace' as input or be logged in as a"
  8398. " user."
  8399. )
  8400. ########################
  8401. # Collection Endpoints #
  8402. ########################
  8403. @validate_hf_hub_args
  8404. def list_collections(
  8405. self,
  8406. *,
  8407. owner: list[str] | str | None = None,
  8408. item: list[str] | str | None = None,
  8409. sort: CollectionSort_T | None = None,
  8410. limit: int | None = None,
  8411. token: bool | str | None = None,
  8412. ) -> Iterable[Collection]:
  8413. """List collections on the Huggingface Hub, given some filters.
  8414. > [!WARNING]
  8415. > When listing collections, the item list per collection is truncated to 4 items maximum. To retrieve all items
  8416. > from a collection, you must use [`get_collection`].
  8417. Args:
  8418. owner (`list[str]` or `str`, *optional*):
  8419. Filter by owner's username.
  8420. item (`list[str]` or `str`, *optional*):
  8421. Filter collections containing a particular items. Example: `"models/teknium/OpenHermes-2.5-Mistral-7B"`, `"datasets/squad"` or `"papers/2311.12983"`.
  8422. sort (`Literal["lastModified", "trending", "upvotes"]`, *optional*):
  8423. Sort collections by last modified, trending or upvotes.
  8424. limit (`int`, *optional*):
  8425. Maximum number of collections to be returned.
  8426. token (`bool` or `str`, *optional*):
  8427. A valid user access token (string). Defaults to the locally saved
  8428. token, which is the recommended method for authentication (see
  8429. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8430. To disable authentication, pass `False`.
  8431. Returns:
  8432. `Iterable[Collection]`: an iterable of [`Collection`] objects.
  8433. """
  8434. # Construct the API endpoint
  8435. path = f"{self.endpoint}/api/collections"
  8436. headers = self._build_hf_headers(token=token)
  8437. params: dict = {}
  8438. if owner is not None:
  8439. params.update({"owner": owner})
  8440. if item is not None:
  8441. params.update({"item": item})
  8442. if sort is not None:
  8443. params.update({"sort": sort})
  8444. if limit is not None:
  8445. params.update({"limit": limit})
  8446. # Paginate over the results until limit is reached
  8447. items = paginate(path, headers=headers, params=params)
  8448. if limit is not None:
  8449. items = islice(items, limit) # Do not iterate over all pages
  8450. # Parse as Collection and return
  8451. for position, collection_data in enumerate(items):
  8452. yield Collection(position=position, **collection_data)
  8453. def get_collection(self, collection_slug: str, *, token: bool | str | None = None) -> Collection:
  8454. """Gets information about a Collection on the Hub.
  8455. Args:
  8456. collection_slug (`str`):
  8457. Slug of the collection of the Hub. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  8458. token (`bool` or `str`, *optional*):
  8459. A valid user access token (string). Defaults to the locally saved
  8460. token, which is the recommended method for authentication (see
  8461. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8462. To disable authentication, pass `False`.
  8463. Returns: [`Collection`]
  8464. Example:
  8465. ```py
  8466. >>> from huggingface_hub import get_collection
  8467. >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
  8468. >>> collection.title
  8469. 'Recent models'
  8470. >>> len(collection.items)
  8471. 37
  8472. >>> collection.items[0]
  8473. CollectionItem(
  8474. item_object_id='651446103cd773a050bf64c2',
  8475. item_id='TheBloke/U-Amethyst-20B-AWQ',
  8476. item_type='model',
  8477. position=88,
  8478. note=None
  8479. )
  8480. ```
  8481. """
  8482. r = get_session().get(
  8483. f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token)
  8484. )
  8485. hf_raise_for_status(r)
  8486. return Collection(**{**r.json(), "endpoint": self.endpoint})
  8487. def create_collection(
  8488. self,
  8489. title: str,
  8490. *,
  8491. namespace: str | None = None,
  8492. description: str | None = None,
  8493. private: bool = False,
  8494. exists_ok: bool = False,
  8495. token: bool | str | None = None,
  8496. ) -> Collection:
  8497. """Create a new Collection on the Hub.
  8498. Args:
  8499. title (`str`):
  8500. Title of the collection to create. Example: `"Recent models"`.
  8501. namespace (`str`, *optional*):
  8502. Namespace of the collection to create (username or org). Will default to the owner name.
  8503. description (`str`, *optional*):
  8504. Description of the collection to create.
  8505. private (`bool`, *optional*):
  8506. Whether the collection should be private or not. Defaults to `False` (i.e. public collection).
  8507. exists_ok (`bool`, *optional*):
  8508. If `True`, do not raise an error if collection already exists.
  8509. token (`bool` or `str`, *optional*):
  8510. A valid user access token (string). Defaults to the locally saved
  8511. token, which is the recommended method for authentication (see
  8512. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8513. To disable authentication, pass `False`.
  8514. Returns: [`Collection`]
  8515. Example:
  8516. ```py
  8517. >>> from huggingface_hub import create_collection
  8518. >>> collection = create_collection(
  8519. ... title="ICCV 2023",
  8520. ... description="Portfolio of models, papers and demos I presented at ICCV 2023",
  8521. ... )
  8522. >>> collection.slug
  8523. "username/iccv-2023-64f9a55bb3115b4f513ec026"
  8524. ```
  8525. """
  8526. if namespace is None:
  8527. namespace = self.whoami(token)["name"]
  8528. payload = {
  8529. "title": title,
  8530. "namespace": namespace,
  8531. "private": private,
  8532. }
  8533. if description is not None:
  8534. payload["description"] = description
  8535. r = get_session().post(
  8536. f"{self.endpoint}/api/collections", headers=self._build_hf_headers(token=token), json=payload
  8537. )
  8538. try:
  8539. hf_raise_for_status(r)
  8540. except HfHubHTTPError as err:
  8541. if exists_ok and err.response.status_code == 409:
  8542. # Collection already exists and `exists_ok=True`
  8543. slug = r.json()["slug"]
  8544. return self.get_collection(slug, token=token)
  8545. else:
  8546. raise
  8547. return Collection(**{**r.json(), "endpoint": self.endpoint})
  8548. def update_collection_metadata(
  8549. self,
  8550. collection_slug: str,
  8551. *,
  8552. title: str | None = None,
  8553. description: str | None = None,
  8554. position: int | None = None,
  8555. private: bool | None = None,
  8556. theme: str | None = None,
  8557. token: bool | str | None = None,
  8558. ) -> Collection:
  8559. """Update metadata of a collection on the Hub.
  8560. All arguments are optional. Only provided metadata will be updated.
  8561. Args:
  8562. collection_slug (`str`):
  8563. Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  8564. title (`str`):
  8565. Title of the collection to update.
  8566. description (`str`, *optional*):
  8567. Description of the collection to update.
  8568. position (`int`, *optional*):
  8569. New position of the collection in the list of collections of the user.
  8570. private (`bool`, *optional*):
  8571. Whether the collection should be private or not.
  8572. theme (`str`, *optional*):
  8573. Theme of the collection on the Hub.
  8574. token (`bool` or `str`, *optional*):
  8575. A valid user access token (string). Defaults to the locally saved
  8576. token, which is the recommended method for authentication (see
  8577. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8578. To disable authentication, pass `False`.
  8579. Returns: [`Collection`]
  8580. Example:
  8581. ```py
  8582. >>> from huggingface_hub import update_collection_metadata
  8583. >>> collection = update_collection_metadata(
  8584. ... collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026",
  8585. ... title="ICCV Oct. 2023"
  8586. ... description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023",
  8587. ... private=False,
  8588. ... theme="pink",
  8589. ... )
  8590. >>> collection.slug
  8591. "username/iccv-oct-2023-64f9a55bb3115b4f513ec026"
  8592. # ^collection slug got updated but not the trailing ID
  8593. ```
  8594. """
  8595. payload = {
  8596. "position": position,
  8597. "private": private,
  8598. "theme": theme,
  8599. "title": title,
  8600. "description": description,
  8601. }
  8602. r = get_session().patch(
  8603. f"{self.endpoint}/api/collections/{collection_slug}",
  8604. headers=self._build_hf_headers(token=token),
  8605. # Only send not-none values to the API
  8606. json={key: value for key, value in payload.items() if value is not None},
  8607. )
  8608. hf_raise_for_status(r)
  8609. return Collection(**{**r.json()["data"], "endpoint": self.endpoint})
  8610. def delete_collection(
  8611. self, collection_slug: str, *, missing_ok: bool = False, token: bool | str | None = None
  8612. ) -> None:
  8613. """Delete a collection on the Hub.
  8614. Args:
  8615. collection_slug (`str`):
  8616. Slug of the collection to delete. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  8617. missing_ok (`bool`, *optional*):
  8618. If `True`, do not raise an error if collection doesn't exists.
  8619. token (`bool` or `str`, *optional*):
  8620. A valid user access token (string). Defaults to the locally saved
  8621. token, which is the recommended method for authentication (see
  8622. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8623. To disable authentication, pass `False`.
  8624. Example:
  8625. ```py
  8626. >>> from huggingface_hub import delete_collection
  8627. >>> collection = delete_collection("username/useless-collection-64f9a55bb3115b4f513ec026", missing_ok=True)
  8628. ```
  8629. > [!WARNING]
  8630. > This is a non-revertible action. A deleted collection cannot be restored.
  8631. """
  8632. r = get_session().delete(
  8633. f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token)
  8634. )
  8635. try:
  8636. hf_raise_for_status(r)
  8637. except HfHubHTTPError as err:
  8638. if missing_ok and err.response.status_code == 404:
  8639. # Collection doesn't exists and `missing_ok=True`
  8640. return
  8641. else:
  8642. raise
  8643. def add_collection_item(
  8644. self,
  8645. collection_slug: str,
  8646. item_id: str,
  8647. item_type: CollectionItemType_T,
  8648. *,
  8649. note: str | None = None,
  8650. exists_ok: bool = False,
  8651. token: bool | str | None = None,
  8652. ) -> Collection:
  8653. """Add an item to a collection on the Hub.
  8654. Args:
  8655. collection_slug (`str`):
  8656. Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  8657. item_id (`str`):
  8658. Id of the item to add to the collection. Use the repo_id for repos/spaces/datasets,
  8659. the paper id for papers, the slug of another collection (e.g. `"moonshotai/kimi-k2"`)
  8660. or a bucket id (e.g. `"namespace/bucket-name"`).
  8661. item_type (`str`):
  8662. Type of the item to add. Can be one of `"model"`, `"dataset"`, `"space"`, `"paper"`, `"collection"`
  8663. or `"bucket"`.
  8664. note (`str`, *optional*):
  8665. A note to attach to the item in the collection. The maximum size for a note is 500 characters.
  8666. exists_ok (`bool`, *optional*):
  8667. If `True`, do not raise an error if item already exists.
  8668. token (`bool` or `str`, *optional*):
  8669. A valid user access token (string). Defaults to the locally saved
  8670. token, which is the recommended method for authentication (see
  8671. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8672. To disable authentication, pass `False`.
  8673. Returns: [`Collection`]
  8674. Raises:
  8675. [`HfHubHTTPError`]:
  8676. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  8677. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  8678. [`HfHubHTTPError`]:
  8679. HTTP 404 if the item you try to add to the collection does not exist on the Hub.
  8680. [`HfHubHTTPError`]:
  8681. HTTP 409 if the item you try to add to the collection is already in the collection (and exists_ok=False)
  8682. Example:
  8683. ```py
  8684. >>> from huggingface_hub import add_collection_item
  8685. >>> collection = add_collection_item(
  8686. ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
  8687. ... item_id="pierre-loic/climate-news-articles",
  8688. ... item_type="dataset"
  8689. ... )
  8690. >>> collection.items[-1].item_id
  8691. "pierre-loic/climate-news-articles"
  8692. # ^item got added to the collection on last position
  8693. # Add item with a note
  8694. >>> add_collection_item(
  8695. ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
  8696. ... item_id="datasets/climate_fever",
  8697. ... item_type="dataset"
  8698. ... note="This dataset adopts the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet."
  8699. ... )
  8700. (...)
  8701. ```
  8702. """
  8703. payload: dict[str, Any] = {"item": {"id": item_id, "type": item_type}}
  8704. if note is not None:
  8705. payload["note"] = note
  8706. r = get_session().post(
  8707. f"{self.endpoint}/api/collections/{collection_slug}/items",
  8708. headers=self._build_hf_headers(token=token),
  8709. json=payload,
  8710. )
  8711. try:
  8712. hf_raise_for_status(r)
  8713. except HfHubHTTPError as err:
  8714. if exists_ok and err.response.status_code == 409:
  8715. # Item already exists and `exists_ok=True`
  8716. return self.get_collection(collection_slug, token=token)
  8717. else:
  8718. raise
  8719. return Collection(**{**r.json(), "endpoint": self.endpoint})
  8720. def update_collection_item(
  8721. self,
  8722. collection_slug: str,
  8723. item_object_id: str,
  8724. *,
  8725. note: str | None = None,
  8726. position: int | None = None,
  8727. token: bool | str | None = None,
  8728. ) -> None:
  8729. """Update an item in a collection.
  8730. Args:
  8731. collection_slug (`str`):
  8732. Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  8733. item_object_id (`str`):
  8734. ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
  8735. It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`.
  8736. note (`str`, *optional*):
  8737. A note to attach to the item in the collection. The maximum size for a note is 500 characters.
  8738. position (`int`, *optional*):
  8739. New position of the item in the collection.
  8740. token (`bool` or `str`, *optional*):
  8741. A valid user access token (string). Defaults to the locally saved
  8742. token, which is the recommended method for authentication (see
  8743. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8744. To disable authentication, pass `False`.
  8745. Example:
  8746. ```py
  8747. >>> from huggingface_hub import get_collection, update_collection_item
  8748. # Get collection first
  8749. >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
  8750. # Update item based on its ID (add note + update position)
  8751. >>> update_collection_item(
  8752. ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
  8753. ... item_object_id=collection.items[-1].item_object_id,
  8754. ... note="Newly updated model!"
  8755. ... position=0,
  8756. ... )
  8757. ```
  8758. """
  8759. payload = {"position": position, "note": note}
  8760. r = get_session().patch(
  8761. f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}",
  8762. headers=self._build_hf_headers(token=token),
  8763. # Only send not-none values to the API
  8764. json={key: value for key, value in payload.items() if value is not None},
  8765. )
  8766. hf_raise_for_status(r)
  8767. def delete_collection_item(
  8768. self,
  8769. collection_slug: str,
  8770. item_object_id: str,
  8771. *,
  8772. missing_ok: bool = False,
  8773. token: bool | str | None = None,
  8774. ) -> None:
  8775. """Delete an item from a collection.
  8776. Args:
  8777. collection_slug (`str`):
  8778. Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  8779. item_object_id (`str`):
  8780. ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
  8781. It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`.
  8782. missing_ok (`bool`, *optional*):
  8783. If `True`, do not raise an error if item doesn't exists.
  8784. token (`bool` or `str`, *optional*):
  8785. A valid user access token (string). Defaults to the locally saved
  8786. token, which is the recommended method for authentication (see
  8787. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8788. To disable authentication, pass `False`.
  8789. Example:
  8790. ```py
  8791. >>> from huggingface_hub import get_collection, delete_collection_item
  8792. # Get collection first
  8793. >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
  8794. # Delete item based on its ID
  8795. >>> delete_collection_item(
  8796. ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
  8797. ... item_object_id=collection.items[-1].item_object_id,
  8798. ... )
  8799. ```
  8800. """
  8801. r = get_session().delete(
  8802. f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}",
  8803. headers=self._build_hf_headers(token=token),
  8804. )
  8805. try:
  8806. hf_raise_for_status(r)
  8807. except HfHubHTTPError as err:
  8808. if missing_ok and err.response.status_code == 404:
  8809. # Item already deleted and `missing_ok=True`
  8810. return
  8811. else:
  8812. raise
  8813. ##########################
  8814. # Manage access requests #
  8815. ##########################
  8816. @validate_hf_hub_args
  8817. def list_pending_access_requests(
  8818. self, repo_id: str, *, repo_type: str | None = None, token: bool | str | None = None
  8819. ) -> Iterable[AccessRequest]:
  8820. """
  8821. Get pending access requests for a given gated repo.
  8822. A pending request means the user has requested access to the repo but the request has not been processed yet.
  8823. If the approval mode is automatic, this list should be empty. Pending requests can be accepted or rejected
  8824. using [`accept_access_request`] and [`reject_access_request`].
  8825. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  8826. Args:
  8827. repo_id (`str`):
  8828. The id of the repo to get access requests for.
  8829. repo_type (`str`, *optional*):
  8830. The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
  8831. Defaults to `model`.
  8832. token (`bool` or `str`, *optional*):
  8833. A valid user access token (string). Defaults to the locally saved
  8834. token, which is the recommended method for authentication (see
  8835. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8836. To disable authentication, pass `False`.
  8837. Returns:
  8838. `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
  8839. `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
  8840. be populated with user's answers.
  8841. Raises:
  8842. [`HfHubHTTPError`]:
  8843. HTTP 400 if the repo is not gated.
  8844. [`HfHubHTTPError`]:
  8845. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  8846. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  8847. Example:
  8848. ```py
  8849. >>> from huggingface_hub import list_pending_access_requests, accept_access_request
  8850. # List pending requests
  8851. >>> requests = list(list_pending_access_requests("meta-llama/Llama-2-7b"))
  8852. >>> len(requests)
  8853. 411
  8854. >>> requests[0]
  8855. [
  8856. AccessRequest(
  8857. username='clem',
  8858. fullname='Clem 🤗',
  8859. email='***',
  8860. timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
  8861. status='pending',
  8862. fields=None,
  8863. ),
  8864. ...
  8865. ]
  8866. # Accept Clem's request
  8867. >>> accept_access_request("meta-llama/Llama-2-7b", "clem")
  8868. ```
  8869. """
  8870. yield from self._list_access_requests(repo_id, "pending", repo_type=repo_type, token=token)
  8871. @validate_hf_hub_args
  8872. def list_accepted_access_requests(
  8873. self, repo_id: str, *, repo_type: str | None = None, token: bool | str | None = None
  8874. ) -> Iterable[AccessRequest]:
  8875. """
  8876. Get accepted access requests for a given gated repo.
  8877. An accepted request means the user has requested access to the repo and the request has been accepted. The user
  8878. can download any file of the repo. If the approval mode is automatic, this list should contains by default all
  8879. requests. Accepted requests can be cancelled or rejected at any time using [`cancel_access_request`] and
  8880. [`reject_access_request`]. A cancelled request will go back to the pending list while a rejected request will
  8881. go to the rejected list. In both cases, the user will lose access to the repo.
  8882. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  8883. Args:
  8884. repo_id (`str`):
  8885. The id of the repo to get access requests for.
  8886. repo_type (`str`, *optional*):
  8887. The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
  8888. Defaults to `model`.
  8889. token (`bool` or `str`, *optional*):
  8890. A valid user access token (string). Defaults to the locally saved
  8891. token, which is the recommended method for authentication (see
  8892. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8893. To disable authentication, pass `False`.
  8894. Returns:
  8895. `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
  8896. `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
  8897. be populated with user's answers.
  8898. Raises:
  8899. [`HfHubHTTPError`]:
  8900. HTTP 400 if the repo is not gated.
  8901. [`HfHubHTTPError`]:
  8902. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  8903. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  8904. Example:
  8905. ```py
  8906. >>> from huggingface_hub import list_accepted_access_requests
  8907. >>> requests = list(list_accepted_access_requests("meta-llama/Llama-2-7b"))
  8908. >>> len(requests)
  8909. 411
  8910. >>> requests[0]
  8911. [
  8912. AccessRequest(
  8913. username='clem',
  8914. fullname='Clem 🤗',
  8915. email='***',
  8916. timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
  8917. status='accepted',
  8918. fields=None,
  8919. ),
  8920. ...
  8921. ]
  8922. ```
  8923. """
  8924. yield from self._list_access_requests(repo_id, "accepted", repo_type=repo_type, token=token)
  8925. @validate_hf_hub_args
  8926. def list_rejected_access_requests(
  8927. self, repo_id: str, *, repo_type: str | None = None, token: bool | str | None = None
  8928. ) -> Iterable[AccessRequest]:
  8929. """
  8930. Get rejected access requests for a given gated repo.
  8931. A rejected request means the user has requested access to the repo and the request has been explicitly rejected
  8932. by a repo owner (either you or another user from your organization). The user cannot download any file of the
  8933. repo. Rejected requests can be accepted or cancelled at any time using [`accept_access_request`] and
  8934. [`cancel_access_request`]. A cancelled request will go back to the pending list while an accepted request will
  8935. go to the accepted list.
  8936. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  8937. Args:
  8938. repo_id (`str`):
  8939. The id of the repo to get access requests for.
  8940. repo_type (`str`, *optional*):
  8941. The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
  8942. Defaults to `model`.
  8943. token (`bool` or `str`, *optional*):
  8944. A valid user access token (string). Defaults to the locally saved
  8945. token, which is the recommended method for authentication (see
  8946. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8947. To disable authentication, pass `False`.
  8948. Returns:
  8949. `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
  8950. `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
  8951. be populated with user's answers.
  8952. Raises:
  8953. [`HfHubHTTPError`]:
  8954. HTTP 400 if the repo is not gated.
  8955. [`HfHubHTTPError`]:
  8956. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  8957. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  8958. Example:
  8959. ```py
  8960. >>> from huggingface_hub import list_rejected_access_requests
  8961. >>> requests = list(list_rejected_access_requests("meta-llama/Llama-2-7b"))
  8962. >>> len(requests)
  8963. 411
  8964. >>> requests[0]
  8965. [
  8966. AccessRequest(
  8967. username='clem',
  8968. fullname='Clem 🤗',
  8969. email='***',
  8970. timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
  8971. status='rejected',
  8972. fields=None,
  8973. ),
  8974. ...
  8975. ]
  8976. ```
  8977. """
  8978. yield from self._list_access_requests(repo_id, "rejected", repo_type=repo_type, token=token)
  8979. def _list_access_requests(
  8980. self,
  8981. repo_id: str,
  8982. status: Literal["accepted", "rejected", "pending"],
  8983. repo_type: str | None = None,
  8984. token: bool | str | None = None,
  8985. ) -> Iterable[AccessRequest]:
  8986. if repo_type not in constants.REPO_TYPES:
  8987. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  8988. if repo_type is None:
  8989. repo_type = constants.REPO_TYPE_MODEL
  8990. for request in paginate(
  8991. f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/{status}",
  8992. params={},
  8993. headers=self._build_hf_headers(token=token),
  8994. ):
  8995. yield AccessRequest(
  8996. username=request["user"]["user"],
  8997. fullname=request["user"]["fullname"],
  8998. email=request["user"].get("email"),
  8999. status=request["status"],
  9000. timestamp=parse_datetime(request["timestamp"]),
  9001. fields=request.get("fields"), # only if custom fields in form
  9002. )
  9003. @validate_hf_hub_args
  9004. def cancel_access_request(
  9005. self, repo_id: str, user: str, *, repo_type: str | None = None, token: bool | str | None = None
  9006. ) -> None:
  9007. """
  9008. Cancel an access request from a user for a given gated repo.
  9009. A cancelled request will go back to the pending list and the user will lose access to the repo.
  9010. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  9011. Args:
  9012. repo_id (`str`):
  9013. The id of the repo to cancel access request for.
  9014. user (`str`):
  9015. The username of the user which access request should be cancelled.
  9016. repo_type (`str`, *optional*):
  9017. The type of the repo to cancel access request for. Must be one of `model`, `dataset` or `space`.
  9018. Defaults to `model`.
  9019. token (`bool` or `str`, *optional*):
  9020. A valid user access token (string). Defaults to the locally saved
  9021. token, which is the recommended method for authentication (see
  9022. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9023. To disable authentication, pass `False`.
  9024. Raises:
  9025. [`HfHubHTTPError`]:
  9026. HTTP 400 if the repo is not gated.
  9027. [`HfHubHTTPError`]:
  9028. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  9029. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  9030. [`HfHubHTTPError`]:
  9031. HTTP 404 if the user does not exist on the Hub.
  9032. [`HfHubHTTPError`]:
  9033. HTTP 404 if the user access request cannot be found.
  9034. [`HfHubHTTPError`]:
  9035. HTTP 404 if the user access request is already in the pending list.
  9036. """
  9037. self._handle_access_request(repo_id, user, "pending", repo_type=repo_type, token=token)
  9038. @validate_hf_hub_args
  9039. def accept_access_request(
  9040. self, repo_id: str, user: str, *, repo_type: str | None = None, token: bool | str | None = None
  9041. ) -> None:
  9042. """
  9043. Accept an access request from a user for a given gated repo.
  9044. Once the request is accepted, the user will be able to download any file of the repo and access the community
  9045. tab. If the approval mode is automatic, you don't have to accept requests manually. An accepted request can be
  9046. cancelled or rejected at any time using [`cancel_access_request`] and [`reject_access_request`].
  9047. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  9048. Args:
  9049. repo_id (`str`):
  9050. The id of the repo to accept access request for.
  9051. user (`str`):
  9052. The username of the user which access request should be accepted.
  9053. repo_type (`str`, *optional*):
  9054. The type of the repo to accept access request for. Must be one of `model`, `dataset` or `space`.
  9055. Defaults to `model`.
  9056. token (`bool` or `str`, *optional*):
  9057. A valid user access token (string). Defaults to the locally saved
  9058. token, which is the recommended method for authentication (see
  9059. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9060. To disable authentication, pass `False`.
  9061. Raises:
  9062. [`HfHubHTTPError`]:
  9063. HTTP 400 if the repo is not gated.
  9064. [`HfHubHTTPError`]:
  9065. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  9066. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  9067. [`HfHubHTTPError`]:
  9068. HTTP 404 if the user does not exist on the Hub.
  9069. [`HfHubHTTPError`]:
  9070. HTTP 404 if the user access request cannot be found.
  9071. [`HfHubHTTPError`]:
  9072. HTTP 404 if the user access request is already in the accepted list.
  9073. """
  9074. self._handle_access_request(repo_id, user, "accepted", repo_type=repo_type, token=token)
  9075. @validate_hf_hub_args
  9076. def reject_access_request(
  9077. self,
  9078. repo_id: str,
  9079. user: str,
  9080. *,
  9081. repo_type: str | None = None,
  9082. rejection_reason: str | None,
  9083. token: bool | str | None = None,
  9084. ) -> None:
  9085. """
  9086. Reject an access request from a user for a given gated repo.
  9087. A rejected request will go to the rejected list. The user cannot download any file of the repo. Rejected
  9088. requests can be accepted or cancelled at any time using [`accept_access_request`] and [`cancel_access_request`].
  9089. A cancelled request will go back to the pending list while an accepted request will go to the accepted list.
  9090. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  9091. Args:
  9092. repo_id (`str`):
  9093. The id of the repo to reject access request for.
  9094. user (`str`):
  9095. The username of the user which access request should be rejected.
  9096. repo_type (`str`, *optional*):
  9097. The type of the repo to reject access request for. Must be one of `model`, `dataset` or `space`.
  9098. Defaults to `model`.
  9099. rejection_reason (`str`, *optional*):
  9100. Optional rejection reason that will be visible to the user (max 200 characters).
  9101. token (`bool` or `str`, *optional*):
  9102. A valid user access token (string). Defaults to the locally saved
  9103. token, which is the recommended method for authentication (see
  9104. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9105. To disable authentication, pass `False`.
  9106. Raises:
  9107. [`HfHubHTTPError`]:
  9108. HTTP 400 if the repo is not gated.
  9109. [`HfHubHTTPError`]:
  9110. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  9111. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  9112. [`HfHubHTTPError`]:
  9113. HTTP 404 if the user does not exist on the Hub.
  9114. [`HfHubHTTPError`]:
  9115. HTTP 404 if the user access request cannot be found.
  9116. [`HfHubHTTPError`]:
  9117. HTTP 404 if the user access request is already in the rejected list.
  9118. """
  9119. self._handle_access_request(
  9120. repo_id, user, "rejected", repo_type=repo_type, rejection_reason=rejection_reason, token=token
  9121. )
  9122. @validate_hf_hub_args
  9123. def _handle_access_request(
  9124. self,
  9125. repo_id: str,
  9126. user: str,
  9127. status: Literal["accepted", "rejected", "pending"],
  9128. repo_type: str | None = None,
  9129. rejection_reason: str | None = None,
  9130. token: bool | str | None = None,
  9131. ) -> None:
  9132. if repo_type not in constants.REPO_TYPES:
  9133. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  9134. if repo_type is None:
  9135. repo_type = constants.REPO_TYPE_MODEL
  9136. payload = {"user": user, "status": status}
  9137. if rejection_reason is not None:
  9138. if status != "rejected":
  9139. raise ValueError("`rejection_reason` can only be passed when rejecting an access request.")
  9140. payload["rejectionReason"] = rejection_reason
  9141. response = get_session().post(
  9142. f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/handle",
  9143. headers=self._build_hf_headers(token=token),
  9144. json=payload,
  9145. )
  9146. hf_raise_for_status(response)
  9147. @validate_hf_hub_args
  9148. def grant_access(
  9149. self, repo_id: str, user: str, *, repo_type: str | None = None, token: bool | str | None = None
  9150. ) -> None:
  9151. """
  9152. Grant access to a user for a given gated repo.
  9153. Granting access don't require for the user to send an access request by themselves. The user is automatically
  9154. added to the accepted list meaning they can download the files You can revoke the granted access at any time
  9155. using [`cancel_access_request`] or [`reject_access_request`].
  9156. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  9157. Args:
  9158. repo_id (`str`):
  9159. The id of the repo to grant access to.
  9160. user (`str`):
  9161. The username of the user to grant access.
  9162. repo_type (`str`, *optional*):
  9163. The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`.
  9164. Defaults to `model`.
  9165. token (`bool` or `str`, *optional*):
  9166. A valid user access token (string). Defaults to the locally saved
  9167. token, which is the recommended method for authentication (see
  9168. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9169. To disable authentication, pass `False`.
  9170. Raises:
  9171. [`HfHubHTTPError`]:
  9172. HTTP 400 if the repo is not gated.
  9173. [`HfHubHTTPError`]:
  9174. HTTP 400 if the user already has access to the repo.
  9175. [`HfHubHTTPError`]:
  9176. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  9177. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  9178. [`HfHubHTTPError`]:
  9179. HTTP 404 if the user does not exist on the Hub.
  9180. """
  9181. if repo_type not in constants.REPO_TYPES:
  9182. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  9183. if repo_type is None:
  9184. repo_type = constants.REPO_TYPE_MODEL
  9185. response = get_session().post(
  9186. f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/grant",
  9187. headers=self._build_hf_headers(token=token),
  9188. json={"user": user},
  9189. )
  9190. hf_raise_for_status(response)
  9191. return response.json()
  9192. ###################
  9193. # Manage webhooks #
  9194. ###################
  9195. @validate_hf_hub_args
  9196. def get_webhook(self, webhook_id: str, *, token: bool | str | None = None) -> WebhookInfo:
  9197. """Get a webhook by its id.
  9198. Args:
  9199. webhook_id (`str`):
  9200. The unique identifier of the webhook to get.
  9201. token (`bool` or `str`, *optional*):
  9202. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  9203. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9204. To disable authentication, pass `False`.
  9205. Returns:
  9206. [`WebhookInfo`]:
  9207. Info about the webhook.
  9208. Example:
  9209. ```python
  9210. >>> from huggingface_hub import get_webhook
  9211. >>> webhook = get_webhook("654bbbc16f2ec14d77f109cc")
  9212. >>> print(webhook)
  9213. WebhookInfo(
  9214. id="654bbbc16f2ec14d77f109cc",
  9215. job=None,
  9216. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  9217. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  9218. secret="my-secret",
  9219. domains=["repo", "discussion"],
  9220. disabled=False,
  9221. )
  9222. ```
  9223. """
  9224. response = get_session().get(
  9225. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}",
  9226. headers=self._build_hf_headers(token=token),
  9227. )
  9228. hf_raise_for_status(response)
  9229. webhook_data = response.json()["webhook"]
  9230. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  9231. webhook = WebhookInfo(
  9232. id=webhook_data["id"],
  9233. url=webhook_data.get("url"),
  9234. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  9235. watched=watched_items,
  9236. domains=webhook_data["domains"],
  9237. secret=webhook_data.get("secret"),
  9238. disabled=webhook_data["disabled"],
  9239. )
  9240. return webhook
  9241. @validate_hf_hub_args
  9242. def list_webhooks(self, *, token: bool | str | None = None) -> list[WebhookInfo]:
  9243. """List all configured webhooks.
  9244. Args:
  9245. token (`bool` or `str`, *optional*):
  9246. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  9247. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9248. To disable authentication, pass `False`.
  9249. Returns:
  9250. `list[WebhookInfo]`:
  9251. List of webhook info objects.
  9252. Example:
  9253. ```python
  9254. >>> from huggingface_hub import list_webhooks
  9255. >>> webhooks = list_webhooks()
  9256. >>> len(webhooks)
  9257. 2
  9258. >>> webhooks[0]
  9259. WebhookInfo(
  9260. id="654bbbc16f2ec14d77f109cc",
  9261. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  9262. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  9263. secret="my-secret",
  9264. domains=["repo", "discussion"],
  9265. disabled=False,
  9266. )
  9267. ```
  9268. """
  9269. response = get_session().get(
  9270. f"{constants.ENDPOINT}/api/settings/webhooks",
  9271. headers=self._build_hf_headers(token=token),
  9272. )
  9273. hf_raise_for_status(response)
  9274. webhooks_data = response.json()
  9275. return [
  9276. WebhookInfo(
  9277. id=webhook["id"],
  9278. url=webhook.get("url"),
  9279. job=JobSpec(**webhook["job"]) if webhook.get("job") else None,
  9280. watched=[WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook["watched"]],
  9281. domains=webhook["domains"],
  9282. secret=webhook.get("secret"),
  9283. disabled=webhook["disabled"],
  9284. )
  9285. for webhook in webhooks_data
  9286. ]
  9287. @validate_hf_hub_args
  9288. def create_webhook(
  9289. self,
  9290. *,
  9291. url: str | None = None,
  9292. job_id: str | None = None,
  9293. watched: list[dict | WebhookWatchedItem],
  9294. domains: list[constants.WEBHOOK_DOMAIN_T] | None = None,
  9295. secret: str | None = None,
  9296. token: bool | str | None = None,
  9297. ) -> WebhookInfo:
  9298. """Create a new webhook.
  9299. The webhook can either send a payload to a URL, or trigger a Job to run on Hugging Face infrastructure.
  9300. This function should be called with one of `url` or `job_id`, but not both.
  9301. Args:
  9302. url (`str`):
  9303. URL to send the payload to.
  9304. job_id (`str`):
  9305. ID of the source Job to trigger with the webhook payload in the environment variable WEBHOOK_PAYLOAD.
  9306. Additional environment variables are available for convenience: WEBHOOK_REPO_ID, WEBHOOK_REPO_TYPE and WEBHOOK_SECRET.
  9307. watched (`list[WebhookWatchedItem]`):
  9308. List of [`WebhookWatchedItem`] to be watched by the webhook. It can be users, orgs, models, datasets or spaces.
  9309. Watched items can also be provided as plain dictionaries.
  9310. domains (`list[Literal["repo", "discussion"]]`, optional):
  9311. List of domains to watch. It can be "repo", "discussion" or both.
  9312. secret (`str`, optional):
  9313. A secret to sign the payload with.
  9314. token (`bool` or `str`, *optional*):
  9315. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  9316. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9317. To disable authentication, pass `False`.
  9318. Returns:
  9319. [`WebhookInfo`]:
  9320. Info about the newly created webhook.
  9321. Example:
  9322. Create a webhook that sends a payload to a URL
  9323. ```python
  9324. >>> from huggingface_hub import create_webhook
  9325. >>> payload = create_webhook(
  9326. ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
  9327. ... url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  9328. ... domains=["repo", "discussion"],
  9329. ... secret="my-secret",
  9330. ... )
  9331. >>> print(payload)
  9332. WebhookInfo(
  9333. id="654bbbc16f2ec14d77f109cc",
  9334. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  9335. job=None,
  9336. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  9337. domains=["repo", "discussion"],
  9338. secret="my-secret",
  9339. disabled=False,
  9340. )
  9341. ```
  9342. Run a Job and then create a webhook that triggers this Job
  9343. ```python
  9344. >>> from huggingface_hub import create_webhook, run_job
  9345. >>> job = run_job(
  9346. ... image="ubuntu",
  9347. ... command=["bash", "-c", r"echo An event occurred in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD"],
  9348. ... )
  9349. >>> payload = create_webhook(
  9350. ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
  9351. ... job_id=job.id,
  9352. ... domains=["repo", "discussion"],
  9353. ... secret="my-secret",
  9354. ... )
  9355. >>> print(payload)
  9356. WebhookInfo(
  9357. id="654bbbc16f2ec14d77f109cc",
  9358. url=None,
  9359. job=JobSpec(
  9360. docker_image='ubuntu',
  9361. space_id=None,
  9362. command=['bash', '-c', 'echo An event occurred in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD'],
  9363. arguments=[],
  9364. environment={},
  9365. secrets=[],
  9366. flavor='cpu-basic',
  9367. timeout=None,
  9368. tags=None,
  9369. arch=None
  9370. ),
  9371. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  9372. domains=["repo", "discussion"],
  9373. secret="my-secret",
  9374. disabled=False,
  9375. )
  9376. ```
  9377. """
  9378. watched_dicts = [asdict(item) if isinstance(item, WebhookWatchedItem) else item for item in watched]
  9379. post_webhooks_json: dict = {"watched": watched_dicts}
  9380. if domains is not None:
  9381. post_webhooks_json["domains"] = domains
  9382. if secret is not None:
  9383. post_webhooks_json["secret"] = secret
  9384. if url is not None and job_id is not None:
  9385. raise ValueError("Set `url` or `job_id` but not both.")
  9386. elif url is not None:
  9387. post_webhooks_json["url"] = url
  9388. elif job_id is not None:
  9389. post_webhooks_json["jobSourceId"] = job_id
  9390. else:
  9391. raise ValueError("Missing argument for webhook: `url` or `job_id`.")
  9392. response = get_session().post(
  9393. f"{constants.ENDPOINT}/api/settings/webhooks",
  9394. json=post_webhooks_json,
  9395. headers=self._build_hf_headers(token=token),
  9396. )
  9397. hf_raise_for_status(response)
  9398. webhook_data = response.json()["webhook"]
  9399. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  9400. webhook = WebhookInfo(
  9401. id=webhook_data["id"],
  9402. url=webhook_data.get("url"),
  9403. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  9404. watched=watched_items,
  9405. domains=webhook_data["domains"],
  9406. secret=webhook_data.get("secret"),
  9407. disabled=webhook_data["disabled"],
  9408. )
  9409. return webhook
  9410. @validate_hf_hub_args
  9411. def update_webhook(
  9412. self,
  9413. webhook_id: str,
  9414. *,
  9415. url: str | None = None,
  9416. watched: list[dict | WebhookWatchedItem] | None = None,
  9417. domains: list[constants.WEBHOOK_DOMAIN_T] | None = None,
  9418. secret: str | None = None,
  9419. token: bool | str | None = None,
  9420. ) -> WebhookInfo:
  9421. """Update an existing webhook.
  9422. Args:
  9423. webhook_id (`str`):
  9424. The unique identifier of the webhook to be updated.
  9425. url (`str`, optional):
  9426. The URL to which the payload will be sent.
  9427. watched (`list[WebhookWatchedItem]`, optional):
  9428. List of items to watch. It can be users, orgs, models, datasets, or spaces.
  9429. Refer to [`WebhookWatchedItem`] for more details. Watched items can also be provided as plain dictionaries.
  9430. domains (`list[Literal["repo", "discussion"]]`, optional):
  9431. The domains to watch. This can include "repo", "discussion", or both.
  9432. secret (`str`, optional):
  9433. A secret to sign the payload with, providing an additional layer of security.
  9434. token (`bool` or `str`, *optional*):
  9435. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  9436. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9437. To disable authentication, pass `False`.
  9438. Returns:
  9439. [`WebhookInfo`]:
  9440. Info about the updated webhook.
  9441. Example:
  9442. ```python
  9443. >>> from huggingface_hub import update_webhook
  9444. >>> updated_payload = update_webhook(
  9445. ... webhook_id="654bbbc16f2ec14d77f109cc",
  9446. ... url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  9447. ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
  9448. ... domains=["repo"],
  9449. ... secret="my-secret",
  9450. ... )
  9451. >>> print(updated_payload)
  9452. WebhookInfo(
  9453. id="654bbbc16f2ec14d77f109cc",
  9454. job=None,
  9455. url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  9456. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  9457. domains=["repo"],
  9458. secret="my-secret",
  9459. disabled=False,
  9460. ```
  9461. """
  9462. if watched is None:
  9463. watched = []
  9464. watched_dicts = [asdict(item) if isinstance(item, WebhookWatchedItem) else item for item in watched]
  9465. update_json: dict = {"watched": watched_dicts}
  9466. if url is not None:
  9467. update_json["url"] = url
  9468. if domains is not None:
  9469. update_json["domains"] = domains
  9470. if secret is not None:
  9471. update_json["secret"] = secret
  9472. response = get_session().post(
  9473. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}",
  9474. json=update_json,
  9475. headers=self._build_hf_headers(token=token),
  9476. )
  9477. hf_raise_for_status(response)
  9478. webhook_data = response.json()["webhook"]
  9479. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  9480. webhook = WebhookInfo(
  9481. id=webhook_data["id"],
  9482. url=webhook_data.get("url"),
  9483. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  9484. watched=watched_items,
  9485. domains=webhook_data["domains"],
  9486. secret=webhook_data.get("secret"),
  9487. disabled=webhook_data["disabled"],
  9488. )
  9489. return webhook
  9490. @validate_hf_hub_args
  9491. def enable_webhook(self, webhook_id: str, *, token: bool | str | None = None) -> WebhookInfo:
  9492. """Enable a webhook (makes it "active").
  9493. Args:
  9494. webhook_id (`str`):
  9495. The unique identifier of the webhook to enable.
  9496. token (`bool` or `str`, *optional*):
  9497. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  9498. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9499. To disable authentication, pass `False`.
  9500. Returns:
  9501. [`WebhookInfo`]:
  9502. Info about the enabled webhook.
  9503. Example:
  9504. ```python
  9505. >>> from huggingface_hub import enable_webhook
  9506. >>> enabled_webhook = enable_webhook("654bbbc16f2ec14d77f109cc")
  9507. >>> enabled_webhook
  9508. WebhookInfo(
  9509. id="654bbbc16f2ec14d77f109cc",
  9510. job=None,
  9511. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  9512. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  9513. domains=["repo", "discussion"],
  9514. secret="my-secret",
  9515. disabled=False,
  9516. )
  9517. ```
  9518. """
  9519. response = get_session().post(
  9520. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}/enable",
  9521. headers=self._build_hf_headers(token=token),
  9522. )
  9523. hf_raise_for_status(response)
  9524. webhook_data = response.json()["webhook"]
  9525. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  9526. webhook = WebhookInfo(
  9527. id=webhook_data["id"],
  9528. url=webhook_data.get("url"),
  9529. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  9530. watched=watched_items,
  9531. domains=webhook_data["domains"],
  9532. secret=webhook_data.get("secret"),
  9533. disabled=webhook_data["disabled"],
  9534. )
  9535. return webhook
  9536. @validate_hf_hub_args
  9537. def disable_webhook(self, webhook_id: str, *, token: bool | str | None = None) -> WebhookInfo:
  9538. """Disable a webhook (makes it "disabled").
  9539. Args:
  9540. webhook_id (`str`):
  9541. The unique identifier of the webhook to disable.
  9542. token (`bool` or `str`, *optional*):
  9543. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  9544. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9545. To disable authentication, pass `False`.
  9546. Returns:
  9547. [`WebhookInfo`]:
  9548. Info about the disabled webhook.
  9549. Example:
  9550. ```python
  9551. >>> from huggingface_hub import disable_webhook
  9552. >>> disabled_webhook = disable_webhook("654bbbc16f2ec14d77f109cc")
  9553. >>> disabled_webhook
  9554. WebhookInfo(
  9555. id="654bbbc16f2ec14d77f109cc",
  9556. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  9557. jon=None,
  9558. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  9559. domains=["repo", "discussion"],
  9560. secret="my-secret",
  9561. disabled=True,
  9562. )
  9563. ```
  9564. """
  9565. response = get_session().post(
  9566. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}/disable",
  9567. headers=self._build_hf_headers(token=token),
  9568. )
  9569. hf_raise_for_status(response)
  9570. webhook_data = response.json()["webhook"]
  9571. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  9572. webhook = WebhookInfo(
  9573. id=webhook_data["id"],
  9574. url=webhook_data.get("url"),
  9575. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  9576. watched=watched_items,
  9577. domains=webhook_data["domains"],
  9578. secret=webhook_data.get("secret"),
  9579. disabled=webhook_data["disabled"],
  9580. )
  9581. return webhook
  9582. @validate_hf_hub_args
  9583. def delete_webhook(self, webhook_id: str, *, token: bool | str | None = None) -> None:
  9584. """Delete a webhook.
  9585. Args:
  9586. webhook_id (`str`):
  9587. The unique identifier of the webhook to delete.
  9588. token (`bool` or `str`, *optional*):
  9589. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  9590. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9591. To disable authentication, pass `False`.
  9592. Returns:
  9593. `None`
  9594. Example:
  9595. ```python
  9596. >>> from huggingface_hub import delete_webhook
  9597. >>> delete_webhook("654bbbc16f2ec14d77f109cc")
  9598. ```
  9599. """
  9600. response = get_session().delete(
  9601. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}",
  9602. headers=self._build_hf_headers(token=token),
  9603. )
  9604. hf_raise_for_status(response)
  9605. #############
  9606. # Internals #
  9607. #############
  9608. def _build_hf_headers(
  9609. self,
  9610. token: bool | str | None = None,
  9611. library_name: str | None = None,
  9612. library_version: str | None = None,
  9613. user_agent: dict | str | None = None,
  9614. ) -> dict[str, str]:
  9615. """
  9616. Alias for [`build_hf_headers`] that uses the token from [`HfApi`] client
  9617. when `token` is not provided.
  9618. """
  9619. if token is None:
  9620. # Cannot do `token = token or self.token` as token can be `False`.
  9621. token = self.token
  9622. return build_hf_headers(
  9623. token=token,
  9624. library_name=library_name or self.library_name,
  9625. library_version=library_version or self.library_version,
  9626. user_agent=user_agent or self.user_agent,
  9627. headers=self.headers,
  9628. )
  9629. def _prepare_folder_deletions(
  9630. self,
  9631. repo_id: str,
  9632. repo_type: str | None,
  9633. revision: str | None,
  9634. path_in_repo: str,
  9635. delete_patterns: list[str] | str | None,
  9636. token: bool | str | None = None,
  9637. ) -> list[CommitOperationDelete]:
  9638. """Generate the list of Delete operations for a commit to delete files from a repo.
  9639. List remote files and match them against the `delete_patterns` constraints. Returns a list of [`CommitOperationDelete`]
  9640. with the matching items.
  9641. Note: `.gitattributes` file is essential to make a repo work properly on the Hub. This file will always be
  9642. kept even if it matches the `delete_patterns` constraints.
  9643. """
  9644. if delete_patterns is None:
  9645. # If no delete patterns, no need to list and filter remote files
  9646. return []
  9647. # List remote files
  9648. filenames = self.list_repo_files(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token)
  9649. # Compute relative path in repo
  9650. if path_in_repo and path_in_repo not in (".", "./"):
  9651. path_in_repo = path_in_repo.strip("/") + "/" # harmonize
  9652. relpath_to_abspath = {
  9653. file[len(path_in_repo) :]: file for file in filenames if file.startswith(path_in_repo)
  9654. }
  9655. else:
  9656. relpath_to_abspath = {file: file for file in filenames}
  9657. # Apply filter on relative paths and return
  9658. return [
  9659. CommitOperationDelete(path_in_repo=relpath_to_abspath[relpath], is_folder=False)
  9660. for relpath in filter_repo_objects(relpath_to_abspath.keys(), allow_patterns=delete_patterns)
  9661. if relpath_to_abspath[relpath] != ".gitattributes"
  9662. ]
  9663. def _prepare_upload_folder_additions(
  9664. self,
  9665. folder_path: str | Path,
  9666. path_in_repo: str,
  9667. allow_patterns: list[str] | str | None = None,
  9668. ignore_patterns: list[str] | str | None = None,
  9669. repo_type: str | None = None,
  9670. token: bool | str | None = None,
  9671. ) -> list[CommitOperationAdd]:
  9672. """Generate the list of Add operations for a commit to upload a folder.
  9673. Files not matching the `allow_patterns` (allowlist) and `ignore_patterns` (denylist)
  9674. constraints are discarded.
  9675. """
  9676. folder_path = Path(folder_path).expanduser().resolve()
  9677. if not folder_path.is_dir():
  9678. raise ValueError(f"Provided path: '{folder_path}' is not a directory")
  9679. # List files from folder
  9680. relpath_to_abspath = {
  9681. path.relative_to(folder_path).as_posix(): path
  9682. for path in sorted(folder_path.glob("**/*")) # sorted to be deterministic
  9683. if path.is_file()
  9684. }
  9685. # Filter files
  9686. # Patterns are applied on the path relative to `folder_path`. `path_in_repo` is prefixed after the filtering.
  9687. filtered_repo_objects = list(
  9688. filter_repo_objects(
  9689. relpath_to_abspath.keys(), allow_patterns=allow_patterns, ignore_patterns=ignore_patterns
  9690. )
  9691. )
  9692. prefix = f"{path_in_repo.strip('/')}/" if path_in_repo else ""
  9693. # If updating a README.md file, make sure the metadata format is valid
  9694. # It's better to fail early than to fail after all the files have been hashed.
  9695. if "README.md" in filtered_repo_objects:
  9696. self._validate_yaml(
  9697. content=relpath_to_abspath["README.md"].read_text(encoding="utf8"),
  9698. repo_type=repo_type,
  9699. token=token,
  9700. )
  9701. if len(filtered_repo_objects) > 30:
  9702. log = logger.warning if len(filtered_repo_objects) > 200 else logger.info
  9703. log(
  9704. "It seems you are trying to upload a large folder at once. This might take some time and then fail if "
  9705. "the folder is too large. For such cases, it is recommended to upload in smaller batches or to use "
  9706. "`HfApi().upload_large_folder(...)`/`hf upload-large-folder` instead. For more details, "
  9707. "check out https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#upload-a-large-folder."
  9708. )
  9709. logger.info(f"Start hashing {len(filtered_repo_objects)} files.")
  9710. operations = [
  9711. CommitOperationAdd(
  9712. path_or_fileobj=relpath_to_abspath[relpath], # absolute path on disk
  9713. path_in_repo=prefix + relpath, # "absolute" path in repo
  9714. )
  9715. for relpath in filtered_repo_objects
  9716. ]
  9717. logger.info(f"Finished hashing {len(filtered_repo_objects)} files.")
  9718. return operations
  9719. def _validate_yaml(self, content: str, *, repo_type: str | None = None, token: bool | str | None = None):
  9720. """
  9721. Validate YAML from `README.md`, used before file hashing and upload.
  9722. Args:
  9723. content (`str`):
  9724. Content of `README.md` to validate.
  9725. repo_type (`str`, *optional*):
  9726. The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`.
  9727. Defaults to `model`.
  9728. token (`bool` or `str`, *optional*):
  9729. A valid user access token (string). Defaults to the locally saved
  9730. token, which is the recommended method for authentication (see
  9731. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9732. To disable authentication, pass `False`.
  9733. Raises:
  9734. - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  9735. if YAML is invalid
  9736. """
  9737. repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL
  9738. headers = self._build_hf_headers(token=token)
  9739. response = get_session().post(
  9740. f"{self.endpoint}/api/validate-yaml",
  9741. json={"content": content, "repoType": repo_type},
  9742. headers=headers,
  9743. )
  9744. # Handle warnings (example: empty metadata)
  9745. response_content = response.json()
  9746. message = "\n".join([f"- {warning.get('message')}" for warning in response_content.get("warnings", [])])
  9747. if message:
  9748. warnings.warn(f"Warnings while validating metadata in README.md:\n{message}")
  9749. # Raise on errors
  9750. try:
  9751. hf_raise_for_status(response)
  9752. except BadRequestError as e:
  9753. errors = response_content.get("errors", [])
  9754. message = "\n".join([f"- {error.get('message')}" for error in errors])
  9755. raise ValueError(f"Invalid metadata in README.md.\n{message}") from e
  9756. def get_user_overview(self, username: str, token: bool | str | None = None) -> User:
  9757. """
  9758. Get an overview of a user on the Hub.
  9759. Args:
  9760. username (`str`):
  9761. Username of the user to get an overview of.
  9762. token (`bool` or `str`, *optional*):
  9763. A valid user access token (string). Defaults to the locally saved
  9764. token, which is the recommended method for authentication (see
  9765. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9766. To disable authentication, pass `False`.
  9767. Returns:
  9768. `User`: A [`User`] object with the user's overview.
  9769. Raises:
  9770. [`HfHubHTTPError`]:
  9771. HTTP 404 If the user does not exist on the Hub.
  9772. """
  9773. r = get_session().get(
  9774. f"{constants.ENDPOINT}/api/users/{username}/overview", headers=self._build_hf_headers(token=token)
  9775. )
  9776. hf_raise_for_status(r)
  9777. return User(**r.json())
  9778. @validate_hf_hub_args
  9779. def get_organization_overview(self, organization: str, token: bool | str | None = None) -> Organization:
  9780. """
  9781. Get an overview of an organization on the Hub.
  9782. Args:
  9783. organization (`str`):
  9784. Name of the organization to get an overview of.
  9785. token (`bool` or `str`, *optional*):
  9786. A valid user access token (string). Defaults to the locally saved token, which is the recommended method
  9787. for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9788. To disable authentication, pass `False`.
  9789. Returns:
  9790. `Organization`: An [`Organization`] object with the organization's overview.
  9791. Raises:
  9792. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  9793. HTTP 404 If the organization does not exist on the Hub.
  9794. """
  9795. r = get_session().get(
  9796. f"{constants.ENDPOINT}/api/organizations/{organization}/overview",
  9797. headers=self._build_hf_headers(token=token),
  9798. )
  9799. hf_raise_for_status(r)
  9800. return Organization(**r.json())
  9801. @validate_hf_hub_args
  9802. def list_organization_followers(self, organization: str, token: bool | str | None = None) -> Iterable[User]:
  9803. """
  9804. List followers of an organization on the Hub.
  9805. Args:
  9806. organization (`str`):
  9807. Name of the organization to get the followers of.
  9808. token (`bool` or `str`, *optional*):
  9809. A valid user access token (string). Defaults to the locally saved
  9810. token, which is the recommended method for authentication (see
  9811. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9812. To disable authentication, pass `False`.
  9813. Returns:
  9814. `Iterable[User]`: A list of [`User`] objects with the followers of the organization.
  9815. Raises:
  9816. [`HfHubHTTPError`]:
  9817. HTTP 404 If the organization does not exist on the Hub.
  9818. """
  9819. for follower in paginate(
  9820. path=f"{constants.ENDPOINT}/api/organizations/{organization}/followers",
  9821. params={},
  9822. headers=self._build_hf_headers(token=token),
  9823. ):
  9824. yield User(**follower)
  9825. def list_organization_members(self, organization: str, token: bool | str | None = None) -> Iterable[User]:
  9826. """
  9827. List of members of an organization on the Hub.
  9828. Args:
  9829. organization (`str`):
  9830. Name of the organization to get the members of.
  9831. token (`bool` or `str`, *optional*):
  9832. A valid user access token (string). Defaults to the locally saved
  9833. token, which is the recommended method for authentication (see
  9834. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9835. To disable authentication, pass `False`.
  9836. Returns:
  9837. `Iterable[User]`: A list of [`User`] objects with the members of the organization.
  9838. Raises:
  9839. [`HfHubHTTPError`]:
  9840. HTTP 404 If the organization does not exist on the Hub.
  9841. """
  9842. for member in paginate(
  9843. path=f"{constants.ENDPOINT}/api/organizations/{organization}/members",
  9844. params={},
  9845. headers=self._build_hf_headers(token=token),
  9846. ):
  9847. yield User(**member)
  9848. def list_user_followers(self, username: str, token: bool | str | None = None) -> Iterable[User]:
  9849. """
  9850. Get the list of followers of a user on the Hub.
  9851. Args:
  9852. username (`str`):
  9853. Username of the user to get the followers of.
  9854. token (`bool` or `str`, *optional*):
  9855. A valid user access token (string). Defaults to the locally saved
  9856. token, which is the recommended method for authentication (see
  9857. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9858. To disable authentication, pass `False`.
  9859. Returns:
  9860. `Iterable[User]`: A list of [`User`] objects with the followers of the user.
  9861. Raises:
  9862. [`HfHubHTTPError`]:
  9863. HTTP 404 If the user does not exist on the Hub.
  9864. """
  9865. for follower in paginate(
  9866. path=f"{constants.ENDPOINT}/api/users/{username}/followers",
  9867. params={},
  9868. headers=self._build_hf_headers(token=token),
  9869. ):
  9870. yield User(**follower)
  9871. def list_user_following(self, username: str, token: bool | str | None = None) -> Iterable[User]:
  9872. """
  9873. Get the list of users followed by a user on the Hub.
  9874. Args:
  9875. username (`str`):
  9876. Username of the user to get the users followed by.
  9877. token (`bool` or `str`, *optional*):
  9878. A valid user access token (string). Defaults to the locally saved
  9879. token, which is the recommended method for authentication (see
  9880. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9881. To disable authentication, pass `False`.
  9882. Returns:
  9883. `Iterable[User]`: A list of [`User`] objects with the users followed by the user.
  9884. Raises:
  9885. [`HfHubHTTPError`]:
  9886. HTTP 404 If the user does not exist on the Hub.
  9887. """
  9888. for followed_user in paginate(
  9889. path=f"{constants.ENDPOINT}/api/users/{username}/following",
  9890. params={},
  9891. headers=self._build_hf_headers(token=token),
  9892. ):
  9893. yield User(**followed_user)
  9894. def list_papers(
  9895. self,
  9896. *,
  9897. query: str | None = None,
  9898. limit: int | None = None,
  9899. token: bool | str | None = None,
  9900. ) -> Iterable[PaperInfo]:
  9901. """
  9902. List daily papers on the Hugging Face Hub given a search query.
  9903. Args:
  9904. query (`str`, *optional*):
  9905. A search query string to find papers.
  9906. If provided, returns papers that match the query.
  9907. limit (`int`, *optional*):
  9908. The maximum number of papers to return.
  9909. token (Union[bool, str, None], *optional*):
  9910. A valid user access token (string). Defaults to the locally saved
  9911. token, which is the recommended method for authentication (see
  9912. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  9913. To disable authentication, pass `False`.
  9914. Returns:
  9915. `Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects.
  9916. Example:
  9917. ```python
  9918. >>> from huggingface_hub import HfApi
  9919. >>> api = HfApi()
  9920. # List all papers with "attention" in their title
  9921. >>> api.list_papers(query="attention")
  9922. ```
  9923. """
  9924. path = f"{self.endpoint}/api/papers/search"
  9925. params: dict[str, Any] = {}
  9926. if query:
  9927. params["q"] = query
  9928. if limit is not None:
  9929. params["limit"] = limit
  9930. r = get_session().get(
  9931. path,
  9932. params=params,
  9933. headers=self._build_hf_headers(token=token),
  9934. )
  9935. hf_raise_for_status(r)
  9936. for paper in r.json():
  9937. yield PaperInfo(**paper)
  9938. def paper_info(self, id: str) -> PaperInfo:
  9939. """
  9940. Get information for a paper on the Hub.
  9941. Args:
  9942. id (`str`, **optional**):
  9943. ArXiv id of the paper.
  9944. Returns:
  9945. `PaperInfo`: A `PaperInfo` object.
  9946. Raises:
  9947. [`HfHubHTTPError`]:
  9948. HTTP 404 If the paper does not exist on the Hub.
  9949. """
  9950. path = f"{self.endpoint}/api/papers/{id}"
  9951. r = get_session().get(path)
  9952. hf_raise_for_status(r)
  9953. return PaperInfo(**r.json())
  9954. def read_paper(self, id: str) -> str:
  9955. """
  9956. Get the markdown content of a paper page on the Hub.
  9957. Args:
  9958. id (`str`):
  9959. ArXiv id of the paper.
  9960. Returns:
  9961. `str`: The paper page content as markdown.
  9962. Raises:
  9963. [`HfHubHTTPError`]:
  9964. HTTP 404 If the paper does not exist on the Hub.
  9965. """
  9966. path = f"{self.endpoint}/papers/{id}.md"
  9967. r = get_session().get(path)
  9968. hf_raise_for_status(r)
  9969. return r.text
  9970. def list_daily_papers(
  9971. self,
  9972. *,
  9973. date: str | None = None,
  9974. token: bool | str | None = None,
  9975. week: str | None = None,
  9976. month: str | None = None,
  9977. submitter: str | None = None,
  9978. sort: DailyPapersSort_T | None = None,
  9979. p: int | None = None,
  9980. limit: int | None = None,
  9981. ) -> Iterable[PaperInfo]:
  9982. """
  9983. List the daily papers published on a given date on the Hugging Face Hub.
  9984. Args:
  9985. date (`str`, *optional*):
  9986. Date in ISO format (YYYY-MM-DD) for which to fetch daily papers.
  9987. Defaults to most recent ones.
  9988. token (Union[bool, str, None], *optional*):
  9989. A valid user access token (string). Defaults to the locally saved
  9990. token. To disable authentication, pass `False`.
  9991. week (`str`, *optional*):
  9992. Week in ISO format (YYYY-Www) for which to fetch daily papers. Example, `2025-W09`.
  9993. month (`str`, *optional*):
  9994. Month in ISO format (YYYY-MM) for which to fetch daily papers. Example, `2025-02`.
  9995. submitter (`str`, *optional*):
  9996. Username of the submitter to filter daily papers.
  9997. sort (`Literal["publishedAt", "trending"]`, *optional*):
  9998. Sort order for the daily papers. Can be either by `publishedAt` or by `trending`.
  9999. Defaults to `"publishedAt"`
  10000. p (`int`, *optional*):
  10001. Page number for pagination. Defaults to 0.
  10002. limit (`int`, *optional*):
  10003. Limit of papers to fetch. Defaults to 50.
  10004. Returns:
  10005. `Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects.
  10006. Example:
  10007. ```python
  10008. >>> from huggingface_hub import HfApi
  10009. >>> api = HfApi()
  10010. >>> list(api.list_daily_papers(date="2025-10-29"))
  10011. ```
  10012. """
  10013. path = f"{self.endpoint}/api/daily_papers"
  10014. params = {
  10015. k: v
  10016. for k, v in {
  10017. "p": p,
  10018. "limit": limit,
  10019. "sort": sort,
  10020. "date": date,
  10021. "week": week,
  10022. "month": month,
  10023. "submitter": submitter,
  10024. }.items()
  10025. if v is not None
  10026. }
  10027. r = get_session().get(path, params=params, headers=self._build_hf_headers(token=token))
  10028. hf_raise_for_status(r)
  10029. for paper in r.json():
  10030. yield PaperInfo(**paper)
  10031. def auth_check(
  10032. self,
  10033. repo_id: str,
  10034. *,
  10035. repo_type: str | None = None,
  10036. token: bool | str | None = None,
  10037. write: bool = False,
  10038. ) -> None:
  10039. """
  10040. Check if the provided user token has access to a specific repository on the Hugging Face Hub.
  10041. This method verifies whether the user, authenticated via the provided token, has access to the specified
  10042. repository. If the repository is not found or if the user lacks the required permissions to access it,
  10043. the method raises an appropriate exception.
  10044. Args:
  10045. repo_id (`str`):
  10046. The repository to check for access. Format should be `"user/repo_name"`.
  10047. Example: `"user/my-cool-model"`.
  10048. repo_type (`str`, *optional*):
  10049. The type of the repository. Should be one of `"model"`, `"dataset"`, or `"space"`.
  10050. If not specified, the default is `"model"`.
  10051. token (`Union[bool, str, None]`, *optional*):
  10052. A valid user access token. If not provided, the locally saved token will be used, which is the
  10053. recommended authentication method. Set to `False` to disable authentication.
  10054. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10055. write (`bool`, *optional*):
  10056. If `True`, checks whether the user has content write permission on the repository.
  10057. If `False` (default), only checks for read access.
  10058. Raises:
  10059. [`~utils.RepositoryNotFoundError`]:
  10060. Raised if the repository does not exist, is private, or the user does not have access. This can
  10061. occur if the `repo_id` or `repo_type` is incorrect or if the repository is private but the user
  10062. is not authenticated.
  10063. [`~utils.GatedRepoError`]:
  10064. Raised if the repository exists but is gated and the user is not authorized to access it.
  10065. Example:
  10066. Check if the user has access to a repository:
  10067. ```python
  10068. >>> from huggingface_hub import auth_check
  10069. >>> from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
  10070. try:
  10071. auth_check("user/my-cool-model")
  10072. except GatedRepoError:
  10073. # Handle gated repository error
  10074. print("You do not have permission to access this gated repository.")
  10075. except RepositoryNotFoundError:
  10076. # Handle repository not found error
  10077. print("The repository was not found or you do not have access.")
  10078. ```
  10079. In this example:
  10080. - If the user has access, the method completes successfully.
  10081. - If the repository is gated or does not exist, appropriate exceptions are raised, allowing the user
  10082. to handle them accordingly.
  10083. """
  10084. headers = self._build_hf_headers(token=token)
  10085. if repo_type is None:
  10086. repo_type = constants.REPO_TYPE_MODEL
  10087. if repo_type not in constants.REPO_TYPES:
  10088. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  10089. path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/auth-check"
  10090. if write:
  10091. path = f"{path}/write"
  10092. r = get_session().get(path, headers=headers)
  10093. hf_raise_for_status(r)
  10094. def run_job(
  10095. self,
  10096. *,
  10097. image: str,
  10098. command: list[str],
  10099. env: dict[str, Any] | None = None,
  10100. secrets: dict[str, Any] | None = None,
  10101. flavor: SpaceHardware | None = None,
  10102. timeout: int | float | str | None = None,
  10103. labels: dict[str, str] | None = None,
  10104. volumes: list[Volume] | None = None,
  10105. namespace: str | None = None,
  10106. token: bool | str | None = None,
  10107. ) -> JobInfo:
  10108. """
  10109. Run compute Jobs on Hugging Face infrastructure.
  10110. Args:
  10111. image (`str`):
  10112. The Docker image to use.
  10113. Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`.
  10114. Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`.
  10115. command (`list[str]`):
  10116. The command to run. Example: `["echo", "hello"]`.
  10117. env (`dict[str, Any]`, *optional*):
  10118. Defines the environment variables for the Job.
  10119. secrets (`dict[str, Any]`, *optional*):
  10120. Defines the secret environment variables for the Job.
  10121. flavor (`str`, *optional*):
  10122. Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
  10123. Defaults to `"cpu-basic"`.
  10124. timeout (`Union[int, float, str]`, *optional*):
  10125. Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days).
  10126. Example: `300` or `"5m"` for 5 minutes.
  10127. labels (`dict[str, str]`, *optional*):
  10128. Labels to attach to the job (key-value pairs).
  10129. volumes (`list[Volume]`, *optional*):
  10130. Hugging Face Buckets or Repos to mount as volumes in the job container.
  10131. Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`),
  10132. `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`).
  10133. namespace (`str`, *optional*):
  10134. The namespace where the Job will be created. Defaults to the current user's namespace.
  10135. token `(Union[bool, str, None]`, *optional*):
  10136. A valid user access token. If not provided, the locally saved token will be used, which is the
  10137. recommended authentication method. Set to `False` to disable authentication.
  10138. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10139. Example:
  10140. Run your first Job:
  10141. ```python
  10142. >>> from huggingface_hub import run_job
  10143. >>> run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
  10144. ```
  10145. Run a GPU Job:
  10146. ```python
  10147. >>> from huggingface_hub import run_job
  10148. >>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
  10149. >>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
  10150. >>> run_job(image=image, command=command, flavor="a10g-small")
  10151. ```
  10152. Run a Job with volumes:
  10153. ```python
  10154. >>> from huggingface_hub import Volume, run_job
  10155. >>> dataset_volume = Volume(type="dataset", source="HuggingFaceFW/fineweb", mount_path="/data")
  10156. >>> output_bucket_volume = Volume(type="bucket", source="username/my-bucket", mount_path="/output")
  10157. >>> image = "duckdb/duckdb"
  10158. >>> command = ["duckdb", "-c", "COPY (SELECT * FROM '/data/**/*.parquet' LIMIT 5) TO '/output/first-rows.parquet'"]
  10159. >>> run_job(image=image, command=command, volumes=[dataset_volume, output_bucket_volume])
  10160. ```
  10161. """
  10162. if namespace is None:
  10163. namespace = self.whoami(token=token)["name"]
  10164. job_spec = _create_job_spec(
  10165. image=image,
  10166. command=command,
  10167. env=env,
  10168. secrets=secrets,
  10169. flavor=flavor,
  10170. timeout=timeout,
  10171. labels=labels,
  10172. volumes=volumes,
  10173. )
  10174. response = get_session().post(
  10175. f"{self.endpoint}/api/jobs/{namespace}",
  10176. json=job_spec,
  10177. headers=self._build_hf_headers(token=token),
  10178. )
  10179. hf_raise_for_status(response)
  10180. job_info = response.json()
  10181. return JobInfo(**job_info, endpoint=self.endpoint)
  10182. def _fetch_running_job_sse(
  10183. self,
  10184. *,
  10185. job_id: str,
  10186. route: str,
  10187. timeout: int,
  10188. skip_previous_events_on_retry: bool,
  10189. tolerated_status_codes: tuple[int, ...] = (),
  10190. tolerated_exception_types: tuple[type[Exception], ...] = (),
  10191. follow: bool = True,
  10192. namespace: str | None = None,
  10193. token: bool | str | None = None,
  10194. ) -> Iterable[dict[str, Any]]:
  10195. if namespace is None:
  10196. namespace = self.whoami(token=token)["name"]
  10197. def has_job_finished() -> bool:
  10198. # We don't use http_backoff: this is the authoritative check that
  10199. # decides whether to keep streaming.
  10200. job_status_response = get_session().get(
  10201. f"{self.endpoint}/api/jobs/{namespace}/{job_id}",
  10202. headers=self._build_hf_headers(token=token),
  10203. )
  10204. hf_raise_for_status(job_status_response)
  10205. job_status = job_status_response.json()
  10206. return "status" in job_status and job_status["status"]["stage"] not in ("RUNNING", "UPDATING")
  10207. yield from self._stream_sse_events(
  10208. url=f"{self.endpoint}/api/jobs/{namespace}/{job_id}/{route}",
  10209. log_label=f"jobs /{route} for {job_id=}",
  10210. timeout=timeout,
  10211. follow=follow,
  10212. token=token,
  10213. skip_previous_events_on_retry=skip_previous_events_on_retry,
  10214. tolerated_status_codes=tolerated_status_codes,
  10215. tolerated_exception_types=tolerated_exception_types,
  10216. on_iteration_end=has_job_finished,
  10217. )
  10218. def fetch_job_logs(
  10219. self,
  10220. *,
  10221. job_id: str,
  10222. namespace: str | None = None,
  10223. follow: bool = False,
  10224. token: bool | str | None = None,
  10225. ) -> Iterable[str]:
  10226. """
  10227. Fetch all the logs from a compute Job on Hugging Face infrastructure.
  10228. Args:
  10229. job_id (`str`):
  10230. ID of the Job.
  10231. namespace (`str`, *optional*):
  10232. The namespace where the Job is running. Defaults to the current user's namespace.
  10233. follow (`bool`, *optional*):
  10234. If `True`, stream logs in real-time until the job completes (blocking).
  10235. If `False` (default), fetch only the currently available logs and return immediately (non-blocking).
  10236. token `(Union[bool, str, None]`, *optional*):
  10237. A valid user access token. If not provided, the locally saved token will be used, which is the
  10238. recommended authentication method. Set to `False` to disable authentication.
  10239. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10240. Example:
  10241. ```python
  10242. >>> from huggingface_hub import fetch_job_logs, run_job
  10243. >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
  10244. >>> for log in fetch_job_logs(job_id=job.id):
  10245. ... print(log)
  10246. Hello from HF compute!
  10247. >>> # Non-blocking: fetch only currently available logs
  10248. >>> for log in fetch_job_logs(job_id=job.id, follow=False):
  10249. ... print(log)
  10250. ```
  10251. """
  10252. # - We need to retry because sometimes the /logs doesn't return logs when the job just started.
  10253. # (for example it can return only two lines: one for "Job started" and one empty line)
  10254. # - Timeouts can happen in case of build errors
  10255. # - ChunkedEncodingError can happen in case of stopped logging in the middle of streaming
  10256. # - Infinite empty log stream can happen in case of build error
  10257. # (the logs stream is infinite and empty except for the Job started message)
  10258. # - there is a ": keep-alive" every 30 seconds
  10259. seconds_between_keep_alive = 30
  10260. # When not following, use a short timeout: the server replays historical logs
  10261. # quickly, then pauses waiting for new events (~30s keep-alive). 5 seconds is
  10262. # enough to receive all buffered logs.
  10263. timeout = 4 * seconds_between_keep_alive if follow else 5
  10264. for event in self._fetch_running_job_sse(
  10265. job_id=job_id,
  10266. route="logs",
  10267. timeout=timeout,
  10268. skip_previous_events_on_retry=True,
  10269. follow=follow,
  10270. namespace=namespace,
  10271. token=token,
  10272. ):
  10273. # timestamp = event["timestamp"]
  10274. if not event["data"].startswith("===== Job started"):
  10275. log = event["data"]
  10276. yield log
  10277. def fetch_job_metrics(
  10278. self,
  10279. *,
  10280. job_id: str,
  10281. namespace: str | None = None,
  10282. token: bool | str | None = None,
  10283. ) -> Iterable[dict[str, Any]]:
  10284. """
  10285. Fetch all the live metrics from a compute Job on Hugging Face infrastructure.
  10286. Args:
  10287. job_id (`str`):
  10288. ID of the Job.
  10289. namespace (`str`, *optional*):
  10290. The namespace where the Job is running. Defaults to the current user's namespace.
  10291. token `(Union[bool, str, None]`, *optional*):
  10292. A valid user access token. If not provided, the locally saved token will be used, which is the
  10293. recommended authentication method. Set to `False` to disable authentication.
  10294. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10295. Example:
  10296. ```python
  10297. >>> from huggingface_hub import fetch_job_metrics, run_job
  10298. >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], flavor="a10g-small")
  10299. >>> for metrics in fetch_job_metrics(job_id=job.id):
  10300. ... print(metrics)
  10301. {
  10302. "cpu_usage_pct": 0,
  10303. "cpu_millicores": 3500,
  10304. "memory_used_bytes": 1306624,
  10305. "memory_total_bytes": 15032385536,
  10306. "rx_bps": 0,
  10307. "tx_bps": 0,
  10308. "gpus": {
  10309. "882fa930": {
  10310. "utilization": 0,
  10311. "memory_used_bytes": 0,
  10312. "memory_total_bytes": 22836000000
  10313. }
  10314. },
  10315. "replica": "57vr7"
  10316. }
  10317. ```
  10318. """
  10319. # - there is one "metric" event every second, like this:
  10320. # event: metric
  10321. # 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"}
  10322. # - the stream doesn't end when the job finishes, so we rely on timeouts (httpx.NetworkError with Timeout as cause)
  10323. # - httpx.ReadTimeout can happen if the job is marked as running but the hardware is not available yet, that we can ignore
  10324. # - it returns an internal error 500 if the job has already finished, we simply ignore it
  10325. # - ChunkedEncodingError can happen in case of stopped logging in the middle of streaming
  10326. # - there is a ": keep-alive" every 30 seconds
  10327. seconds_between_events = 1
  10328. yield from self._fetch_running_job_sse(
  10329. job_id=job_id,
  10330. route="metrics",
  10331. timeout=10 * seconds_between_events,
  10332. skip_previous_events_on_retry=False,
  10333. tolerated_status_codes=(500,),
  10334. namespace=namespace,
  10335. token=token,
  10336. )
  10337. def list_jobs(
  10338. self,
  10339. *,
  10340. timeout: int | None = None,
  10341. namespace: str | None = None,
  10342. token: bool | str | None = None,
  10343. ) -> list[JobInfo]:
  10344. """
  10345. List compute Jobs on Hugging Face infrastructure.
  10346. Args:
  10347. timeout (`float`, *optional*):
  10348. Whether to set a timeout for the request to the Hub.
  10349. namespace (`str`, *optional*):
  10350. The namespace from where it lists the jobs. Defaults to the current user's namespace.
  10351. token `(Union[bool, str, None]`, *optional*):
  10352. A valid user access token. If not provided, the locally saved token will be used, which is the
  10353. recommended authentication method. Set to `False` to disable authentication.
  10354. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10355. """
  10356. if namespace is None:
  10357. namespace = whoami(token=token)["name"]
  10358. response = get_session().get(
  10359. f"{self.endpoint}/api/jobs/{namespace}",
  10360. headers=self._build_hf_headers(token=token),
  10361. timeout=timeout,
  10362. )
  10363. response.raise_for_status()
  10364. return [JobInfo(**job_info, endpoint=self.endpoint) for job_info in response.json()]
  10365. def list_jobs_hardware(self, token: bool | str | None = None) -> list[JobHardware]:
  10366. """
  10367. List available hardware options for Jobs on Hugging Face infrastructure.
  10368. Returns:
  10369. `list[JobHardware]`: A list of available hardware configurations.
  10370. Example:
  10371. ```python
  10372. >>> from huggingface_hub import HfApi
  10373. >>> api = HfApi()
  10374. >>> hardware_list = api.list_jobs_hardware()
  10375. >>> hardware_list[0]
  10376. 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')
  10377. >>> hardware_list[0].name
  10378. 'cpu-basic'
  10379. # Filter GPU options
  10380. >>> gpu_hardware = [hw for hw in hardware_list if hw.accelerator is not None]
  10381. >>> gpu_hardware[0].accelerator.model
  10382. 'T4'
  10383. ```
  10384. """
  10385. response = get_session().get(f"{self.endpoint}/api/jobs/hardware", headers=self._build_hf_headers(token=token))
  10386. hf_raise_for_status(response)
  10387. return [JobHardware(**hardware) for hardware in response.json()]
  10388. def inspect_job(
  10389. self,
  10390. *,
  10391. job_id: str,
  10392. namespace: str | None = None,
  10393. token: bool | str | None = None,
  10394. ) -> JobInfo:
  10395. """
  10396. Inspect a compute Job on Hugging Face infrastructure.
  10397. Args:
  10398. job_id (`str`):
  10399. ID of the Job.
  10400. namespace (`str`, *optional*):
  10401. The namespace where the Job is running. Defaults to the current user's namespace.
  10402. token `(Union[bool, str, None]`, *optional*):
  10403. A valid user access token. If not provided, the locally saved token will be used, which is the
  10404. recommended authentication method. Set to `False` to disable authentication.
  10405. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10406. Example:
  10407. ```python
  10408. >>> from huggingface_hub import inspect_job, run_job
  10409. >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
  10410. >>> inspect_job(job.id)
  10411. JobInfo(
  10412. id='68780d00bbe36d38803f645f',
  10413. created_at=datetime.datetime(2025, 7, 16, 20, 35, 12, 808000, tzinfo=datetime.timezone.utc),
  10414. docker_image='python:3.12',
  10415. space_id=None,
  10416. command=['python', '-c', "print('Hello from HF compute!')"],
  10417. arguments=[],
  10418. environment={},
  10419. secrets={},
  10420. flavor='cpu-basic',
  10421. status=JobStatus(stage='RUNNING', message=None)
  10422. )
  10423. ```
  10424. """
  10425. if namespace is None:
  10426. namespace = self.whoami(token=token)["name"]
  10427. response = get_session().get(
  10428. f"{self.endpoint}/api/jobs/{namespace}/{job_id}",
  10429. headers=self._build_hf_headers(token=token),
  10430. )
  10431. response.raise_for_status()
  10432. return JobInfo(**response.json(), endpoint=self.endpoint)
  10433. def cancel_job(
  10434. self,
  10435. *,
  10436. job_id: str,
  10437. namespace: str | None = None,
  10438. token: bool | str | None = None,
  10439. ) -> None:
  10440. """
  10441. Cancel a compute Job on Hugging Face infrastructure.
  10442. Args:
  10443. job_id (`str`):
  10444. ID of the Job.
  10445. namespace (`str`, *optional*):
  10446. The namespace where the Job is running. Defaults to the current user's namespace.
  10447. token `(Union[bool, str, None]`, *optional*):
  10448. A valid user access token. If not provided, the locally saved token will be used, which is the
  10449. recommended authentication method. Set to `False` to disable authentication.
  10450. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10451. """
  10452. if namespace is None:
  10453. namespace = self.whoami(token=token)["name"]
  10454. get_session().post(
  10455. f"{self.endpoint}/api/jobs/{namespace}/{job_id}/cancel",
  10456. headers=self._build_hf_headers(token=token),
  10457. ).raise_for_status()
  10458. @experimental
  10459. def run_uv_job(
  10460. self,
  10461. script: str,
  10462. *,
  10463. script_args: list[str] | None = None,
  10464. dependencies: list[str] | None = None,
  10465. python: str | None = None,
  10466. image: str | None = None,
  10467. env: dict[str, Any] | None = None,
  10468. secrets: dict[str, Any] | None = None,
  10469. flavor: SpaceHardware | None = None,
  10470. timeout: int | float | str | None = None,
  10471. labels: dict[str, str] | None = None,
  10472. volumes: list[Volume] | None = None,
  10473. namespace: str | None = None,
  10474. token: bool | str | None = None,
  10475. ) -> JobInfo:
  10476. """
  10477. Run a UV script Job on Hugging Face infrastructure.
  10478. Args:
  10479. script (`str`):
  10480. Path or URL of the UV script, or a command.
  10481. script_args (`list[str]`, *optional*)
  10482. Arguments to pass to the script or command.
  10483. dependencies (`list[str]`, *optional*)
  10484. Dependencies to use to run the UV script.
  10485. python (`str`, *optional*)
  10486. Use a specific Python version. Default is 3.12.
  10487. image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"):
  10488. Use a custom Docker image with `uv` installed.
  10489. env (`dict[str, Any]`, *optional*):
  10490. Defines the environment variables for the Job.
  10491. secrets (`dict[str, Any]`, *optional*):
  10492. Defines the secret environment variables for the Job.
  10493. flavor (`str`, *optional*):
  10494. Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
  10495. Defaults to `"cpu-basic"`.
  10496. timeout (`Union[int, float, str]`, *optional*):
  10497. Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days).
  10498. Example: `300` or `"5m"` for 5 minutes.
  10499. labels (`dict[str, str]`, *optional*):
  10500. Labels to attach to the job (key-value pairs).
  10501. volumes (`list[Volume]`, *optional*):
  10502. Hugging Face Buckets or Repos to mount as volumes in the job container.
  10503. Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`),
  10504. `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`).
  10505. namespace (`str`, *optional*):
  10506. The namespace where the Job will be created. Defaults to the current user's namespace.
  10507. token `(Union[bool, str, None]`, *optional*):
  10508. A valid user access token. If not provided, the locally saved token will be used, which is the
  10509. recommended authentication method. Set to `False` to disable authentication.
  10510. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10511. Example:
  10512. Run a script from a URL:
  10513. ```python
  10514. >>> from huggingface_hub import run_uv_job
  10515. >>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
  10516. >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
  10517. >>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")
  10518. ```
  10519. Run a local script:
  10520. ```python
  10521. >>> from huggingface_hub import run_uv_job
  10522. >>> script = "my_sft.py"
  10523. >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
  10524. >>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")
  10525. ```
  10526. Run a command:
  10527. ```python
  10528. >>> from huggingface_hub import run_uv_job
  10529. >>> script = "lighteval"
  10530. >>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
  10531. >>> run_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small")
  10532. ```
  10533. Mount volumes, e.g. to save model checkpoints during training:
  10534. ```python
  10535. >>> from huggingface_hub import Volume, run_uv_job
  10536. >>> script = "my_sft.py"
  10537. >>> script_args = ["--output_dir", "/training-outputs/training-v3-final", ...]
  10538. >>> checkpoints_bucket = Volume(type="bucket", source="username/my-bucket", mount_path="/training-outputs")
  10539. >>> run_uv_job(script, script_args=script_args, volumes=[checkpoints_bucket])
  10540. ```
  10541. """
  10542. image = image or "ghcr.io/astral-sh/uv:python3.12-bookworm"
  10543. env = env or {}
  10544. secrets = secrets or {}
  10545. # Build command
  10546. command, env, secrets = self._create_uv_command_env_and_secrets(
  10547. script=script,
  10548. script_args=script_args,
  10549. dependencies=dependencies,
  10550. python=python,
  10551. env=env,
  10552. secrets=secrets,
  10553. namespace=namespace,
  10554. token=token,
  10555. )
  10556. # Create RunCommand args
  10557. return self.run_job(
  10558. image=image,
  10559. command=command,
  10560. env=env,
  10561. secrets=secrets,
  10562. flavor=flavor,
  10563. timeout=timeout,
  10564. labels=labels,
  10565. volumes=volumes,
  10566. namespace=namespace,
  10567. token=token,
  10568. )
  10569. def create_scheduled_job(
  10570. self,
  10571. *,
  10572. image: str,
  10573. command: list[str],
  10574. schedule: str,
  10575. suspend: bool | None = None,
  10576. concurrency: bool | None = None,
  10577. env: dict[str, Any] | None = None,
  10578. secrets: dict[str, Any] | None = None,
  10579. flavor: SpaceHardware | None = None,
  10580. timeout: int | float | str | None = None,
  10581. labels: dict[str, str] | None = None,
  10582. volumes: list[Volume] | None = None,
  10583. namespace: str | None = None,
  10584. token: bool | str | None = None,
  10585. ) -> ScheduledJobInfo:
  10586. """
  10587. Create scheduled compute Jobs on Hugging Face infrastructure.
  10588. Args:
  10589. image (`str`):
  10590. The Docker image to use.
  10591. Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`.
  10592. Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`.
  10593. command (`list[str]`):
  10594. The command to run. Example: `["echo", "hello"]`.
  10595. schedule (`str`):
  10596. One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
  10597. CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
  10598. suspend (`bool`, *optional*):
  10599. If True, the scheduled Job is suspended (paused). Defaults to False.
  10600. concurrency (`bool`, *optional*):
  10601. If True, multiple instances of this Job can run concurrently. Defaults to False.
  10602. env (`dict[str, Any]`, *optional*):
  10603. Defines the environment variables for the Job.
  10604. secrets (`dict[str, Any]`, *optional*):
  10605. Defines the secret environment variables for the Job.
  10606. flavor (`str`, *optional*):
  10607. Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
  10608. Defaults to `"cpu-basic"`.
  10609. timeout (`Union[int, float, str]`, *optional*):
  10610. Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days).
  10611. Example: `300` or `"5m"` for 5 minutes.
  10612. labels (`dict[str, str]`, *optional*):
  10613. Labels to attach to the job (key-value pairs).
  10614. volumes (`list[Volume]`, *optional*):
  10615. Hugging Face Buckets or Repos to mount as volumes in the job container.
  10616. Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`),
  10617. `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`).
  10618. namespace (`str`, *optional*):
  10619. The namespace where the Job will be created. Defaults to the current user's namespace.
  10620. token `(Union[bool, str, None]`, *optional*):
  10621. A valid user access token. If not provided, the locally saved token will be used, which is the
  10622. recommended authentication method. Set to `False` to disable authentication.
  10623. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10624. Example:
  10625. Create your first scheduled Job:
  10626. ```python
  10627. >>> from huggingface_hub import create_scheduled_job
  10628. >>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")
  10629. ```
  10630. Use a CRON schedule expression:
  10631. ```python
  10632. >>> from huggingface_hub import create_scheduled_job
  10633. >>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('this runs every 5min')"], schedule="*/5 * * * *")
  10634. ```
  10635. Create a scheduled GPU Job:
  10636. ```python
  10637. >>> from huggingface_hub import create_scheduled_job
  10638. >>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
  10639. >>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
  10640. >>> create_scheduled_job(image, command, flavor="a10g-small", schedule="@hourly")
  10641. ```
  10642. """
  10643. if namespace is None:
  10644. namespace = self.whoami(token=token)["name"]
  10645. # prepare payload to send to HF Jobs API
  10646. job_spec = _create_job_spec(
  10647. image=image,
  10648. command=command,
  10649. env=env,
  10650. secrets=secrets,
  10651. flavor=flavor,
  10652. timeout=timeout,
  10653. labels=labels,
  10654. volumes=volumes,
  10655. )
  10656. input_json: dict[str, Any] = {
  10657. "jobSpec": job_spec,
  10658. "schedule": schedule,
  10659. }
  10660. if concurrency is not None:
  10661. input_json["concurrency"] = concurrency
  10662. if suspend is not None:
  10663. input_json["suspend"] = suspend
  10664. response = get_session().post(
  10665. f"{self.endpoint}/api/scheduled-jobs/{namespace}",
  10666. json=input_json,
  10667. headers=self._build_hf_headers(token=token),
  10668. )
  10669. hf_raise_for_status(response)
  10670. scheduled_job_info = response.json()
  10671. return ScheduledJobInfo(**scheduled_job_info)
  10672. def list_scheduled_jobs(
  10673. self,
  10674. *,
  10675. timeout: int | None = None,
  10676. namespace: str | None = None,
  10677. token: bool | str | None = None,
  10678. ) -> list[ScheduledJobInfo]:
  10679. """
  10680. List scheduled compute Jobs on Hugging Face infrastructure.
  10681. Args:
  10682. timeout (`float`, *optional*):
  10683. Whether to set a timeout for the request to the Hub.
  10684. namespace (`str`, *optional*):
  10685. The namespace from where it lists the jobs. Defaults to the current user's namespace.
  10686. token `(Union[bool, str, None]`, *optional*):
  10687. A valid user access token. If not provided, the locally saved token will be used, which is the
  10688. recommended authentication method. Set to `False` to disable authentication.
  10689. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10690. """
  10691. if namespace is None:
  10692. namespace = self.whoami(token=token)["name"]
  10693. response = get_session().get(
  10694. f"{self.endpoint}/api/scheduled-jobs/{namespace}",
  10695. headers=self._build_hf_headers(token=token),
  10696. timeout=timeout,
  10697. )
  10698. hf_raise_for_status(response)
  10699. return [ScheduledJobInfo(**scheduled_job_info) for scheduled_job_info in response.json()]
  10700. def inspect_scheduled_job(
  10701. self,
  10702. *,
  10703. scheduled_job_id: str,
  10704. namespace: str | None = None,
  10705. token: bool | str | None = None,
  10706. ) -> ScheduledJobInfo:
  10707. """
  10708. Inspect a scheduled compute Job on Hugging Face infrastructure.
  10709. Args:
  10710. scheduled_job_id (`str`):
  10711. ID of the scheduled Job.
  10712. namespace (`str`, *optional*):
  10713. The namespace where the scheduled Job is. Defaults to the current user's namespace.
  10714. token `(Union[bool, str, None]`, *optional*):
  10715. A valid user access token. If not provided, the locally saved token will be used, which is the
  10716. recommended authentication method. Set to `False` to disable authentication.
  10717. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10718. Example:
  10719. ```python
  10720. >>> from huggingface_hub import inspect_job, create_scheduled_job
  10721. >>> scheduled_job = create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")
  10722. >>> inspect_scheduled_job(scheduled_job.id)
  10723. ```
  10724. """
  10725. if namespace is None:
  10726. namespace = self.whoami(token=token)["name"]
  10727. response = get_session().get(
  10728. f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}",
  10729. headers=self._build_hf_headers(token=token),
  10730. )
  10731. hf_raise_for_status(response)
  10732. return ScheduledJobInfo(**response.json())
  10733. def delete_scheduled_job(
  10734. self,
  10735. *,
  10736. scheduled_job_id: str,
  10737. namespace: str | None = None,
  10738. token: bool | str | None = None,
  10739. ) -> None:
  10740. """
  10741. Delete a scheduled compute Job on Hugging Face infrastructure.
  10742. Args:
  10743. scheduled_job_id (`str`):
  10744. ID of the scheduled Job.
  10745. namespace (`str`, *optional*):
  10746. The namespace where the scheduled Job is. Defaults to the current user's namespace.
  10747. token `(Union[bool, str, None]`, *optional*):
  10748. A valid user access token. If not provided, the locally saved token will be used, which is the
  10749. recommended authentication method. Set to `False` to disable authentication.
  10750. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10751. """
  10752. if namespace is None:
  10753. namespace = self.whoami(token=token)["name"]
  10754. response = get_session().delete(
  10755. f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}",
  10756. headers=self._build_hf_headers(token=token),
  10757. )
  10758. hf_raise_for_status(response)
  10759. def suspend_scheduled_job(
  10760. self,
  10761. *,
  10762. scheduled_job_id: str,
  10763. namespace: str | None = None,
  10764. token: bool | str | None = None,
  10765. ) -> None:
  10766. """
  10767. Suspend (pause) a scheduled compute Job on Hugging Face infrastructure.
  10768. Args:
  10769. scheduled_job_id (`str`):
  10770. ID of the scheduled Job.
  10771. namespace (`str`, *optional*):
  10772. The namespace where the scheduled Job is. Defaults to the current user's namespace.
  10773. token `(Union[bool, str, None]`, *optional*):
  10774. A valid user access token. If not provided, the locally saved token will be used, which is the
  10775. recommended authentication method. Set to `False` to disable authentication.
  10776. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10777. """
  10778. if namespace is None:
  10779. namespace = self.whoami(token=token)["name"]
  10780. get_session().post(
  10781. f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}/suspend",
  10782. headers=self._build_hf_headers(token=token),
  10783. ).raise_for_status()
  10784. def resume_scheduled_job(
  10785. self,
  10786. *,
  10787. scheduled_job_id: str,
  10788. namespace: str | None = None,
  10789. token: bool | str | None = None,
  10790. ) -> None:
  10791. """
  10792. Resume (unpause) a scheduled compute Job on Hugging Face infrastructure.
  10793. Args:
  10794. scheduled_job_id (`str`):
  10795. ID of the scheduled Job.
  10796. namespace (`str`, *optional*):
  10797. The namespace where the scheduled Job is. Defaults to the current user's namespace.
  10798. token `(Union[bool, str, None]`, *optional*):
  10799. A valid user access token. If not provided, the locally saved token will be used, which is the
  10800. recommended authentication method. Set to `False` to disable authentication.
  10801. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10802. """
  10803. if namespace is None:
  10804. namespace = self.whoami(token=token)["name"]
  10805. get_session().post(
  10806. f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}/resume",
  10807. headers=self._build_hf_headers(token=token),
  10808. ).raise_for_status()
  10809. @experimental
  10810. def create_scheduled_uv_job(
  10811. self,
  10812. script: str,
  10813. *,
  10814. script_args: list[str] | None = None,
  10815. schedule: str,
  10816. suspend: bool | None = None,
  10817. concurrency: bool | None = None,
  10818. dependencies: list[str] | None = None,
  10819. python: str | None = None,
  10820. image: str | None = None,
  10821. env: dict[str, Any] | None = None,
  10822. secrets: dict[str, Any] | None = None,
  10823. flavor: SpaceHardware | None = None,
  10824. timeout: int | float | str | None = None,
  10825. labels: dict[str, str] | None = None,
  10826. volumes: list[Volume] | None = None,
  10827. namespace: str | None = None,
  10828. token: bool | str | None = None,
  10829. ) -> ScheduledJobInfo:
  10830. """
  10831. Run a UV script Job on Hugging Face infrastructure.
  10832. Args:
  10833. script (`str`):
  10834. Path or URL of the UV script, or a command.
  10835. script_args (`list[str]`, *optional*)
  10836. Arguments to pass to the script, or a command.
  10837. schedule (`str`):
  10838. One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
  10839. CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
  10840. suspend (`bool`, *optional*):
  10841. If True, the scheduled Job is suspended (paused). Defaults to False.
  10842. concurrency (`bool`, *optional*):
  10843. If True, multiple instances of this Job can run concurrently. Defaults to False.
  10844. dependencies (`list[str]`, *optional*)
  10845. Dependencies to use to run the UV script.
  10846. python (`str`, *optional*)
  10847. Use a specific Python version. Default is 3.12.
  10848. image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"):
  10849. Use a custom Docker image with `uv` installed.
  10850. env (`dict[str, Any]`, *optional*):
  10851. Defines the environment variables for the Job.
  10852. secrets (`dict[str, Any]`, *optional*):
  10853. Defines the secret environment variables for the Job.
  10854. flavor (`str`, *optional*):
  10855. Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
  10856. Defaults to `"cpu-basic"`.
  10857. timeout (`Union[int, float, str]`, *optional*):
  10858. Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days).
  10859. Example: `300` or `"5m"` for 5 minutes.
  10860. labels (`dict[str, str]`, *optional*):
  10861. Labels to attach to the job (key-value pairs).
  10862. volumes (`list[Volume]`, *optional*):
  10863. Hugging Face Buckets or Repos to mount as volumes in the job container.
  10864. Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`),
  10865. `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`).
  10866. namespace (`str`, *optional*):
  10867. The namespace where the Job will be created. Defaults to the current user's namespace.
  10868. token `(Union[bool, str, None]`, *optional*):
  10869. A valid user access token. If not provided, the locally saved token will be used, which is the
  10870. recommended authentication method. Set to `False` to disable authentication.
  10871. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  10872. Example:
  10873. Schedule a script from a URL:
  10874. ```python
  10875. >>> from huggingface_hub import create_scheduled_uv_job
  10876. >>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
  10877. >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
  10878. >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")
  10879. ```
  10880. Schedule a local script:
  10881. ```python
  10882. >>> from huggingface_hub import create_scheduled_uv_job
  10883. >>> script = "my_sft.py"
  10884. >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
  10885. >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")
  10886. ```
  10887. Schedule a command:
  10888. ```python
  10889. >>> from huggingface_hub import create_scheduled_uv_job
  10890. >>> script = "lighteval"
  10891. >>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
  10892. >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small", schedule="@weekly")
  10893. ```
  10894. """
  10895. image = image or "ghcr.io/astral-sh/uv:python3.12-bookworm"
  10896. # Build command
  10897. command, env, secrets = self._create_uv_command_env_and_secrets(
  10898. script=script,
  10899. script_args=script_args,
  10900. dependencies=dependencies,
  10901. python=python,
  10902. env=env,
  10903. secrets=secrets,
  10904. namespace=namespace,
  10905. token=token,
  10906. )
  10907. # Create RunCommand args
  10908. return self.create_scheduled_job(
  10909. image=image,
  10910. command=command,
  10911. schedule=schedule,
  10912. suspend=suspend,
  10913. concurrency=concurrency,
  10914. env=env,
  10915. secrets=secrets,
  10916. flavor=flavor,
  10917. timeout=timeout,
  10918. labels=labels,
  10919. volumes=volumes,
  10920. namespace=namespace,
  10921. token=token,
  10922. )
  10923. def _create_uv_command_env_and_secrets(
  10924. self,
  10925. *,
  10926. script: str,
  10927. script_args: list[str] | None,
  10928. dependencies: list[str] | None,
  10929. python: str | None,
  10930. env: dict[str, Any] | None,
  10931. secrets: dict[str, Any] | None,
  10932. namespace: str | None,
  10933. token: bool | str | None,
  10934. ) -> tuple[list[str], dict[str, Any], dict[str, Any]]:
  10935. env = env or {}
  10936. secrets = secrets or {}
  10937. # Build command
  10938. uv_args = []
  10939. if dependencies:
  10940. for dependency in dependencies:
  10941. uv_args += ["--with", dependency]
  10942. if python:
  10943. uv_args += ["--python", python]
  10944. script_args = script_args or []
  10945. if namespace is None:
  10946. namespace = self.whoami(token=token)["name"]
  10947. # Find the local files to pass to the job
  10948. local_files_to_include = {candidate for candidate in [script] + script_args if Path(candidate).is_file()}
  10949. # Fail early for missing scripts or config files
  10950. missing_local_files = {
  10951. candidate
  10952. for candidate in [script] + script_args
  10953. if not Path(candidate).is_file()
  10954. and Path(candidate).suffix in [".py", ".sh", ".yaml", ".yml", ".toml"]
  10955. and not candidate.startswith("https://")
  10956. and not candidate.startswith("http://")
  10957. }
  10958. if missing_local_files:
  10959. raise FileNotFoundError(", ".join(missing_local_files))
  10960. if len(local_files_to_include) == 0:
  10961. # Direct URL execution or command - no upload needed
  10962. command = ["uv", "run"] + uv_args + [script] + script_args
  10963. else:
  10964. # Find appropriate remote file names
  10965. remote_to_local_file_names: dict[str, str] = {}
  10966. for local_file_to_include in local_files_to_include:
  10967. local_file_path = Path(local_file_to_include)
  10968. # remove spaces for proper xargs parsing
  10969. remote_file_path = Path(local_file_path.name.replace(" ", "_"))
  10970. if remote_file_path.name in remote_to_local_file_names:
  10971. for i in itertools.count():
  10972. remote_file_name = remote_file_path.with_stem(remote_file_path.stem + f"({i})").name
  10973. if remote_file_name not in remote_to_local_file_names:
  10974. remote_to_local_file_names[remote_file_name] = local_file_to_include
  10975. break
  10976. else:
  10977. remote_to_local_file_names[remote_file_path.name] = local_file_to_include
  10978. local_to_remote_file_names = {
  10979. local_file_to_include: remote_file_name
  10980. for remote_file_name, local_file_to_include in remote_to_local_file_names.items()
  10981. }
  10982. # Replace local paths with remote paths in command
  10983. if script in local_to_remote_file_names:
  10984. script = local_to_remote_file_names[script]
  10985. script_args = [
  10986. local_to_remote_file_names[arg] if arg in local_to_remote_file_names else arg for arg in script_args
  10987. ]
  10988. # Load content to pass as environment variable with format
  10989. # file1 base64content1
  10990. # file2 base64content2
  10991. # ...
  10992. env["LOCAL_FILES_ENCODED"] = "\n".join(
  10993. remote_file_name + " " + base64.b64encode(Path(local_file_to_include).read_bytes()).decode()
  10994. for remote_file_name, local_file_to_include in remote_to_local_file_names.items()
  10995. )
  10996. # Shell-quote each arg to prevent metacharacters (e.g. '>') from being interpreted by bash
  10997. quoted_parts = ["'" + arg.replace("'", r"'\''") + "'" for arg in [*uv_args, script, *script_args]]
  10998. command = [
  10999. "bash",
  11000. "-c",
  11001. """echo $LOCAL_FILES_ENCODED | xargs -n 2 bash -c 'echo "$1" | base64 -d > "$0"' && """
  11002. + f"uv run {' '.join(quoted_parts)}",
  11003. ]
  11004. return command, env, secrets
  11005. @validate_hf_hub_args
  11006. def create_bucket(
  11007. self,
  11008. bucket_id: str,
  11009. *,
  11010. private: bool | None = None,
  11011. resource_group_id: str | None = None,
  11012. exist_ok: bool = False,
  11013. token: bool | str | None = None,
  11014. ) -> BucketUrl:
  11015. """Create a bucket on the Hub.
  11016. Args:
  11017. bucket_id (`str`):
  11018. A namespace (user or an organization) and a bucket name separated by a `/`.
  11019. If no namespace is provided, the bucket will be created in the current user's namespace.
  11020. private (`bool`, *optional*):
  11021. Whether to make the bucket private. If `None` (default), the bucket will be public unless the
  11022. organization's default is private.
  11023. resource_group_id (`str`, *optional*):
  11024. Resource group in which to create the bucket. Resource groups are only available for Enterprise Hub
  11025. organizations and allow to define which members of the organization can access the resource. The ID
  11026. of a resource group can be found in the URL of the resource's page on the Hub
  11027. (e.g. `"66670e5163145ca562cb1988"`). To learn more about resource groups, see
  11028. https://huggingface.co/docs/hub/en/security-resource-groups.
  11029. exist_ok (`bool`, *optional*, defaults to `False`):
  11030. If `True`, do not raise an error if the bucket already exists.
  11031. token (`bool` or `str`, *optional*):
  11032. A valid user access token (string). Defaults to the locally saved
  11033. token, which is the recommended method for authentication (see
  11034. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  11035. To disable authentication, pass `False`.
  11036. Returns:
  11037. [`BucketUrl`]: URL to the newly created bucket containing
  11038. attributes like `endpoint`, `namespace`, and `bucket_id`.
  11039. Example:
  11040. ```python
  11041. >>> from huggingface_hub import create_bucket
  11042. >>> url = create_bucket(bucket_id="my-bucket")
  11043. >>> url.bucket_id
  11044. 'user/my-bucket'
  11045. >>> url.url
  11046. 'https://huggingface.co/buckets/user/my-bucket'
  11047. >>> url.handle
  11048. 'hf://buckets/user/my-bucket'
  11049. >>> create_bucket(bucket_id="my-bucket", private=True, exist_ok=True)
  11050. BucketUrl(...)
  11051. ```
  11052. """
  11053. payload: dict[str, Any] = {}
  11054. if private is not None:
  11055. payload["private"] = private
  11056. if resource_group_id is not None:
  11057. payload["resourceGroupId"] = resource_group_id
  11058. if "/" not in bucket_id:
  11059. namespace, name = "me", bucket_id # "me" namespace refers to the current user
  11060. else:
  11061. bucket_id_parsed, prefix = _split_bucket_id_and_prefix(bucket_id)
  11062. if prefix:
  11063. raise ValueError(f"Invalid bucket ID: {bucket_id}")
  11064. namespace, name = bucket_id_parsed.split("/")
  11065. response = get_session().post(
  11066. f"{self.endpoint}/api/buckets/{namespace}/{name}",
  11067. headers=self._build_hf_headers(token=token),
  11068. json=payload,
  11069. )
  11070. try:
  11071. hf_raise_for_status(response)
  11072. except HfHubHTTPError as err:
  11073. if exist_ok and err.response.status_code == 409:
  11074. # Repo already exists and `exist_ok=True`
  11075. pass
  11076. elif exist_ok and err.response.status_code == 403:
  11077. # No write permission on the namespace but repo might already exist
  11078. try:
  11079. self.bucket_info(bucket_id=bucket_id, token=token)
  11080. return BucketUrl(f"{self.endpoint}/buckets/{bucket_id}", endpoint=self.endpoint)
  11081. except HfHubHTTPError:
  11082. raise err
  11083. else:
  11084. raise
  11085. return BucketUrl(response.json()["url"], endpoint=self.endpoint)
  11086. @validate_hf_hub_args
  11087. def bucket_info(
  11088. self,
  11089. bucket_id: str,
  11090. *,
  11091. token: bool | str | None = None,
  11092. ) -> BucketInfo:
  11093. """Get information about a specific bucket on the Hub.
  11094. Args:
  11095. bucket_id (`str`):
  11096. The ID of the bucket (e.g. `"username/my-bucket"`).
  11097. token (`bool` or `str`, *optional*):
  11098. A valid user access token (string). Defaults to the locally saved
  11099. token, which is the recommended method for authentication (see
  11100. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  11101. To disable authentication, pass `False`.
  11102. Returns:
  11103. [`BucketInfo`]: The bucket information.
  11104. Raises:
  11105. [`~errors.BucketNotFoundError`]: If the bucket cannot be found. This may be because it doesn't exist,
  11106. or because it is set to `private` and you do not have access.
  11107. Example:
  11108. ```python
  11109. >>> from huggingface_hub import bucket_info
  11110. >>> info = bucket_info(bucket_id="Wauplin/first-bucket")
  11111. >>> info.id
  11112. 'Wauplin/first-bucket'
  11113. >>> info.private
  11114. False
  11115. >>> info.created_at
  11116. datetime.datetime(2026, 2, 6, 17, 37, 57, tzinfo=datetime.timezone.utc)
  11117. >>> info.size
  11118. 551879671
  11119. >>> info.total_files
  11120. 12
  11121. ```
  11122. """
  11123. response = get_session().get(
  11124. f"{self.endpoint}/api/buckets/{bucket_id}",
  11125. headers=self._build_hf_headers(token=token),
  11126. )
  11127. hf_raise_for_status(response)
  11128. return BucketInfo(**response.json())
  11129. @validate_hf_hub_args
  11130. def list_buckets(
  11131. self,
  11132. namespace: str | None = None,
  11133. *,
  11134. token: bool | str | None = None,
  11135. ) -> Iterable[BucketInfo]:
  11136. """List buckets on the Hub under a certain namespace.
  11137. Args:
  11138. namespace (`str`, *optional*):
  11139. List buckets under this namespace (user or organization). Defaults to listing user's buckets.
  11140. token (`bool` or `str`, *optional*):
  11141. A valid user access token (string). Defaults to the locally saved
  11142. token, which is the recommended method for authentication (see
  11143. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  11144. To disable authentication, pass `False`.
  11145. Returns:
  11146. `Iterable[BucketInfo]`: An iterable of [`BucketInfo`] objects.
  11147. Example:
  11148. ```python
  11149. >>> from huggingface_hub import list_buckets
  11150. >>> for bucket in list_buckets(): # lists buckets in the user's namespace
  11151. ... print(bucket)
  11152. >>> for bucket in list_buckets(namespace="huggingface"): # lists buckets in the "huggingface" organization
  11153. ... print(bucket)
  11154. ```
  11155. """
  11156. if namespace is None:
  11157. namespace = "me"
  11158. for item in paginate(
  11159. f"{self.endpoint}/api/buckets/{namespace}", params={}, headers=self._build_hf_headers(token=token)
  11160. ):
  11161. yield BucketInfo(**item)
  11162. @validate_hf_hub_args
  11163. def delete_bucket(
  11164. self,
  11165. bucket_id: str,
  11166. *,
  11167. missing_ok: bool = False,
  11168. token: bool | str | None = None,
  11169. ) -> None:
  11170. """Delete a bucket from the Hub.
  11171. Args:
  11172. bucket_id (`str`):
  11173. The ID of the bucket (e.g. `"username/my-bucket"`).
  11174. missing_ok (`bool`, *optional*, defaults to `False`):
  11175. If `True`, do not raise an error if the bucket does not exist.
  11176. token (`bool` or `str`, *optional*):
  11177. A valid user access token (string). Defaults to the locally saved
  11178. token, which is the recommended method for authentication (see
  11179. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  11180. To disable authentication, pass `False`.
  11181. Raises:
  11182. [`~errors.BucketNotFoundError`]: If the bucket cannot be found and `missing_ok` is set to `False` (default).
  11183. Example:
  11184. ```python
  11185. >>> from huggingface_hub import delete_bucket
  11186. >>> delete_bucket(bucket_id="Wauplin/first-bucket")
  11187. >>> delete_bucket(bucket_id="Wauplin/first-bucket", missing_ok=True)
  11188. ```
  11189. """
  11190. response = get_session().delete(
  11191. f"{self.endpoint}/api/buckets/{bucket_id}",
  11192. headers=self._build_hf_headers(token=token),
  11193. )
  11194. reset_xet_connection_info_cache_for_repo("bucket", bucket_id)
  11195. try:
  11196. hf_raise_for_status(response)
  11197. except HfHubHTTPError as e:
  11198. if e.response.status_code != 404 or not missing_ok:
  11199. raise
  11200. @validate_hf_hub_args
  11201. def move_bucket(
  11202. self,
  11203. from_id: str,
  11204. to_id: str,
  11205. *,
  11206. token: bool | str | None = None,
  11207. ) -> None:
  11208. """Move a bucket from "namespace1/repo_name1" to "namespace2/repo_name2"
  11209. Note there are certain limitations. For more information about moving
  11210. repositories, please see
  11211. https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.
  11212. Args:
  11213. from_id (`str`):
  11214. A namespace (user or an organization) and a bucket name separated
  11215. by a `/`. Original bucket identifier (e.g. `"username/my-bucket"`).
  11216. to_id (`str`):
  11217. A namespace (user or an organization) and a bucket name separated
  11218. by a `/`. Final bucket identifier (e.g. `"username/new-bucket-name"`
  11219. or `"organization/my-bucket"`).
  11220. token (`bool` or `str`, *optional*):
  11221. A valid user access token (string). Defaults to the locally saved
  11222. token, which is the recommended method for authentication (see
  11223. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  11224. To disable authentication, pass `False`.
  11225. Raises:
  11226. [`~errors.BucketNotFoundError`]:
  11227. If the source bucket cannot be found. This may be because it doesn't exist,
  11228. or because it is set to `private` and you do not have access.
  11229. Example:
  11230. ```python
  11231. >>> from huggingface_hub import move_bucket
  11232. >>> # Rename a bucket within the same namespace
  11233. >>> move_bucket(from_id="username/old-name", to_id="username/new-name")
  11234. >>> # Transfer a bucket to an organization
  11235. >>> move_bucket(from_id="username/my-bucket", to_id="my-org/my-bucket")
  11236. ```
  11237. """
  11238. if len(from_id.split("/")) != 2:
  11239. raise ValueError(f"Invalid repo_id: {from_id}. It should have a namespace (:namespace:/:repo_name:)")
  11240. if len(to_id.split("/")) != 2:
  11241. raise ValueError(f"Invalid repo_id: {to_id}. It should have a namespace (:namespace:/:repo_name:)")
  11242. json_payload = {"fromRepo": from_id, "toRepo": to_id, "type": "bucket"}
  11243. path = f"{self.endpoint}/api/repos/move"
  11244. headers = self._build_hf_headers(token=token)
  11245. response = get_session().post(path, headers=headers, json=json_payload)
  11246. hf_raise_for_status(response)
  11247. @validate_hf_hub_args
  11248. def list_bucket_tree(
  11249. self,
  11250. bucket_id: str,
  11251. prefix: str | None = None,
  11252. *,
  11253. recursive: bool | None = None,
  11254. token: str | bool | None = None,
  11255. ) -> Iterable[BucketFile | BucketFolder]:
  11256. """List files in a bucket.
  11257. Args:
  11258. bucket_id (`str`):
  11259. The ID of the bucket (e.g. `"username/my-bucket"`).
  11260. prefix (`str`, *optional*):
  11261. Filter results to files whose path starts with this prefix.
  11262. recursive (`bool`, *optional*):
  11263. If `True`, list files recursively. If `False` (default), list files and directories only at root.
  11264. token (`bool` or `str`, *optional*):
  11265. A valid user access token (string). Defaults to the locally saved
  11266. token, which is the recommended method for authentication (see
  11267. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  11268. To disable authentication, pass `False`.
  11269. Returns:
  11270. `Iterable[Union[BucketFile, BucketFolder]]`: An iterable of [`BucketFile`] and [`BucketFolder`] objects
  11271. containing file and directory information (path, etc.).
  11272. Example:
  11273. ```python
  11274. >>> from huggingface_hub import list_bucket_tree
  11275. >>> for file_info in list_bucket_tree(bucket_id="username/my-bucket"):
  11276. ... print(file_info.path)
  11277. >>> # Filter by prefix
  11278. >>> for file_info in list_bucket_tree(bucket_id="username/my-bucket", prefix="models/"):
  11279. ... print(file_info.path)
  11280. ```
  11281. """
  11282. encoded_prefix = "/" + quote(prefix, safe="") if prefix else ""
  11283. params = {}
  11284. if recursive is not None:
  11285. params["recursive"] = recursive
  11286. for item in paginate(
  11287. path=f"{self.endpoint}/api/buckets/{bucket_id}/tree{encoded_prefix}",
  11288. headers=self._build_hf_headers(token=token),
  11289. params=params,
  11290. ):
  11291. if item["type"] == "file":
  11292. yield BucketFile(**item)
  11293. elif item["type"] == "directory":
  11294. yield BucketFolder(**item)
  11295. @validate_hf_hub_args
  11296. def get_bucket_paths_info(
  11297. self,
  11298. bucket_id: str,
  11299. paths: Iterable[str],
  11300. *,
  11301. token: str | bool | None = None,
  11302. ) -> Iterable[BucketFile]:
  11303. """
  11304. Get information about a bucket's paths.
  11305. Calls are made in batches of 1000 paths. Results are yielded as they are received.
  11306. Args:
  11307. bucket_id (`str`):
  11308. The ID of the bucket (e.g. `"username/my-bucket"`).
  11309. paths (`Iterable[str]`):
  11310. The paths to get information about. If a path does not exist, it is ignored without raising an exception.
  11311. Only file paths are supported.
  11312. token (`bool` or `str`, *optional*):
  11313. A valid user access token (string). Defaults to the locally saved
  11314. token, which is the recommended method for authentication (see
  11315. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  11316. To disable authentication, pass `False`.
  11317. Returns:
  11318. `Iterable[BucketFile]`:
  11319. The information about the paths, as an iterable of [`BucketFile`] objects.
  11320. Example:
  11321. ```py
  11322. >>> from huggingface_hub import get_bucket_paths_info
  11323. >>> paths_info = get_bucket_paths_info("username/my-bucket", ["file.txt", "checkpoints/model.safetensors"])
  11324. >>> for info in paths_info:
  11325. ... print(info)
  11326. BucketFile(type='file', path='file.txt', size=2379, xet_hash='96e637d9665bd35477b1908a23f2e254edfba0618dbd2d62f90a6baee7d139cf', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc))
  11327. BucketFile(type='file', path='checkpoints/model.safetensors', size=2408828, xet_hash='3ed0e9fefe788ddd61d1e26eba67057e9740a064b009256fbafadf6bb95785ca', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc))
  11328. ```
  11329. """
  11330. headers = self._build_hf_headers(token=token)
  11331. for batch in chunk_iterable(paths, chunk_size=_BUCKET_PATHS_INFO_BATCH_SIZE):
  11332. response = http_backoff(
  11333. "POST",
  11334. f"{self.endpoint}/api/buckets/{bucket_id}/paths-info",
  11335. json={"paths": list(batch)},
  11336. headers=headers,
  11337. )
  11338. hf_raise_for_status(response)
  11339. for path_info in response.json():
  11340. yield BucketFile(**path_info)
  11341. @validate_hf_hub_args
  11342. def copy_files(self, source: str, destination: str, *, token: str | bool | None = None) -> None:
  11343. """Copy files between locations on the Hub.
  11344. Copy files from a bucket or repository (model, dataset, space) to a bucket. Both individual files and
  11345. entire folders are supported.
  11346. Currently, only bucket destinations are supported. Copying to a repository is not supported.
  11347. When copying from a repository, `.gitattributes` files are automatically excluded since they are
  11348. git-specific metadata and not relevant in a bucket context.
  11349. Args:
  11350. source (`str`):
  11351. Source location as an `hf://` handle. Can be a bucket path (e.g. `"hf://buckets/my-bucket/path/to/file"`)
  11352. or a repo path (e.g. `"hf://username/my-model/weights.bin"`, `"hf://datasets/username/my-dataset/data/"`).
  11353. destination (`str`):
  11354. Destination location as an `hf://` handle pointing to a bucket
  11355. (e.g. `"hf://buckets/my-bucket/target/path"`).
  11356. token (`bool` or `str`, *optional*):
  11357. A valid user access token (string). Defaults to the locally saved
  11358. token, which is the recommended method for authentication (see
  11359. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  11360. To disable authentication, pass `False`.
  11361. Raises:
  11362. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
  11363. If the destination is not a bucket or if the source/destination handles are invalid.
  11364. Example:
  11365. ```python
  11366. >>> from huggingface_hub import copy_files
  11367. # Copy a single file between buckets
  11368. >>> copy_files("hf://buckets/my-bucket/data.bin", "hf://buckets/other-bucket/data.bin")
  11369. # Copy a folder from a bucket to another bucket
  11370. >>> copy_files("hf://buckets/my-bucket/models/", "hf://buckets/other-bucket/backup/")
  11371. # Copy a file from a model repo to a bucket
  11372. >>> copy_files("hf://username/my-model/model.safetensors", "hf://buckets/my-bucket/")
  11373. # Copy an entire dataset to a bucket
  11374. >>> copy_files("hf://datasets/username/my-dataset/", "hf://buckets/my-bucket/datasets/")
  11375. ```
  11376. """
  11377. source_handle = _parse_hf_copy_handle(source)
  11378. destination_handle = _parse_hf_copy_handle(destination)
  11379. if isinstance(destination_handle, _RepoCopyHandle):
  11380. raise ValueError("Bucket-to-repo and repo-to-repo copy are not supported. Destination must be a bucket.")
  11381. destination_bucket_id = destination_handle.bucket_id
  11382. destination_path = destination_handle.path
  11383. destination_is_directory = False
  11384. destination_exists_as_directory = False
  11385. if destination_path == "":
  11386. # Bucket root always exists as a directory
  11387. destination_is_directory = True
  11388. destination_exists_as_directory = True
  11389. else:
  11390. # Check if destination matches an existing file
  11391. dest_path_info = list(self.get_bucket_paths_info(destination_bucket_id, [destination_path], token=token))
  11392. if dest_path_info:
  11393. destination_is_directory = False
  11394. else:
  11395. # Check if destination is an existing "directory" (prefix with children)
  11396. destination_exists_as_directory = any(
  11397. self.list_bucket_tree(destination_bucket_id, prefix=destination_path, recursive=False, token=token)
  11398. )
  11399. # Treat as directory if it exists as one, or if the user signaled with trailing slash
  11400. destination_is_directory = destination_exists_as_directory or destination.endswith("/")
  11401. all_adds: list[tuple[str, str]] = []
  11402. all_copies: list[_BucketCopyFile] = []
  11403. pending_downloads: list[tuple[str, str]] = [] # (file_path, target_path) for non-xet files to download
  11404. def _resolve_target_path(src_file_path: str, src_root_path: str | None, is_single_file: bool) -> str:
  11405. basename = src_file_path.rsplit("/", 1)[-1]
  11406. if is_single_file:
  11407. if destination_path == "":
  11408. return basename
  11409. if destination_is_directory:
  11410. return f"{destination_path.rstrip('/')}/{basename}"
  11411. return destination_path
  11412. if src_root_path is None:
  11413. rel_path = src_file_path
  11414. elif src_file_path.startswith(src_root_path + "/"):
  11415. rel_path = src_file_path[len(src_root_path) + 1 :]
  11416. elif src_file_path == src_root_path:
  11417. rel_path = src_file_path.rsplit("/", 1)[-1]
  11418. else:
  11419. raise ValueError(f"Unexpected source path while copying folder: '{src_file_path}'.")
  11420. if rel_path == "":
  11421. raise ValueError("Cannot copy an empty relative path.")
  11422. # Match Unix `cp -r` behavior: when the destination already exists as a
  11423. # directory, nest the source folder inside it (e.g. cp -r src dst → dst/src/...).
  11424. # When the destination does not exist, use rename semantics (cp -r src new → new/...).
  11425. if destination_exists_as_directory and src_root_path is not None:
  11426. src_dir_basename = src_root_path.rsplit("/", 1)[-1]
  11427. rel_path = f"{src_dir_basename}/{rel_path}"
  11428. if destination_path == "":
  11429. return rel_path
  11430. return f"{destination_path.rstrip('/')}/{rel_path}"
  11431. def _build_copy_op(
  11432. target_path: str, xet_hash: str, size: int, source_repo_type: str, source_repo_id: str
  11433. ) -> _BucketCopyFile:
  11434. """Server-side copy by xet hash — no data transfer needed."""
  11435. return _BucketCopyFile(
  11436. destination=target_path,
  11437. xet_hash=xet_hash,
  11438. source_repo_type=source_repo_type,
  11439. source_repo_id=source_repo_id,
  11440. size=size,
  11441. )
  11442. def _add_repo_file(file: RepoFile, target_path: str) -> None:
  11443. """Queue a repo file: copy-by-hash if xet-backed, otherwise download first."""
  11444. if file.xet_hash is not None:
  11445. all_copies.append(
  11446. _build_copy_op(
  11447. target_path,
  11448. file.xet_hash,
  11449. file.size,
  11450. source_handle.repo_type, # type: ignore
  11451. source_handle.repo_id, # type: ignore
  11452. )
  11453. )
  11454. else:
  11455. pending_downloads.append((file.path, target_path))
  11456. # === Source is a bucket: always hash-based copy (no download needed) ===
  11457. if isinstance(source_handle, _BucketCopyHandle):
  11458. source_path = source_handle.path
  11459. source_path_info = list(self.get_bucket_paths_info(source_handle.bucket_id, [source_path], token=token))
  11460. if source_path_info:
  11461. # Source path matched a single file
  11462. source_file = source_path_info[0]
  11463. target_path = _resolve_target_path(source_file.path, None, is_single_file=True)
  11464. all_copies.append(
  11465. _build_copy_op(
  11466. target_path, source_file.xet_hash, source_file.size, "bucket", source_handle.bucket_id
  11467. )
  11468. )
  11469. else:
  11470. # Source path is a folder (or prefix) — list and copy all matching files
  11471. for item in self.list_bucket_tree(
  11472. source_handle.bucket_id, prefix=source_path or None, recursive=True, token=token
  11473. ):
  11474. if not isinstance(item, BucketFile):
  11475. continue
  11476. if source_path and not (item.path == source_path or item.path.startswith(source_path + "/")):
  11477. continue
  11478. target_path = _resolve_target_path(item.path, source_path or None, is_single_file=False)
  11479. all_copies.append(
  11480. _build_copy_op(target_path, item.xet_hash, item.size, "bucket", source_handle.bucket_id)
  11481. )
  11482. # === Source is a repo: copy-by-hash if xet-backed, download otherwise ===
  11483. else:
  11484. source_path = source_handle.path
  11485. source_repo_path_info: list[RepoFile | RepoFolder] = []
  11486. if source_path != "":
  11487. source_repo_path_info = self.get_paths_info(
  11488. repo_id=source_handle.repo_id,
  11489. paths=[source_path],
  11490. repo_type=source_handle.repo_type,
  11491. revision=source_handle.revision,
  11492. token=token,
  11493. )
  11494. if len(source_repo_path_info) == 1 and isinstance(source_repo_path_info[0], RepoFile):
  11495. # Source path matched a single file — skip .gitattributes (git-specific metadata)
  11496. if source_repo_path_info[0].path.rsplit("/", 1)[-1] == ".gitattributes":
  11497. return
  11498. target_path = _resolve_target_path(source_repo_path_info[0].path, None, is_single_file=True)
  11499. _add_repo_file(source_repo_path_info[0], target_path)
  11500. else:
  11501. # Source path is a folder — list and copy all files recursively
  11502. for repo_item in self.list_repo_tree(
  11503. repo_id=source_handle.repo_id,
  11504. path_in_repo=source_path,
  11505. recursive=True,
  11506. repo_type=source_handle.repo_type,
  11507. revision=source_handle.revision,
  11508. token=token,
  11509. ):
  11510. if not isinstance(repo_item, RepoFile):
  11511. continue
  11512. # Skip .gitattributes files (git-specific metadata, not relevant in a bucket)
  11513. if repo_item.path.rsplit("/", 1)[-1] == ".gitattributes":
  11514. continue
  11515. target_path = _resolve_target_path(repo_item.path, source_path or None, is_single_file=False)
  11516. _add_repo_file(repo_item, target_path)
  11517. # Download non-xet files in parallel
  11518. if pending_downloads:
  11519. def _download_and_collect(item: tuple[str, str]) -> None:
  11520. file_path, target_path = item
  11521. local_path = self.hf_hub_download(
  11522. repo_id=source_handle.repo_id, # type: ignore
  11523. repo_type=source_handle.repo_type, # type: ignore
  11524. filename=file_path,
  11525. revision=source_handle.revision, # type: ignore
  11526. token=token,
  11527. tqdm_class=silent_tqdm, # type: ignore
  11528. )
  11529. all_adds.append((local_path, target_path))
  11530. thread_map(_download_and_collect, pending_downloads, desc="Downloading text files for copy")
  11531. # Send copies first (no upload needed), then adds (may need upload)
  11532. if all_copies:
  11533. for copy_chunk in chunk_iterable(all_copies, chunk_size=_BUCKET_BATCH_ADD_CHUNK_SIZE):
  11534. self._batch_bucket_files(destination_bucket_id, copy=list(copy_chunk), token=token)
  11535. if all_adds:
  11536. for add_chunk in chunk_iterable(all_adds, chunk_size=_BUCKET_BATCH_ADD_CHUNK_SIZE):
  11537. self._batch_bucket_files(destination_bucket_id, add=list(add_chunk), token=token)
  11538. @validate_hf_hub_args
  11539. def batch_bucket_files(
  11540. self,
  11541. bucket_id: str,
  11542. *,
  11543. add: list[tuple[str | Path | bytes, str]] | None = None,
  11544. copy: list[tuple[str, str, str, str]] | None = None,
  11545. delete: list[str] | None = None,
  11546. token: str | bool | None = None,
  11547. ):
  11548. """Add, copy, and/or delete files in a bucket.
  11549. This is a non-transactional operation. If an error occurs in the process, some files may have been uploaded,
  11550. copied, or deleted while others haven't.
  11551. Args:
  11552. bucket_id (`str`):
  11553. The ID of the bucket (e.g. `"username/my-bucket"`).
  11554. add (`list` of `tuple`, *optional*):
  11555. Files to upload. Each element is a `(source, destination)` tuple where `source` is a path to a local
  11556. file (`str` or `Path`) or raw `bytes` content, and `destination` is the path in the bucket.
  11557. copy (`list` of `tuple`, *optional*):
  11558. Files to copy by xet hash. Each element is a `(source_repo_type, source_repo_id, xet_hash,
  11559. destination)` tuple where:
  11560. - `source_repo_type` is the type of the source repository: `"model"`, `"dataset"`, `"space"`, or
  11561. `"bucket"`.
  11562. - `source_repo_id` is the ID of the source repository or bucket (e.g. `"username/my-model"`).
  11563. - `xet_hash` is the xet hash of the file to copy.
  11564. - `destination` is the destination path in the bucket.
  11565. This is a server-side operation — no data is downloaded or re-uploaded.
  11566. delete (`list` of `str`, *optional*):
  11567. Paths of files to delete from the bucket.
  11568. token (`bool` or `str`, *optional*):
  11569. A valid user access token (string). Defaults to the locally saved
  11570. token, which is the recommended method for authentication (see
  11571. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  11572. To disable authentication, pass `False`.
  11573. Example:
  11574. ```python
  11575. >>> from huggingface_hub import batch_bucket_files
  11576. # Upload files
  11577. >>> batch_bucket_files(
  11578. ... "username/my-bucket",
  11579. ... add=[
  11580. ... ("./model.safetensors", "models/model.safetensors"),
  11581. ... (b'{{"key": "value"}}', "config.json"),
  11582. ... ],
  11583. ... )
  11584. # Copy xet files from another bucket or repo (server-side, no data transfer)
  11585. >>> batch_bucket_files(
  11586. ... "username/my-bucket",
  11587. ... copy=[
  11588. ... ("bucket", "username/source-bucket", "<xethash_1>", "models/model.safetensors"),
  11589. ... ("model", "username/my-model", "<xethash_2>", "models/config.safetensors"),
  11590. ... ],
  11591. ... )
  11592. # Delete files
  11593. >>> batch_bucket_files("username/my-bucket", delete=["old-model.bin"])
  11594. # Upload and delete in one batch
  11595. >>> batch_bucket_files(
  11596. ... "username/my-bucket",
  11597. ... add=[("./new.txt", "new.txt")],
  11598. ... delete=["old.txt"],
  11599. ... )
  11600. ```
  11601. """
  11602. add = add or []
  11603. copy = copy or []
  11604. delete = delete or []
  11605. # Small batch: do everything in one call
  11606. if len(add) + len(copy) + len(delete) <= _BUCKET_BATCH_ADD_CHUNK_SIZE:
  11607. self._batch_bucket_files(bucket_id, add=add, copy=copy, delete=delete, token=token) # type: ignore
  11608. return
  11609. # Large batch: chunk copies first (no upload), then adds, then deletes
  11610. from .utils._xet_progress_reporting import XetProgressReporter
  11611. if add and not are_progress_bars_disabled():
  11612. progress = XetProgressReporter(total_files=len(add))
  11613. else:
  11614. progress = None
  11615. try:
  11616. for copy_chunk in chunk_iterable(copy, chunk_size=_BUCKET_BATCH_ADD_CHUNK_SIZE):
  11617. self._batch_bucket_files(bucket_id, copy=list(copy_chunk), token=token)
  11618. for add_chunk in chunk_iterable(add, chunk_size=_BUCKET_BATCH_ADD_CHUNK_SIZE):
  11619. self._batch_bucket_files(bucket_id, add=list(add_chunk), token=token, _progress=progress)
  11620. for delete_chunk in chunk_iterable(delete, chunk_size=_BUCKET_BATCH_DELETE_CHUNK_SIZE):
  11621. self._batch_bucket_files(bucket_id, delete=list(delete_chunk), token=token)
  11622. finally:
  11623. if progress is not None:
  11624. progress.close(False)
  11625. return
  11626. def _batch_bucket_files(
  11627. self,
  11628. bucket_id: str,
  11629. *,
  11630. add: list[tuple[str | Path | bytes, str] | _BucketAddFile] | None = None,
  11631. copy: list[tuple[str, str, str, str] | _BucketCopyFile] | None = None,
  11632. delete: list[str | _BucketDeleteFile] | None = None,
  11633. token: str | bool | None = None,
  11634. _progress: XetProgressReporter | None = None,
  11635. ):
  11636. """Internal method: process a single batch of bucket file operations (upload to XET + call /batch)."""
  11637. # Convert public API inputs to internal operation objects
  11638. operations: list[_BucketAddFile | _BucketCopyFile | _BucketDeleteFile] = []
  11639. if add:
  11640. for add_item in add:
  11641. if isinstance(add_item, _BucketAddFile):
  11642. operations.append(add_item)
  11643. else:
  11644. source, destination = add_item
  11645. operations.append(_BucketAddFile(source=source, destination=destination))
  11646. if copy:
  11647. for copy_item in copy:
  11648. if isinstance(copy_item, _BucketCopyFile):
  11649. operations.append(copy_item)
  11650. else:
  11651. source_repo_type, source_repo_id, xet_hash, destination = copy_item
  11652. operations.append(
  11653. _BucketCopyFile(
  11654. destination=destination,
  11655. xet_hash=xet_hash,
  11656. source_repo_type=source_repo_type,
  11657. source_repo_id=source_repo_id,
  11658. )
  11659. )
  11660. if delete:
  11661. for delete_item in delete:
  11662. if isinstance(delete_item, _BucketDeleteFile):
  11663. operations.append(delete_item)
  11664. else:
  11665. operations.append(_BucketDeleteFile(path=delete_item))
  11666. if not operations:
  11667. return
  11668. from hf_xet import upload_bytes, upload_files
  11669. from .utils._xet_progress_reporting import XetProgressReporter
  11670. headers = self._build_hf_headers(token=token)
  11671. add_operations = [op for op in operations if isinstance(op, _BucketAddFile)]
  11672. add_operations_to_upload = [op for op in add_operations if op.xet_hash is None]
  11673. add_bytes_operations = [op for op in add_operations if isinstance(op.source, bytes)]
  11674. add_path_operations = [op for op in add_operations if not isinstance(op.source, bytes)]
  11675. if len(add_operations_to_upload) > 0:
  11676. try:
  11677. xet_connection_info = fetch_xet_connection_info_from_repo_info(
  11678. token_type=XetTokenType.WRITE,
  11679. repo_id=bucket_id,
  11680. repo_type="bucket",
  11681. headers=headers,
  11682. endpoint=self.endpoint,
  11683. )
  11684. except HfHubHTTPError as e:
  11685. if e.response.status_code == 401:
  11686. raise XetAuthorizationError(
  11687. f"You are unauthorized to upload to xet storage for bucket/{bucket_id}. "
  11688. f"Please check that you have configured your access token with write access to the repo."
  11689. ) from e
  11690. raise
  11691. xet_endpoint = xet_connection_info.endpoint
  11692. access_token_info = (xet_connection_info.access_token, xet_connection_info.expiration_unix_epoch)
  11693. def token_refresher() -> tuple[str, int]:
  11694. new_xet_connection = fetch_xet_connection_info_from_repo_info(
  11695. token_type=XetTokenType.WRITE,
  11696. repo_id=bucket_id,
  11697. repo_type="bucket",
  11698. headers=headers,
  11699. endpoint=self.endpoint,
  11700. )
  11701. if new_xet_connection is None:
  11702. raise XetRefreshTokenError("Failed to refresh xet token")
  11703. return new_xet_connection.access_token, new_xet_connection.expiration_unix_epoch
  11704. owns_progress = _progress is None
  11705. if _progress is not None:
  11706. progress = _progress
  11707. progress_callback = progress.update_progress
  11708. elif not are_progress_bars_disabled():
  11709. progress = XetProgressReporter()
  11710. progress_callback = progress.update_progress
  11711. else:
  11712. progress, progress_callback = None, None
  11713. try:
  11714. # 2.a. Upload path files
  11715. xet_upload_infos = upload_files(
  11716. [str(op.source) for op in add_path_operations if op.xet_hash is None],
  11717. xet_endpoint,
  11718. access_token_info,
  11719. token_refresher,
  11720. progress_callback,
  11721. "bucket",
  11722. skip_sha256=True,
  11723. )
  11724. for upload_info, op in zip(
  11725. xet_upload_infos, [op for op in add_path_operations if op.xet_hash is None]
  11726. ):
  11727. op.xet_hash = upload_info.hash
  11728. op.size = upload_info.filesize
  11729. if progress is not None:
  11730. progress.notify_upload_complete()
  11731. # 2.b. Upload bytes files
  11732. xet_upload_infos = upload_bytes(
  11733. [op.source for op in add_bytes_operations if op.xet_hash is None],
  11734. xet_endpoint,
  11735. access_token_info,
  11736. token_refresher,
  11737. progress_callback,
  11738. "bucket",
  11739. skip_sha256=True,
  11740. )
  11741. for upload_info, op in zip(
  11742. xet_upload_infos, [op for op in add_bytes_operations if op.xet_hash is None]
  11743. ):
  11744. op.xet_hash = upload_info.hash
  11745. op.size = upload_info.filesize
  11746. if progress is not None:
  11747. progress.notify_upload_complete()
  11748. finally:
  11749. if owns_progress and progress is not None:
  11750. progress.close(False)
  11751. # 3. /batch call
  11752. def _payload_as_ndjson() -> Iterable[bytes]:
  11753. for op in operations:
  11754. if isinstance(op, _BucketAddFile):
  11755. payload = {
  11756. "type": "addFile",
  11757. "path": op.destination,
  11758. "xetHash": op.xet_hash,
  11759. "mtime": op.mtime,
  11760. }
  11761. if op.content_type is not None:
  11762. payload["contentType"] = op.content_type
  11763. elif isinstance(op, _BucketCopyFile):
  11764. payload = {
  11765. "type": "copyFile",
  11766. "path": op.destination,
  11767. "xetHash": op.xet_hash,
  11768. "sourceRepoType": op.source_repo_type,
  11769. "sourceRepoId": op.source_repo_id,
  11770. }
  11771. else:
  11772. payload = {
  11773. "type": "deleteFile",
  11774. "path": op.path,
  11775. }
  11776. yield json.dumps(payload).encode()
  11777. yield b"\n"
  11778. headers = {
  11779. "Content-Type": "application/x-ndjson",
  11780. **headers,
  11781. }
  11782. data = b"".join(_payload_as_ndjson())
  11783. response = http_backoff(
  11784. "POST", f"{self.endpoint}/api/buckets/{bucket_id}/batch", headers=headers, content=data
  11785. )
  11786. hf_raise_for_status(response)
  11787. @validate_hf_hub_args
  11788. def get_bucket_file_metadata(
  11789. self,
  11790. bucket_id: str,
  11791. remote_path: str,
  11792. *,
  11793. token: str | bool | None = None,
  11794. ) -> BucketFileMetadata:
  11795. """Fetch metadata of a file in a bucket.
  11796. Args:
  11797. bucket_id (`str`):
  11798. The ID of the bucket (e.g. `"username/my-bucket"`).
  11799. remote_path (`str`):
  11800. The path of the file in the bucket.
  11801. token (`bool` or `str`, *optional*):
  11802. A valid user access token (string). Defaults to the locally saved
  11803. token, which is the recommended method for authentication (see
  11804. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  11805. To disable authentication, pass `False`.
  11806. Returns:
  11807. [`BucketFileMetadata`]: The file metadata containing size and xet information.
  11808. Example:
  11809. ```python
  11810. >>> from huggingface_hub import get_bucket_file_metadata
  11811. >>> metadata = get_bucket_file_metadata(
  11812. ... bucket_id="username/my-bucket",
  11813. ... remote_path="models/model.safetensors",
  11814. ... )
  11815. >>> metadata.size
  11816. 42000
  11817. ```
  11818. """
  11819. response = _httpx_follow_relative_redirects_with_backoff(
  11820. "HEAD",
  11821. f"{self.endpoint}/buckets/{bucket_id}/resolve/{quote(remote_path, safe='')}",
  11822. headers=self._build_hf_headers(token=token),
  11823. retry_on_errors=True,
  11824. )
  11825. xet_file_data = parse_xet_file_data_from_response(response)
  11826. if xet_file_data is None:
  11827. raise ValueError(f"Could not parse xet file data for '{remote_path}' in bucket '{bucket_id}'.")
  11828. size = response.headers.get("Content-Length")
  11829. if size is None:
  11830. raise ValueError(f"Could not get size for '{remote_path}' in bucket '{bucket_id}'.")
  11831. return BucketFileMetadata(size=int(size), xet_file_data=xet_file_data)
  11832. @validate_hf_hub_args
  11833. def download_bucket_files(
  11834. self,
  11835. bucket_id: str,
  11836. files: list[tuple[str | BucketFile, str | Path]],
  11837. *,
  11838. raise_on_missing_files: bool = False,
  11839. token: str | bool | None = None,
  11840. ) -> None:
  11841. """Download files from a bucket.
  11842. Files input is a list of `(remote file, local file)` tuples where `remote file` is either the path of the file
  11843. in the bucket or a [`BucketFile`] object, and `local file` is the destination path on the local filesystem.
  11844. When passing a [`BucketFile`] object (obtained from [`list_bucket_tree`]), the method will skip the metadata
  11845. fetching step and directly download the files.
  11846. Args:
  11847. bucket_id (`str`):
  11848. The ID of the bucket (e.g. `"username/my-bucket"`).
  11849. files (`list[tuple[Union[str, BucketFile], Union[str, Path]]]`):
  11850. Files to download as a list of tuple (source, destination). See description above for format details.
  11851. raise_on_missing_files (`bool`, *optional*):
  11852. If `True`, raise an [`EntryNotFoundError`] when a requested file does not exist in the bucket. If
  11853. `False` (default), missing files are skipped with a warning.
  11854. token (`bool` or `str`, *optional*):
  11855. A valid user access token (string). Defaults to the locally saved
  11856. token, which is the recommended method for authentication (see
  11857. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  11858. To disable authentication, pass `False`.
  11859. Example:
  11860. ```python
  11861. >>> from huggingface_hub import download_bucket_files
  11862. >>> download_bucket_files(
  11863. ... bucket_id="username/my-bucket",
  11864. ... files=[
  11865. ... ("models/model.safetensors", "./local/model.safetensors"),
  11866. ... ("config.json", "./local/config.json"),
  11867. ... ],
  11868. ... )
  11869. ```
  11870. ```python
  11871. >>> from huggingface_hub import download_bucket_files
  11872. >>> parquet_files = [file for file in list_bucket_tree(bucket_id="username/my-bucket") if file.path.endswith(".parquet")]
  11873. >>> download_bucket_files(
  11874. ... bucket_id="username/my-bucket",
  11875. ... files=[(file, f"./local/{file.path}") for file in parquet_files],
  11876. ... )
  11877. ```
  11878. """
  11879. from hf_xet import PyXetDownloadInfo, download_files # type: ignore[no-redef]
  11880. headers = self._build_hf_headers(token=token)
  11881. if len(files) == 0:
  11882. return
  11883. # Resolve all string paths to BucketFile objects in a single batch request
  11884. str_paths = [path for path, _ in files if not isinstance(path, BucketFile)]
  11885. bucket_files_by_path: dict[str, BucketFile] = {}
  11886. if str_paths:
  11887. bucket_files_by_path = {
  11888. info.path: info for info in self.get_bucket_paths_info(bucket_id, str_paths, token=token)
  11889. }
  11890. # Check for missing files
  11891. missing_paths = [path for path in str_paths if path not in bucket_files_by_path]
  11892. if missing_paths:
  11893. if raise_on_missing_files:
  11894. raise EntryNotFoundError(
  11895. f"{len(missing_paths)} file(s) not found in bucket '{bucket_id}': {', '.join(missing_paths)}"
  11896. )
  11897. for path in missing_paths:
  11898. warnings.warn(f"File '{path}' not found in bucket '{bucket_id}'. Skipping.")
  11899. xet_download_infos = []
  11900. first_valid_bucket_file: BucketFile | None = None
  11901. for remote_file, local_path in files:
  11902. if not isinstance(remote_file, BucketFile):
  11903. if remote_file not in bucket_files_by_path:
  11904. continue # skip missing files (already warned above)
  11905. remote_file = bucket_files_by_path[remote_file]
  11906. if first_valid_bucket_file is None:
  11907. first_valid_bucket_file = remote_file
  11908. xet_download_infos.append(
  11909. PyXetDownloadInfo(
  11910. destination_path=str(Path(local_path).absolute()),
  11911. hash=remote_file.xet_hash,
  11912. file_size=remote_file.size,
  11913. )
  11914. )
  11915. if len(xet_download_infos) == 0 or first_valid_bucket_file is None:
  11916. return
  11917. # Fetch Xet connection info (same for all files)
  11918. remote_path = first_valid_bucket_file.path
  11919. metadata = self.get_bucket_file_metadata(bucket_id, remote_path, token=token)
  11920. connection_info = refresh_xet_connection_info(file_data=metadata.xet_file_data, headers=headers)
  11921. def token_refresher() -> tuple[str, int]:
  11922. connection_info = refresh_xet_connection_info(file_data=metadata.xet_file_data, headers=headers)
  11923. if connection_info is None:
  11924. raise ValueError("Failed to refresh token using xet metadata.")
  11925. return connection_info.access_token, connection_info.expiration_unix_epoch
  11926. # Create empty files for zero-size files (no need to download them)
  11927. # and filter them out from xet_download_infos to avoid passing to xet library
  11928. non_zero_download_infos = []
  11929. for download_info in xet_download_infos:
  11930. if download_info.file_size == 0:
  11931. dest_path = Path(download_info.destination_path)
  11932. if dest_path.exists():
  11933. # already exists => make sure it's an empty file
  11934. if dest_path.is_dir():
  11935. raise IsADirectoryError(f"Expected file but found directory at '{dest_path}'")
  11936. if dest_path.stat().st_size != 0:
  11937. dest_path.write_bytes(b"")
  11938. else:
  11939. # doesn't exist => create it
  11940. dest_path.parent.mkdir(parents=True, exist_ok=True)
  11941. dest_path.touch()
  11942. else:
  11943. non_zero_download_infos.append(download_info)
  11944. # If only zero-size files, nothing more to download
  11945. if len(non_zero_download_infos) == 0:
  11946. return
  11947. # Download files
  11948. progress_cm = _get_progress_bar_context(
  11949. desc="Downloading bucket files",
  11950. log_level=logger.getEffectiveLevel(),
  11951. total=sum(info.file_size for info in non_zero_download_infos),
  11952. initial=0,
  11953. name="huggingface_hub.download_bucket_files",
  11954. )
  11955. with progress_cm as progress:
  11956. def progress_updater(progress_bytes: float):
  11957. progress.update(progress_bytes)
  11958. download_files(
  11959. non_zero_download_infos,
  11960. endpoint=connection_info.endpoint,
  11961. token_info=(connection_info.access_token, connection_info.expiration_unix_epoch),
  11962. token_refresher=token_refresher,
  11963. progress_updater=[progress_updater] * len(non_zero_download_infos),
  11964. )
  11965. @validate_hf_hub_args
  11966. def sync_bucket(
  11967. self,
  11968. source: str | None = None,
  11969. dest: str | None = None,
  11970. *,
  11971. delete: bool = False,
  11972. ignore_times: bool = False,
  11973. ignore_sizes: bool = False,
  11974. existing: bool = False,
  11975. ignore_existing: bool = False,
  11976. include: list[str] | None = None,
  11977. exclude: list[str] | None = None,
  11978. filter_from: str | None = None,
  11979. plan: str | None = None,
  11980. apply: str | None = None,
  11981. dry_run: bool = False,
  11982. verbose: bool = False,
  11983. quiet: bool = False,
  11984. token: bool | str | None = None,
  11985. ) -> SyncPlan:
  11986. """Sync files between a local directory and a bucket.
  11987. This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path
  11988. (``hf://buckets/...``) and the other must be a local directory path.
  11989. Args:
  11990. source (`str`, *optional*):
  11991. Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
  11992. Required unless using ``apply``.
  11993. dest (`str`, *optional*):
  11994. Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
  11995. Required unless using ``apply``.
  11996. delete (`bool`, *optional*, defaults to `False`):
  11997. Delete destination files not present in source.
  11998. ignore_times (`bool`, *optional*, defaults to `False`):
  11999. Skip files only based on size, ignoring modification times.
  12000. ignore_sizes (`bool`, *optional*, defaults to `False`):
  12001. Skip files only based on modification times, ignoring sizes.
  12002. existing (`bool`, *optional*, defaults to `False`):
  12003. Skip creating new files on receiver (only update existing files).
  12004. ignore_existing (`bool`, *optional*, defaults to `False`):
  12005. Skip updating files that exist on receiver (only create new files).
  12006. include (`list[str]`, *optional*):
  12007. Include files matching patterns (fnmatch-style).
  12008. exclude (`list[str]`, *optional*):
  12009. Exclude files matching patterns (fnmatch-style).
  12010. filter_from (`str`, *optional*):
  12011. Path to a filter file with include/exclude rules.
  12012. plan (`str`, *optional*):
  12013. Save sync plan to this JSONL file instead of executing.
  12014. apply (`str`, *optional*):
  12015. Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed.
  12016. dry_run (`bool`, *optional*, defaults to `False`):
  12017. Print sync plan to stdout as JSONL without executing.
  12018. verbose (`bool`, *optional*, defaults to `False`):
  12019. Show detailed per-file operations.
  12020. quiet (`bool`, *optional*, defaults to `False`):
  12021. Suppress all output and progress bars.
  12022. token (Union[bool, str, None], optional):
  12023. A valid user access token. If not provided, the locally saved token will be used.
  12024. Returns:
  12025. [`SyncPlan`]: The computed (or loaded) sync plan.
  12026. Example:
  12027. ```python
  12028. >>> from huggingface_hub import HfApi
  12029. >>> api = HfApi()
  12030. # Upload local directory to bucket
  12031. >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")
  12032. # Download bucket to local directory
  12033. >>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")
  12034. # Sync with delete and filtering
  12035. >>> api.sync_bucket(
  12036. ... "./data",
  12037. ... "hf://buckets/username/my-bucket",
  12038. ... delete=True,
  12039. ... include=["*.safetensors"],
  12040. ... )
  12041. # Dry run: preview what would be synced
  12042. >>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
  12043. >>> plan.summary()
  12044. {'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}
  12045. # Save plan for review, then apply
  12046. >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")
  12047. >>> api.sync_bucket(apply="sync-plan.jsonl")
  12048. ```
  12049. """
  12050. return sync_bucket_internal(
  12051. source=source,
  12052. dest=dest,
  12053. api=self,
  12054. delete=delete,
  12055. ignore_times=ignore_times,
  12056. ignore_sizes=ignore_sizes,
  12057. existing=existing,
  12058. ignore_existing=ignore_existing,
  12059. include=include,
  12060. exclude=exclude,
  12061. filter_from=filter_from,
  12062. plan=plan,
  12063. apply=apply,
  12064. dry_run=dry_run,
  12065. verbose=verbose,
  12066. quiet=quiet,
  12067. token=token,
  12068. )
  12069. def _parse_revision_from_pr_url(pr_url: str) -> str:
  12070. """Safely parse revision number from a PR url.
  12071. Example:
  12072. ```py
  12073. >>> _parse_revision_from_pr_url("https://huggingface.co/bigscience/bloom/discussions/2")
  12074. "refs/pr/2"
  12075. ```
  12076. """
  12077. re_match = re.match(_REGEX_DISCUSSION_URL, pr_url)
  12078. if re_match is None:
  12079. raise RuntimeError(f"Unexpected response from the hub, expected a Pull Request URL but got: '{pr_url}'")
  12080. return f"refs/pr/{re_match[1]}"
  12081. def parse_local_safetensors_file_metadata(path: str | Path) -> SafetensorsFileMetadata:
  12082. """
  12083. Parse metadata from a local safetensors file.
  12084. For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
  12085. Args:
  12086. path (`str` or `Path`):
  12087. Path to the safetensors file.
  12088. Returns:
  12089. [`SafetensorsFileMetadata`]: information related to the safetensors file.
  12090. Raises:
  12091. [`SafetensorsParsingError`]:
  12092. If the safetensors file header couldn't be parsed correctly.
  12093. `FileNotFoundError`:
  12094. If the file does not exist.
  12095. Example:
  12096. ```py
  12097. >>> metadata = parse_local_safetensors_file_metadata("path/to/model.safetensors")
  12098. >>> metadata
  12099. SafetensorsFileMetadata(
  12100. metadata={'format': 'pt'},
  12101. tensors={'layer.weight': TensorInfo(dtype='F32', shape=[512, 512], ...}, ...}
  12102. )
  12103. >>> metadata.parameter_count
  12104. {'F32': 262144}
  12105. ```
  12106. """
  12107. path = Path(path)
  12108. filename = path.name
  12109. context_msg = f"path '{path}'"
  12110. with open(path, "rb") as f:
  12111. # 1. Read first 8 bytes and parse/validate metadata size using shared helper
  12112. size_bytes = f.read(8)
  12113. metadata_size = _get_safetensors_metadata_size(size_bytes, filename, context_msg)
  12114. # 2. Read metadata bytes
  12115. metadata_as_bytes = f.read(metadata_size)
  12116. if len(metadata_as_bytes) < metadata_size:
  12117. raise SafetensorsParsingError(
  12118. f"Failed to parse safetensors header for '{filename}' ({context_msg}): file is truncated. Expected "
  12119. f"{metadata_size} bytes of metadata but got {len(metadata_as_bytes)}."
  12120. )
  12121. # 3. Parse using shared helper
  12122. return _parse_safetensors_header(metadata_as_bytes, filename, context_msg)
  12123. def get_local_safetensors_metadata(path: str | Path) -> SafetensorsRepoMetadata:
  12124. """
  12125. Parse metadata for a local safetensors file or folder.
  12126. Supports:
  12127. - Single safetensors file (e.g., `model.safetensors`)
  12128. - Directory with non-sharded model (contains `model.safetensors`)
  12129. - Directory with sharded model (contains `model.safetensors.index.json`)
  12130. For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
  12131. Args:
  12132. path (`str` or `Path`):
  12133. Path to a safetensors file or directory containing safetensors files.
  12134. Returns:
  12135. [`SafetensorsRepoMetadata`]: information related to the safetensors repo.
  12136. Raises:
  12137. [`NotASafetensorsRepoError`]:
  12138. If the path is not a valid safetensors file or folder (i.e., doesn't have either a
  12139. `model.safetensors` or a `model.safetensors.index.json` file).
  12140. [`SafetensorsParsingError`]:
  12141. If a safetensors file header couldn't be parsed correctly.
  12142. `FileNotFoundError`:
  12143. If the path does not exist.
  12144. Example:
  12145. ```py
  12146. # Parse single safetensors file
  12147. >>> metadata = get_local_safetensors_metadata("path/to/model.safetensors")
  12148. >>> metadata
  12149. SafetensorsRepoMetadata(metadata=None, sharded=False, weight_map={...}, files_metadata={...})
  12150. # Parse directory with sharded model
  12151. >>> metadata = get_local_safetensors_metadata("path/to/model_folder")
  12152. >>> metadata
  12153. SafetensorsRepoMetadata(metadata={'total_size': ...}, sharded=True, weight_map={...}, files_metadata={...})
  12154. >>> len(metadata.files_metadata)
  12155. 3 # Number of safetensors shards
  12156. ```
  12157. """
  12158. path = Path(path)
  12159. # Case 1: Direct path to a safetensors file
  12160. if path.is_file():
  12161. file_metadata = parse_local_safetensors_file_metadata(path)
  12162. return SafetensorsRepoMetadata(
  12163. metadata=None,
  12164. sharded=False,
  12165. weight_map={tensor_name: path.name for tensor_name in file_metadata.tensors.keys()},
  12166. files_metadata={path.name: file_metadata},
  12167. )
  12168. # Case 2: Directory
  12169. if not path.is_dir():
  12170. raise FileNotFoundError(f"Path '{path}' does not exist.")
  12171. single_file_path = path / constants.SAFETENSORS_SINGLE_FILE
  12172. index_file_path = path / constants.SAFETENSORS_INDEX_FILE
  12173. # Case 2a: Non-sharded model (single model.safetensors file)
  12174. if single_file_path.exists():
  12175. file_metadata = parse_local_safetensors_file_metadata(single_file_path)
  12176. return SafetensorsRepoMetadata(
  12177. metadata=None,
  12178. sharded=False,
  12179. weight_map={
  12180. tensor_name: constants.SAFETENSORS_SINGLE_FILE for tensor_name in file_metadata.tensors.keys()
  12181. },
  12182. files_metadata={constants.SAFETENSORS_SINGLE_FILE: file_metadata},
  12183. )
  12184. # Case 2b: Sharded model (model.safetensors.index.json)
  12185. if index_file_path.exists():
  12186. with open(index_file_path) as f:
  12187. index = json.load(f)
  12188. weight_map = index.get("weight_map", {})
  12189. # Parse metadata from each shard
  12190. files_metadata = {}
  12191. for shard_filename in set(weight_map.values()):
  12192. shard_path = path / shard_filename
  12193. files_metadata[shard_filename] = parse_local_safetensors_file_metadata(shard_path)
  12194. return SafetensorsRepoMetadata(
  12195. metadata=index.get("metadata", None),
  12196. sharded=True,
  12197. weight_map=weight_map,
  12198. files_metadata=files_metadata,
  12199. )
  12200. # Not a valid safetensors folder
  12201. raise NotASafetensorsRepoError(
  12202. f"'{path}' is not a valid safetensors folder. Couldn't find '{constants.SAFETENSORS_INDEX_FILE}' or "
  12203. f"'{constants.SAFETENSORS_SINGLE_FILE}' files."
  12204. )
  12205. api = HfApi()
  12206. whoami = api.whoami
  12207. auth_check = api.auth_check
  12208. list_models = api.list_models
  12209. model_info = api.model_info
  12210. list_datasets = api.list_datasets
  12211. list_dataset_parquet_files = api.list_dataset_parquet_files
  12212. dataset_info = api.dataset_info
  12213. get_dataset_leaderboard = api.get_dataset_leaderboard
  12214. list_spaces = api.list_spaces
  12215. search_spaces = api.search_spaces
  12216. space_info = api.space_info
  12217. kernel_info = api.kernel_info
  12218. list_papers = api.list_papers
  12219. paper_info = api.paper_info
  12220. read_paper = api.read_paper
  12221. list_daily_papers = api.list_daily_papers
  12222. repo_exists = api.repo_exists
  12223. revision_exists = api.revision_exists
  12224. file_exists = api.file_exists
  12225. repo_info = api.repo_info
  12226. list_repo_files = api.list_repo_files
  12227. list_repo_refs = api.list_repo_refs
  12228. list_repo_commits = api.list_repo_commits
  12229. list_repo_tree = api.list_repo_tree
  12230. get_paths_info = api.get_paths_info
  12231. verify_repo_checksums = api.verify_repo_checksums
  12232. get_model_tags = api.get_model_tags
  12233. get_dataset_tags = api.get_dataset_tags
  12234. create_commit = api.create_commit
  12235. create_repo = api.create_repo
  12236. delete_repo = api.delete_repo
  12237. update_repo_settings = api.update_repo_settings
  12238. move_repo = api.move_repo
  12239. upload_file = api.upload_file
  12240. upload_folder = api.upload_folder
  12241. delete_file = api.delete_file
  12242. delete_folder = api.delete_folder
  12243. delete_files = api.delete_files
  12244. upload_large_folder = api.upload_large_folder
  12245. preupload_lfs_files = api.preupload_lfs_files
  12246. create_branch = api.create_branch
  12247. delete_branch = api.delete_branch
  12248. create_tag = api.create_tag
  12249. delete_tag = api.delete_tag
  12250. get_full_repo_name = api.get_full_repo_name
  12251. # Danger-zone API
  12252. super_squash_history = api.super_squash_history
  12253. list_lfs_files = api.list_lfs_files
  12254. permanently_delete_lfs_files = api.permanently_delete_lfs_files
  12255. # Safetensors helpers
  12256. get_safetensors_metadata = api.get_safetensors_metadata
  12257. parse_safetensors_file_metadata = api.parse_safetensors_file_metadata
  12258. # Background jobs
  12259. run_as_future = api.run_as_future
  12260. # Activity API
  12261. list_liked_repos = api.list_liked_repos
  12262. list_repo_likers = api.list_repo_likers
  12263. unlike = api.unlike
  12264. # Community API
  12265. get_discussion_details = api.get_discussion_details
  12266. get_repo_discussions = api.get_repo_discussions
  12267. create_discussion = api.create_discussion
  12268. create_pull_request = api.create_pull_request
  12269. change_discussion_status = api.change_discussion_status
  12270. comment_discussion = api.comment_discussion
  12271. edit_discussion_comment = api.edit_discussion_comment
  12272. rename_discussion = api.rename_discussion
  12273. merge_pull_request = api.merge_pull_request
  12274. # Space API
  12275. add_space_secret = api.add_space_secret
  12276. delete_space_secret = api.delete_space_secret
  12277. get_space_variables = api.get_space_variables
  12278. add_space_variable = api.add_space_variable
  12279. delete_space_variable = api.delete_space_variable
  12280. get_space_runtime = api.get_space_runtime
  12281. request_space_hardware = api.request_space_hardware
  12282. set_space_sleep_time = api.set_space_sleep_time
  12283. pause_space = api.pause_space
  12284. restart_space = api.restart_space
  12285. duplicate_repo = api.duplicate_repo
  12286. duplicate_space = api.duplicate_space
  12287. request_space_storage = api.request_space_storage
  12288. delete_space_storage = api.delete_space_storage
  12289. set_space_volumes = api.set_space_volumes
  12290. delete_space_volumes = api.delete_space_volumes
  12291. enable_space_dev_mode = api.enable_space_dev_mode
  12292. disable_space_dev_mode = api.disable_space_dev_mode
  12293. fetch_space_logs = api.fetch_space_logs
  12294. # Inference Endpoint API
  12295. list_inference_endpoints = api.list_inference_endpoints
  12296. create_inference_endpoint = api.create_inference_endpoint
  12297. get_inference_endpoint = api.get_inference_endpoint
  12298. update_inference_endpoint = api.update_inference_endpoint
  12299. delete_inference_endpoint = api.delete_inference_endpoint
  12300. pause_inference_endpoint = api.pause_inference_endpoint
  12301. resume_inference_endpoint = api.resume_inference_endpoint
  12302. scale_to_zero_inference_endpoint = api.scale_to_zero_inference_endpoint
  12303. create_inference_endpoint_from_catalog = api.create_inference_endpoint_from_catalog
  12304. list_inference_catalog = api.list_inference_catalog
  12305. # Collections API
  12306. get_collection = api.get_collection
  12307. list_collections = api.list_collections
  12308. create_collection = api.create_collection
  12309. update_collection_metadata = api.update_collection_metadata
  12310. delete_collection = api.delete_collection
  12311. add_collection_item = api.add_collection_item
  12312. update_collection_item = api.update_collection_item
  12313. delete_collection_item = api.delete_collection_item
  12314. delete_collection_item = api.delete_collection_item
  12315. # Access requests API
  12316. list_pending_access_requests = api.list_pending_access_requests
  12317. list_accepted_access_requests = api.list_accepted_access_requests
  12318. list_rejected_access_requests = api.list_rejected_access_requests
  12319. cancel_access_request = api.cancel_access_request
  12320. accept_access_request = api.accept_access_request
  12321. reject_access_request = api.reject_access_request
  12322. grant_access = api.grant_access
  12323. # Webhooks API
  12324. create_webhook = api.create_webhook
  12325. disable_webhook = api.disable_webhook
  12326. delete_webhook = api.delete_webhook
  12327. enable_webhook = api.enable_webhook
  12328. get_webhook = api.get_webhook
  12329. list_webhooks = api.list_webhooks
  12330. update_webhook = api.update_webhook
  12331. # User API
  12332. get_user_overview = api.get_user_overview
  12333. get_organization_overview = api.get_organization_overview
  12334. list_organization_followers = api.list_organization_followers
  12335. list_organization_members = api.list_organization_members
  12336. list_user_followers = api.list_user_followers
  12337. list_user_following = api.list_user_following
  12338. # Jobs API
  12339. run_job = api.run_job
  12340. fetch_job_logs = api.fetch_job_logs
  12341. fetch_job_metrics = api.fetch_job_metrics
  12342. list_jobs = api.list_jobs
  12343. list_jobs_hardware = api.list_jobs_hardware
  12344. inspect_job = api.inspect_job
  12345. cancel_job = api.cancel_job
  12346. run_uv_job = api.run_uv_job
  12347. create_scheduled_job = api.create_scheduled_job
  12348. list_scheduled_jobs = api.list_scheduled_jobs
  12349. inspect_scheduled_job = api.inspect_scheduled_job
  12350. delete_scheduled_job = api.delete_scheduled_job
  12351. suspend_scheduled_job = api.suspend_scheduled_job
  12352. resume_scheduled_job = api.resume_scheduled_job
  12353. create_scheduled_uv_job = api.create_scheduled_uv_job
  12354. # Buckets API
  12355. create_bucket = api.create_bucket
  12356. bucket_info = api.bucket_info
  12357. list_buckets = api.list_buckets
  12358. delete_bucket = api.delete_bucket
  12359. move_bucket = api.move_bucket
  12360. list_bucket_tree = api.list_bucket_tree
  12361. get_bucket_paths_info = api.get_bucket_paths_info
  12362. copy_files = api.copy_files
  12363. batch_bucket_files = api.batch_bucket_files
  12364. get_bucket_file_metadata = api.get_bucket_file_metadata
  12365. download_bucket_files = api.download_bucket_files
  12366. sync_bucket = api.sync_bucket