hf_api.py 476 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036
  1. # coding=utf-8
  2. # Copyright 2019-present, the HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import annotations
  16. import inspect
  17. import json
  18. import re
  19. import struct
  20. import time
  21. import warnings
  22. from collections import defaultdict
  23. from concurrent.futures import Future, ThreadPoolExecutor
  24. from dataclasses import asdict, dataclass, field
  25. from datetime import datetime
  26. from functools import wraps
  27. from itertools import islice
  28. from pathlib import Path
  29. from textwrap import dedent
  30. from typing import (
  31. TYPE_CHECKING,
  32. Any,
  33. BinaryIO,
  34. Callable,
  35. Dict,
  36. Iterable,
  37. Iterator,
  38. List,
  39. Literal,
  40. Optional,
  41. Tuple,
  42. Type,
  43. TypeVar,
  44. Union,
  45. overload,
  46. )
  47. from urllib.parse import quote
  48. import requests
  49. from requests.exceptions import HTTPError
  50. from tqdm.auto import tqdm as base_tqdm
  51. from tqdm.contrib.concurrent import thread_map
  52. from . import constants
  53. from ._commit_api import (
  54. CommitOperation,
  55. CommitOperationAdd,
  56. CommitOperationCopy,
  57. CommitOperationDelete,
  58. _fetch_files_to_copy,
  59. _fetch_upload_modes,
  60. _prepare_commit_payload,
  61. _upload_files,
  62. _warn_on_overwriting_operations,
  63. )
  64. from ._inference_endpoints import InferenceEndpoint, InferenceEndpointType
  65. from ._jobs_api import JobInfo, JobSpec, ScheduledJobInfo, _create_job_spec
  66. from ._space_api import SpaceHardware, SpaceRuntime, SpaceStorage, SpaceVariable
  67. from ._upload_large_folder import upload_large_folder_internal
  68. from .community import (
  69. Discussion,
  70. DiscussionComment,
  71. DiscussionStatusChange,
  72. DiscussionTitleChange,
  73. DiscussionWithDetails,
  74. deserialize_event,
  75. )
  76. from .constants import (
  77. DEFAULT_ETAG_TIMEOUT, # noqa: F401 # kept for backward compatibility
  78. DEFAULT_REQUEST_TIMEOUT, # noqa: F401 # kept for backward compatibility
  79. DEFAULT_REVISION, # noqa: F401 # kept for backward compatibility
  80. DISCUSSION_STATUS, # noqa: F401 # kept for backward compatibility
  81. DISCUSSION_TYPES, # noqa: F401 # kept for backward compatibility
  82. ENDPOINT, # noqa: F401 # kept for backward compatibility
  83. INFERENCE_ENDPOINTS_ENDPOINT, # noqa: F401 # kept for backward compatibility
  84. REGEX_COMMIT_OID, # noqa: F401 # kept for backward compatibility
  85. REPO_TYPE_MODEL, # noqa: F401 # kept for backward compatibility
  86. REPO_TYPES, # noqa: F401 # kept for backward compatibility
  87. REPO_TYPES_MAPPING, # noqa: F401 # kept for backward compatibility
  88. REPO_TYPES_URL_PREFIXES, # noqa: F401 # kept for backward compatibility
  89. SAFETENSORS_INDEX_FILE, # noqa: F401 # kept for backward compatibility
  90. SAFETENSORS_MAX_HEADER_LENGTH, # noqa: F401 # kept for backward compatibility
  91. SAFETENSORS_SINGLE_FILE, # noqa: F401 # kept for backward compatibility
  92. SPACES_SDK_TYPES, # noqa: F401 # kept for backward compatibility
  93. WEBHOOK_DOMAIN_T, # noqa: F401 # kept for backward compatibility
  94. DiscussionStatusFilter, # noqa: F401 # kept for backward compatibility
  95. DiscussionTypeFilter, # noqa: F401 # kept for backward compatibility
  96. )
  97. from .errors import (
  98. BadRequestError,
  99. EntryNotFoundError,
  100. GatedRepoError,
  101. HfHubHTTPError,
  102. RepositoryNotFoundError,
  103. RevisionNotFoundError,
  104. )
  105. from .file_download import HfFileMetadata, get_hf_file_metadata, hf_hub_url
  106. from .repocard_data import DatasetCardData, ModelCardData, SpaceCardData
  107. from .utils import (
  108. DEFAULT_IGNORE_PATTERNS,
  109. HfFolder, # noqa: F401 # kept for backward compatibility
  110. LocalTokenNotFoundError,
  111. NotASafetensorsRepoError,
  112. SafetensorsFileMetadata,
  113. SafetensorsParsingError,
  114. SafetensorsRepoMetadata,
  115. TensorInfo,
  116. build_hf_headers,
  117. chunk_iterable,
  118. experimental,
  119. filter_repo_objects,
  120. fix_hf_endpoint_in_url,
  121. get_session,
  122. get_token,
  123. hf_raise_for_status,
  124. logging,
  125. paginate,
  126. parse_datetime,
  127. validate_hf_hub_args,
  128. )
  129. from .utils import tqdm as hf_tqdm
  130. from .utils._auth import _get_token_from_environment, _get_token_from_file, _get_token_from_google_colab
  131. from .utils._deprecation import _deprecate_arguments, _deprecate_method
  132. from .utils._typing import CallableT
  133. from .utils.endpoint_helpers import _is_emission_within_threshold
  134. if TYPE_CHECKING:
  135. from .inference._providers import PROVIDER_T
  136. R = TypeVar("R") # Return type
  137. CollectionItemType_T = Literal["model", "dataset", "space", "paper", "collection"]
  138. ExpandModelProperty_T = Literal[
  139. "author",
  140. "baseModels",
  141. "cardData",
  142. "childrenModelCount",
  143. "config",
  144. "createdAt",
  145. "disabled",
  146. "downloads",
  147. "downloadsAllTime",
  148. "gated",
  149. "gguf",
  150. "inference",
  151. "inferenceProviderMapping",
  152. "lastModified",
  153. "library_name",
  154. "likes",
  155. "mask_token",
  156. "model-index",
  157. "pipeline_tag",
  158. "private",
  159. "resourceGroup",
  160. "safetensors",
  161. "sha",
  162. "siblings",
  163. "spaces",
  164. "tags",
  165. "transformersInfo",
  166. "trendingScore",
  167. "usedStorage",
  168. "widgetData",
  169. "xetEnabled",
  170. ]
  171. ExpandDatasetProperty_T = Literal[
  172. "author",
  173. "cardData",
  174. "citation",
  175. "createdAt",
  176. "description",
  177. "disabled",
  178. "downloads",
  179. "downloadsAllTime",
  180. "gated",
  181. "lastModified",
  182. "likes",
  183. "paperswithcode_id",
  184. "private",
  185. "resourceGroup",
  186. "sha",
  187. "siblings",
  188. "tags",
  189. "trendingScore",
  190. "usedStorage",
  191. "xetEnabled",
  192. ]
  193. ExpandSpaceProperty_T = Literal[
  194. "author",
  195. "cardData",
  196. "createdAt",
  197. "datasets",
  198. "disabled",
  199. "lastModified",
  200. "likes",
  201. "models",
  202. "private",
  203. "resourceGroup",
  204. "runtime",
  205. "sdk",
  206. "sha",
  207. "siblings",
  208. "subdomain",
  209. "tags",
  210. "trendingScore",
  211. "usedStorage",
  212. "xetEnabled",
  213. ]
  214. USERNAME_PLACEHOLDER = "hf_user"
  215. _REGEX_DISCUSSION_URL = re.compile(r".*/discussions/(\d+)$")
  216. _CREATE_COMMIT_NO_REPO_ERROR_MESSAGE = (
  217. "\nNote: Creating a commit assumes that the repo already exists on the"
  218. " Huggingface Hub. Please use `create_repo` if it's not the case."
  219. )
  220. _AUTH_CHECK_NO_REPO_ERROR_MESSAGE = (
  221. "\nNote: The repository either does not exist or you do not have access rights."
  222. " Please check the repository ID and your access permissions."
  223. " If this is a private repository, ensure that your token is correct."
  224. )
  225. logger = logging.get_logger(__name__)
  226. def repo_type_and_id_from_hf_id(hf_id: str, hub_url: Optional[str] = None) -> Tuple[Optional[str], Optional[str], str]:
  227. """
  228. Returns the repo type and ID from a huggingface.co URL linking to a
  229. repository
  230. Args:
  231. hf_id (`str`):
  232. An URL or ID of a repository on the HF hub. Accepted values are:
  233. - https://huggingface.co/<repo_type>/<namespace>/<repo_id>
  234. - https://huggingface.co/<namespace>/<repo_id>
  235. - hf://<repo_type>/<namespace>/<repo_id>
  236. - hf://<namespace>/<repo_id>
  237. - <repo_type>/<namespace>/<repo_id>
  238. - <namespace>/<repo_id>
  239. - <repo_id>
  240. hub_url (`str`, *optional*):
  241. The URL of the HuggingFace Hub, defaults to https://huggingface.co
  242. Returns:
  243. A tuple with three items: repo_type (`str` or `None`), namespace (`str` or
  244. `None`) and repo_id (`str`).
  245. Raises:
  246. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  247. If URL cannot be parsed.
  248. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  249. If `repo_type` is unknown.
  250. """
  251. input_hf_id = hf_id
  252. hub_url = re.sub(r"https?://", "", hub_url if hub_url is not None else constants.ENDPOINT)
  253. is_hf_url = hub_url in hf_id and "@" not in hf_id
  254. HFFS_PREFIX = "hf://"
  255. if hf_id.startswith(HFFS_PREFIX): # Remove "hf://" prefix if exists
  256. hf_id = hf_id[len(HFFS_PREFIX) :]
  257. url_segments = hf_id.split("/")
  258. is_hf_id = len(url_segments) <= 3
  259. namespace: Optional[str]
  260. if is_hf_url:
  261. namespace, repo_id = url_segments[-2:]
  262. if namespace == hub_url:
  263. namespace = None
  264. if len(url_segments) > 2 and hub_url not in url_segments[-3]:
  265. repo_type = url_segments[-3]
  266. elif namespace in constants.REPO_TYPES_MAPPING:
  267. # Mean canonical dataset or model
  268. repo_type = constants.REPO_TYPES_MAPPING[namespace]
  269. namespace = None
  270. else:
  271. repo_type = None
  272. elif is_hf_id:
  273. if len(url_segments) == 3:
  274. # Passed <repo_type>/<user>/<model_id> or <repo_type>/<org>/<model_id>
  275. repo_type, namespace, repo_id = url_segments[-3:]
  276. elif len(url_segments) == 2:
  277. if url_segments[0] in constants.REPO_TYPES_MAPPING:
  278. # Passed '<model_id>' or 'datasets/<dataset_id>' for a canonical model or dataset
  279. repo_type = constants.REPO_TYPES_MAPPING[url_segments[0]]
  280. namespace = None
  281. repo_id = hf_id.split("/")[-1]
  282. else:
  283. # Passed <user>/<model_id> or <org>/<model_id>
  284. namespace, repo_id = hf_id.split("/")[-2:]
  285. repo_type = None
  286. else:
  287. # Passed <model_id>
  288. repo_id = url_segments[0]
  289. namespace, repo_type = None, None
  290. else:
  291. raise ValueError(f"Unable to retrieve user and repo ID from the passed HF ID: {hf_id}")
  292. # Check if repo type is known (mapping "spaces" => "space" + empty value => `None`)
  293. if repo_type in constants.REPO_TYPES_MAPPING:
  294. repo_type = constants.REPO_TYPES_MAPPING[repo_type]
  295. if repo_type == "":
  296. repo_type = None
  297. if repo_type not in constants.REPO_TYPES:
  298. raise ValueError(f"Unknown `repo_type`: '{repo_type}' ('{input_hf_id}')")
  299. return repo_type, namespace, repo_id
  300. @dataclass
  301. class LastCommitInfo(dict):
  302. oid: str
  303. title: str
  304. date: datetime
  305. def __post_init__(self): # hack to make LastCommitInfo backward compatible
  306. self.update(asdict(self))
  307. @dataclass
  308. class BlobLfsInfo(dict):
  309. size: int
  310. sha256: str
  311. pointer_size: int
  312. def __post_init__(self): # hack to make BlobLfsInfo backward compatible
  313. self.update(asdict(self))
  314. @dataclass
  315. class BlobSecurityInfo(dict):
  316. safe: bool # duplicate information with "status" field, keeping it for backward compatibility
  317. status: str
  318. av_scan: Optional[Dict]
  319. pickle_import_scan: Optional[Dict]
  320. def __post_init__(self): # hack to make BlogSecurityInfo backward compatible
  321. self.update(asdict(self))
  322. @dataclass
  323. class TransformersInfo(dict):
  324. auto_model: str
  325. custom_class: Optional[str] = None
  326. # possible `pipeline_tag` values: https://github.com/huggingface/huggingface.js/blob/3ee32554b8620644a6287e786b2a83bf5caf559c/packages/tasks/src/pipelines.ts#L72
  327. pipeline_tag: Optional[str] = None
  328. processor: Optional[str] = None
  329. def __post_init__(self): # hack to make TransformersInfo backward compatible
  330. self.update(asdict(self))
  331. @dataclass
  332. class SafeTensorsInfo(dict):
  333. parameters: Dict[str, int]
  334. total: int
  335. def __post_init__(self): # hack to make SafeTensorsInfo backward compatible
  336. self.update(asdict(self))
  337. @dataclass
  338. class CommitInfo(str):
  339. """Data structure containing information about a newly created commit.
  340. Returned by any method that creates a commit on the Hub: [`create_commit`], [`upload_file`], [`upload_folder`],
  341. [`delete_file`], [`delete_folder`]. It inherits from `str` for backward compatibility but using methods specific
  342. to `str` is deprecated.
  343. Attributes:
  344. commit_url (`str`):
  345. Url where to find the commit.
  346. commit_message (`str`):
  347. The summary (first line) of the commit that has been created.
  348. commit_description (`str`):
  349. Description of the commit that has been created. Can be empty.
  350. oid (`str`):
  351. Commit hash id. Example: `"91c54ad1727ee830252e457677f467be0bfd8a57"`.
  352. pr_url (`str`, *optional*):
  353. Url to the PR that has been created, if any. Populated when `create_pr=True`
  354. is passed.
  355. pr_revision (`str`, *optional*):
  356. Revision of the PR that has been created, if any. Populated when
  357. `create_pr=True` is passed. Example: `"refs/pr/1"`.
  358. pr_num (`int`, *optional*):
  359. Number of the PR discussion that has been created, if any. Populated when
  360. `create_pr=True` is passed. Can be passed as `discussion_num` in
  361. [`get_discussion_details`]. Example: `1`.
  362. repo_url (`RepoUrl`):
  363. Repo URL of the commit containing info like repo_id, repo_type, etc.
  364. _url (`str`, *optional*):
  365. Legacy url for `str` compatibility. Can be the url to the uploaded file on the Hub (if returned by
  366. [`upload_file`]), to the uploaded folder on the Hub (if returned by [`upload_folder`]) or to the commit on
  367. the Hub (if returned by [`create_commit`]). Defaults to `commit_url`. It is deprecated to use this
  368. attribute. Please use `commit_url` instead.
  369. """
  370. commit_url: str
  371. commit_message: str
  372. commit_description: str
  373. oid: str
  374. pr_url: Optional[str] = None
  375. # Computed from `commit_url` in `__post_init__`
  376. repo_url: RepoUrl = field(init=False)
  377. # Computed from `pr_url` in `__post_init__`
  378. pr_revision: Optional[str] = field(init=False)
  379. pr_num: Optional[str] = field(init=False)
  380. # legacy url for `str` compatibility (ex: url to uploaded file, url to uploaded folder, url to PR, etc.)
  381. _url: str = field(repr=False, default=None) # type: ignore # defaults to `commit_url`
  382. def __new__(cls, *args, commit_url: str, _url: Optional[str] = None, **kwargs):
  383. return str.__new__(cls, _url or commit_url)
  384. def __post_init__(self):
  385. """Populate pr-related fields after initialization.
  386. See https://docs.python.org/3.10/library/dataclasses.html#post-init-processing.
  387. """
  388. # Repo info
  389. self.repo_url = RepoUrl(self.commit_url.split("/commit/")[0])
  390. # PR info
  391. if self.pr_url is not None:
  392. self.pr_revision = _parse_revision_from_pr_url(self.pr_url)
  393. self.pr_num = int(self.pr_revision.split("/")[-1])
  394. else:
  395. self.pr_revision = None
  396. self.pr_num = None
  397. @dataclass
  398. class AccessRequest:
  399. """Data structure containing information about a user access request.
  400. Attributes:
  401. username (`str`):
  402. Username of the user who requested access.
  403. fullname (`str`):
  404. Fullname of the user who requested access.
  405. email (`Optional[str]`):
  406. Email of the user who requested access.
  407. Can only be `None` in the /accepted list if the user was granted access manually.
  408. timestamp (`datetime`):
  409. Timestamp of the request.
  410. status (`Literal["pending", "accepted", "rejected"]`):
  411. Status of the request. Can be one of `["pending", "accepted", "rejected"]`.
  412. fields (`Dict[str, Any]`, *optional*):
  413. Additional fields filled by the user in the gate form.
  414. """
  415. username: str
  416. fullname: str
  417. email: Optional[str]
  418. timestamp: datetime
  419. status: Literal["pending", "accepted", "rejected"]
  420. # Additional fields filled by the user in the gate form
  421. fields: Optional[Dict[str, Any]] = None
  422. @dataclass
  423. class WebhookWatchedItem:
  424. """Data structure containing information about the items watched by a webhook.
  425. Attributes:
  426. type (`Literal["dataset", "model", "org", "space", "user"]`):
  427. Type of the item to be watched. Can be one of `["dataset", "model", "org", "space", "user"]`.
  428. name (`str`):
  429. Name of the item to be watched. Can be the username, organization name, model name, dataset name or space name.
  430. """
  431. type: Literal["dataset", "model", "org", "space", "user"]
  432. name: str
  433. @dataclass
  434. class WebhookInfo:
  435. """Data structure containing information about a webhook.
  436. One of `url` or `job` is specified, but not both.
  437. Attributes:
  438. id (`str`):
  439. ID of the webhook.
  440. url (`str`, *optional*):
  441. URL of the webhook.
  442. job (`JobSpec`, *optional*):
  443. Specifications of the Job to trigger.
  444. watched (`List[WebhookWatchedItem]`):
  445. List of items watched by the webhook, see [`WebhookWatchedItem`].
  446. domains (`List[WEBHOOK_DOMAIN_T]`):
  447. List of domains the webhook is watching. Can be one of `["repo", "discussions"]`.
  448. secret (`str`, *optional*):
  449. Secret of the webhook.
  450. disabled (`bool`):
  451. Whether the webhook is disabled or not.
  452. """
  453. id: str
  454. url: Optional[str]
  455. job: Optional[JobSpec]
  456. watched: List[WebhookWatchedItem]
  457. domains: List[constants.WEBHOOK_DOMAIN_T]
  458. secret: Optional[str]
  459. disabled: bool
  460. class RepoUrl(str):
  461. """Subclass of `str` describing a repo URL on the Hub.
  462. `RepoUrl` is returned by `HfApi.create_repo`. It inherits from `str` for backward
  463. compatibility. At initialization, the URL is parsed to populate properties:
  464. - endpoint (`str`)
  465. - namespace (`Optional[str]`)
  466. - repo_name (`str`)
  467. - repo_id (`str`)
  468. - repo_type (`Literal["model", "dataset", "space"]`)
  469. - url (`str`)
  470. Args:
  471. url (`Any`):
  472. String value of the repo url.
  473. endpoint (`str`, *optional*):
  474. Endpoint of the Hub. Defaults to <https://huggingface.co>.
  475. Example:
  476. ```py
  477. >>> RepoUrl('https://huggingface.co/gpt2')
  478. RepoUrl('https://huggingface.co/gpt2', endpoint='https://huggingface.co', repo_type='model', repo_id='gpt2')
  479. >>> RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co')
  480. 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')
  481. >>> RepoUrl('hf://datasets/my-user/my-dataset')
  482. RepoUrl('hf://datasets/my-user/my-dataset', endpoint='https://huggingface.co', repo_type='dataset', repo_id='user/dataset')
  483. >>> HfApi.create_repo("dummy_model")
  484. RepoUrl('https://huggingface.co/Wauplin/dummy_model', endpoint='https://huggingface.co', repo_type='model', repo_id='Wauplin/dummy_model')
  485. ```
  486. Raises:
  487. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  488. If URL cannot be parsed.
  489. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  490. If `repo_type` is unknown.
  491. """
  492. def __new__(cls, url: Any, endpoint: Optional[str] = None):
  493. url = fix_hf_endpoint_in_url(url, endpoint=endpoint)
  494. return super(RepoUrl, cls).__new__(cls, url)
  495. def __init__(self, url: Any, endpoint: Optional[str] = None) -> None:
  496. super().__init__()
  497. # Parse URL
  498. self.endpoint = endpoint or constants.ENDPOINT
  499. repo_type, namespace, repo_name = repo_type_and_id_from_hf_id(self, hub_url=self.endpoint)
  500. # Populate fields
  501. self.namespace = namespace
  502. self.repo_name = repo_name
  503. self.repo_id = repo_name if namespace is None else f"{namespace}/{repo_name}"
  504. self.repo_type = repo_type or constants.REPO_TYPE_MODEL
  505. self.url = str(self) # just in case it's needed
  506. def __repr__(self) -> str:
  507. return f"RepoUrl('{self}', endpoint='{self.endpoint}', repo_type='{self.repo_type}', repo_id='{self.repo_id}')"
  508. @dataclass
  509. class RepoSibling:
  510. """
  511. Contains basic information about a repo file inside a repo on the Hub.
  512. > [!TIP]
  513. > All attributes of this class are optional except `rfilename`. This is because only the file names are returned when
  514. > listing repositories on the Hub (with [`list_models`], [`list_datasets`] or [`list_spaces`]). If you need more
  515. > information like file size, blob id or lfs details, you must request them specifically from one repo at a time
  516. > (using [`model_info`], [`dataset_info`] or [`space_info`]) as it adds more constraints on the backend server to
  517. > retrieve these.
  518. Attributes:
  519. rfilename (str):
  520. file name, relative to the repo root.
  521. size (`int`, *optional*):
  522. The file's size, in bytes. This attribute is defined when `files_metadata` argument of [`repo_info`] is set
  523. to `True`. It's `None` otherwise.
  524. blob_id (`str`, *optional*):
  525. The file's git OID. This attribute is defined when `files_metadata` argument of [`repo_info`] is set to
  526. `True`. It's `None` otherwise.
  527. lfs (`BlobLfsInfo`, *optional*):
  528. The file's LFS metadata. This attribute is defined when`files_metadata` argument of [`repo_info`] is set to
  529. `True` and the file is stored with Git LFS. It's `None` otherwise.
  530. """
  531. rfilename: str
  532. size: Optional[int] = None
  533. blob_id: Optional[str] = None
  534. lfs: Optional[BlobLfsInfo] = None
  535. @dataclass
  536. class RepoFile:
  537. """
  538. Contains information about a file on the Hub.
  539. Attributes:
  540. path (str):
  541. file path relative to the repo root.
  542. size (`int`):
  543. The file's size, in bytes.
  544. blob_id (`str`):
  545. The file's git OID.
  546. lfs (`BlobLfsInfo`):
  547. The file's LFS metadata.
  548. last_commit (`LastCommitInfo`, *optional*):
  549. The file's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
  550. are called with `expand=True`.
  551. security (`BlobSecurityInfo`, *optional*):
  552. The file's security scan metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
  553. are called with `expand=True`.
  554. """
  555. path: str
  556. size: int
  557. blob_id: str
  558. lfs: Optional[BlobLfsInfo] = None
  559. last_commit: Optional[LastCommitInfo] = None
  560. security: Optional[BlobSecurityInfo] = None
  561. def __init__(self, **kwargs):
  562. self.path = kwargs.pop("path")
  563. self.size = kwargs.pop("size")
  564. self.blob_id = kwargs.pop("oid")
  565. lfs = kwargs.pop("lfs", None)
  566. if lfs is not None:
  567. lfs = BlobLfsInfo(size=lfs["size"], sha256=lfs["oid"], pointer_size=lfs["pointerSize"])
  568. self.lfs = lfs
  569. last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None)
  570. if last_commit is not None:
  571. last_commit = LastCommitInfo(
  572. oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"])
  573. )
  574. self.last_commit = last_commit
  575. security = kwargs.pop("securityFileStatus", None)
  576. if security is not None:
  577. safe = security["status"] == "safe"
  578. security = BlobSecurityInfo(
  579. safe=safe,
  580. status=security["status"],
  581. av_scan=security["avScan"],
  582. pickle_import_scan=security["pickleImportScan"],
  583. )
  584. self.security = security
  585. # backwards compatibility
  586. self.rfilename = self.path
  587. self.lastCommit = self.last_commit
  588. @dataclass
  589. class RepoFolder:
  590. """
  591. Contains information about a folder on the Hub.
  592. Attributes:
  593. path (str):
  594. folder path relative to the repo root.
  595. tree_id (`str`):
  596. The folder's git OID.
  597. last_commit (`LastCommitInfo`, *optional*):
  598. The folder's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
  599. are called with `expand=True`.
  600. """
  601. path: str
  602. tree_id: str
  603. last_commit: Optional[LastCommitInfo] = None
  604. def __init__(self, **kwargs):
  605. self.path = kwargs.pop("path")
  606. self.tree_id = kwargs.pop("oid")
  607. last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None)
  608. if last_commit is not None:
  609. last_commit = LastCommitInfo(
  610. oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"])
  611. )
  612. self.last_commit = last_commit
  613. @dataclass
  614. class InferenceProviderMapping:
  615. provider: "PROVIDER_T" # Provider name
  616. hf_model_id: str # ID of the model on the Hugging Face Hub
  617. provider_id: str # ID of the model on the provider's side
  618. status: Literal["error", "live", "staging"]
  619. task: str
  620. adapter: Optional[str] = None
  621. adapter_weights_path: Optional[str] = None
  622. type: Optional[Literal["single-model", "tag-filter"]] = None
  623. def __init__(self, **kwargs):
  624. self.provider = kwargs.pop("provider")
  625. self.hf_model_id = kwargs.pop("hf_model_id")
  626. self.provider_id = kwargs.pop("providerId")
  627. self.status = kwargs.pop("status")
  628. self.task = kwargs.pop("task")
  629. self.adapter = kwargs.pop("adapter", None)
  630. self.adapter_weights_path = kwargs.pop("adapterWeightsPath", None)
  631. self.type = kwargs.pop("type", None)
  632. self.__dict__.update(**kwargs)
  633. @dataclass
  634. class ModelInfo:
  635. """
  636. Contains information about a model on the Hub. This object is returned by [`model_info`] and [`list_models`].
  637. > [!TIP]
  638. > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
  639. > In general, the more specific the query, the more information is returned. On the contrary, when listing models
  640. > using [`list_models`] only a subset of the attributes are returned.
  641. Attributes:
  642. id (`str`):
  643. ID of model.
  644. author (`str`, *optional*):
  645. Author of the model.
  646. sha (`str`, *optional*):
  647. Repo SHA at this particular revision.
  648. created_at (`datetime`, *optional*):
  649. Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
  650. corresponding to the date when we began to store creation dates.
  651. last_modified (`datetime`, *optional*):
  652. Date of last commit to the repo.
  653. private (`bool`):
  654. Is the repo private.
  655. disabled (`bool`, *optional*):
  656. Is the repo disabled.
  657. downloads (`int`):
  658. Number of downloads of the model over the last 30 days.
  659. downloads_all_time (`int`):
  660. Cumulated number of downloads of the model since its creation.
  661. gated (`Literal["auto", "manual", False]`, *optional*):
  662. Is the repo gated.
  663. If so, whether there is manual or automatic approval.
  664. gguf (`Dict`, *optional*):
  665. GGUF information of the model.
  666. inference (`Literal["warm"]`, *optional*):
  667. Status of the model on Inference Providers. Warm if the model is served by at least one provider.
  668. inference_provider_mapping (`List[InferenceProviderMapping]`, *optional*):
  669. A list of [`InferenceProviderMapping`] ordered after the user's provider order.
  670. likes (`int`):
  671. Number of likes of the model.
  672. library_name (`str`, *optional*):
  673. Library associated with the model.
  674. tags (`List[str]`):
  675. List of tags of the model. Compared to `card_data.tags`, contains extra tags computed by the Hub
  676. (e.g. supported libraries, model's arXiv).
  677. pipeline_tag (`str`, *optional*):
  678. Pipeline tag associated with the model.
  679. mask_token (`str`, *optional*):
  680. Mask token used by the model.
  681. widget_data (`Any`, *optional*):
  682. Widget data associated with the model.
  683. model_index (`Dict`, *optional*):
  684. Model index for evaluation.
  685. config (`Dict`, *optional*):
  686. Model configuration.
  687. transformers_info (`TransformersInfo`, *optional*):
  688. Transformers-specific info (auto class, processor, etc.) associated with the model.
  689. trending_score (`int`, *optional*):
  690. Trending score of the model.
  691. card_data (`ModelCardData`, *optional*):
  692. Model Card Metadata as a [`huggingface_hub.repocard_data.ModelCardData`] object.
  693. siblings (`List[RepoSibling]`):
  694. List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the model.
  695. spaces (`List[str]`, *optional*):
  696. List of spaces using the model.
  697. safetensors (`SafeTensorsInfo`, *optional*):
  698. Model's safetensors information.
  699. security_repo_status (`Dict`, *optional*):
  700. Model's security scan status.
  701. """
  702. id: str
  703. author: Optional[str]
  704. sha: Optional[str]
  705. created_at: Optional[datetime]
  706. last_modified: Optional[datetime]
  707. private: Optional[bool]
  708. disabled: Optional[bool]
  709. downloads: Optional[int]
  710. downloads_all_time: Optional[int]
  711. gated: Optional[Literal["auto", "manual", False]]
  712. gguf: Optional[Dict]
  713. inference: Optional[Literal["warm"]]
  714. inference_provider_mapping: Optional[List[InferenceProviderMapping]]
  715. likes: Optional[int]
  716. library_name: Optional[str]
  717. tags: Optional[List[str]]
  718. pipeline_tag: Optional[str]
  719. mask_token: Optional[str]
  720. card_data: Optional[ModelCardData]
  721. widget_data: Optional[Any]
  722. model_index: Optional[Dict]
  723. config: Optional[Dict]
  724. transformers_info: Optional[TransformersInfo]
  725. trending_score: Optional[int]
  726. siblings: Optional[List[RepoSibling]]
  727. spaces: Optional[List[str]]
  728. safetensors: Optional[SafeTensorsInfo]
  729. security_repo_status: Optional[Dict]
  730. xet_enabled: Optional[bool]
  731. def __init__(self, **kwargs):
  732. self.id = kwargs.pop("id")
  733. self.author = kwargs.pop("author", None)
  734. self.sha = kwargs.pop("sha", None)
  735. last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
  736. self.last_modified = parse_datetime(last_modified) if last_modified else None
  737. created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
  738. self.created_at = parse_datetime(created_at) if created_at else None
  739. self.private = kwargs.pop("private", None)
  740. self.gated = kwargs.pop("gated", None)
  741. self.disabled = kwargs.pop("disabled", None)
  742. self.downloads = kwargs.pop("downloads", None)
  743. self.downloads_all_time = kwargs.pop("downloadsAllTime", None)
  744. self.likes = kwargs.pop("likes", None)
  745. self.library_name = kwargs.pop("library_name", None)
  746. self.gguf = kwargs.pop("gguf", None)
  747. self.inference = kwargs.pop("inference", None)
  748. # little hack to simplify Inference Providers logic and make it backward and forward compatible
  749. # right now, API returns a dict on model_info and a list on list_models. Let's harmonize to list.
  750. mapping = kwargs.pop("inferenceProviderMapping", None)
  751. if isinstance(mapping, list):
  752. self.inference_provider_mapping = [
  753. InferenceProviderMapping(**{**value, "hf_model_id": self.id}) for value in mapping
  754. ]
  755. elif isinstance(mapping, dict):
  756. self.inference_provider_mapping = [
  757. InferenceProviderMapping(**{**value, "hf_model_id": self.id, "provider": provider})
  758. for provider, value in mapping.items()
  759. ]
  760. elif mapping is None:
  761. self.inference_provider_mapping = None
  762. else:
  763. raise ValueError(
  764. f"Unexpected type for `inferenceProviderMapping`. Expecting `dict` or `list`. Got {mapping}."
  765. )
  766. self.tags = kwargs.pop("tags", None)
  767. self.pipeline_tag = kwargs.pop("pipeline_tag", None)
  768. self.mask_token = kwargs.pop("mask_token", None)
  769. self.trending_score = kwargs.pop("trendingScore", None)
  770. card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
  771. self.card_data = (
  772. ModelCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
  773. )
  774. self.widget_data = kwargs.pop("widgetData", None)
  775. self.model_index = kwargs.pop("model-index", None) or kwargs.pop("model_index", None)
  776. self.config = kwargs.pop("config", None)
  777. transformers_info = kwargs.pop("transformersInfo", None) or kwargs.pop("transformers_info", None)
  778. self.transformers_info = TransformersInfo(**transformers_info) if transformers_info else None
  779. siblings = kwargs.pop("siblings", None)
  780. self.siblings = (
  781. [
  782. RepoSibling(
  783. rfilename=sibling["rfilename"],
  784. size=sibling.get("size"),
  785. blob_id=sibling.get("blobId"),
  786. lfs=(
  787. BlobLfsInfo(
  788. size=sibling["lfs"]["size"],
  789. sha256=sibling["lfs"]["sha256"],
  790. pointer_size=sibling["lfs"]["pointerSize"],
  791. )
  792. if sibling.get("lfs")
  793. else None
  794. ),
  795. )
  796. for sibling in siblings
  797. ]
  798. if siblings is not None
  799. else None
  800. )
  801. self.spaces = kwargs.pop("spaces", None)
  802. safetensors = kwargs.pop("safetensors", None)
  803. self.safetensors = (
  804. SafeTensorsInfo(
  805. parameters=safetensors["parameters"],
  806. total=safetensors["total"],
  807. )
  808. if safetensors
  809. else None
  810. )
  811. self.security_repo_status = kwargs.pop("securityRepoStatus", None)
  812. self.xet_enabled = kwargs.pop("xetEnabled", None)
  813. # backwards compatibility
  814. self.lastModified = self.last_modified
  815. self.cardData = self.card_data
  816. self.transformersInfo = self.transformers_info
  817. self.__dict__.update(**kwargs)
  818. @dataclass
  819. class DatasetInfo:
  820. """
  821. Contains information about a dataset on the Hub. This object is returned by [`dataset_info`] and [`list_datasets`].
  822. > [!TIP]
  823. > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
  824. > In general, the more specific the query, the more information is returned. On the contrary, when listing datasets
  825. > using [`list_datasets`] only a subset of the attributes are returned.
  826. Attributes:
  827. id (`str`):
  828. ID of dataset.
  829. author (`str`):
  830. Author of the dataset.
  831. sha (`str`):
  832. Repo SHA at this particular revision.
  833. created_at (`datetime`, *optional*):
  834. Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
  835. corresponding to the date when we began to store creation dates.
  836. last_modified (`datetime`, *optional*):
  837. Date of last commit to the repo.
  838. private (`bool`):
  839. Is the repo private.
  840. disabled (`bool`, *optional*):
  841. Is the repo disabled.
  842. gated (`Literal["auto", "manual", False]`, *optional*):
  843. Is the repo gated.
  844. If so, whether there is manual or automatic approval.
  845. downloads (`int`):
  846. Number of downloads of the dataset over the last 30 days.
  847. downloads_all_time (`int`):
  848. Cumulated number of downloads of the model since its creation.
  849. likes (`int`):
  850. Number of likes of the dataset.
  851. tags (`List[str]`):
  852. List of tags of the dataset.
  853. card_data (`DatasetCardData`, *optional*):
  854. Model Card Metadata as a [`huggingface_hub.repocard_data.DatasetCardData`] object.
  855. siblings (`List[RepoSibling]`):
  856. List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the dataset.
  857. paperswithcode_id (`str`, *optional*):
  858. Papers with code ID of the dataset.
  859. trending_score (`int`, *optional*):
  860. Trending score of the dataset.
  861. """
  862. id: str
  863. author: Optional[str]
  864. sha: Optional[str]
  865. created_at: Optional[datetime]
  866. last_modified: Optional[datetime]
  867. private: Optional[bool]
  868. gated: Optional[Literal["auto", "manual", False]]
  869. disabled: Optional[bool]
  870. downloads: Optional[int]
  871. downloads_all_time: Optional[int]
  872. likes: Optional[int]
  873. paperswithcode_id: Optional[str]
  874. tags: Optional[List[str]]
  875. trending_score: Optional[int]
  876. card_data: Optional[DatasetCardData]
  877. siblings: Optional[List[RepoSibling]]
  878. xet_enabled: Optional[bool]
  879. def __init__(self, **kwargs):
  880. self.id = kwargs.pop("id")
  881. self.author = kwargs.pop("author", None)
  882. self.sha = kwargs.pop("sha", None)
  883. created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
  884. self.created_at = parse_datetime(created_at) if created_at else None
  885. last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
  886. self.last_modified = parse_datetime(last_modified) if last_modified else None
  887. self.private = kwargs.pop("private", None)
  888. self.gated = kwargs.pop("gated", None)
  889. self.disabled = kwargs.pop("disabled", None)
  890. self.downloads = kwargs.pop("downloads", None)
  891. self.downloads_all_time = kwargs.pop("downloadsAllTime", None)
  892. self.likes = kwargs.pop("likes", None)
  893. self.paperswithcode_id = kwargs.pop("paperswithcode_id", None)
  894. self.tags = kwargs.pop("tags", None)
  895. self.trending_score = kwargs.pop("trendingScore", None)
  896. card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
  897. self.card_data = (
  898. DatasetCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
  899. )
  900. siblings = kwargs.pop("siblings", None)
  901. self.siblings = (
  902. [
  903. RepoSibling(
  904. rfilename=sibling["rfilename"],
  905. size=sibling.get("size"),
  906. blob_id=sibling.get("blobId"),
  907. lfs=(
  908. BlobLfsInfo(
  909. size=sibling["lfs"]["size"],
  910. sha256=sibling["lfs"]["sha256"],
  911. pointer_size=sibling["lfs"]["pointerSize"],
  912. )
  913. if sibling.get("lfs")
  914. else None
  915. ),
  916. )
  917. for sibling in siblings
  918. ]
  919. if siblings is not None
  920. else None
  921. )
  922. self.xet_enabled = kwargs.pop("xetEnabled", None)
  923. # backwards compatibility
  924. self.lastModified = self.last_modified
  925. self.cardData = self.card_data
  926. self.__dict__.update(**kwargs)
  927. @dataclass
  928. class SpaceInfo:
  929. """
  930. Contains information about a Space on the Hub. This object is returned by [`space_info`] and [`list_spaces`].
  931. > [!TIP]
  932. > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
  933. > In general, the more specific the query, the more information is returned. On the contrary, when listing spaces
  934. > using [`list_spaces`] only a subset of the attributes are returned.
  935. Attributes:
  936. id (`str`):
  937. ID of the Space.
  938. author (`str`, *optional*):
  939. Author of the Space.
  940. sha (`str`, *optional*):
  941. Repo SHA at this particular revision.
  942. created_at (`datetime`, *optional*):
  943. Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
  944. corresponding to the date when we began to store creation dates.
  945. last_modified (`datetime`, *optional*):
  946. Date of last commit to the repo.
  947. private (`bool`):
  948. Is the repo private.
  949. gated (`Literal["auto", "manual", False]`, *optional*):
  950. Is the repo gated.
  951. If so, whether there is manual or automatic approval.
  952. disabled (`bool`, *optional*):
  953. Is the Space disabled.
  954. host (`str`, *optional*):
  955. Host URL of the Space.
  956. subdomain (`str`, *optional*):
  957. Subdomain of the Space.
  958. likes (`int`):
  959. Number of likes of the Space.
  960. tags (`List[str]`):
  961. List of tags of the Space.
  962. siblings (`List[RepoSibling]`):
  963. List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the Space.
  964. card_data (`SpaceCardData`, *optional*):
  965. Space Card Metadata as a [`huggingface_hub.repocard_data.SpaceCardData`] object.
  966. runtime (`SpaceRuntime`, *optional*):
  967. Space runtime information as a [`huggingface_hub.hf_api.SpaceRuntime`] object.
  968. sdk (`str`, *optional*):
  969. SDK used by the Space.
  970. models (`List[str]`, *optional*):
  971. List of models used by the Space.
  972. datasets (`List[str]`, *optional*):
  973. List of datasets used by the Space.
  974. trending_score (`int`, *optional*):
  975. Trending score of the Space.
  976. """
  977. id: str
  978. author: Optional[str]
  979. sha: Optional[str]
  980. created_at: Optional[datetime]
  981. last_modified: Optional[datetime]
  982. private: Optional[bool]
  983. gated: Optional[Literal["auto", "manual", False]]
  984. disabled: Optional[bool]
  985. host: Optional[str]
  986. subdomain: Optional[str]
  987. likes: Optional[int]
  988. sdk: Optional[str]
  989. tags: Optional[List[str]]
  990. siblings: Optional[List[RepoSibling]]
  991. trending_score: Optional[int]
  992. card_data: Optional[SpaceCardData]
  993. runtime: Optional[SpaceRuntime]
  994. models: Optional[List[str]]
  995. datasets: Optional[List[str]]
  996. xet_enabled: Optional[bool]
  997. def __init__(self, **kwargs):
  998. self.id = kwargs.pop("id")
  999. self.author = kwargs.pop("author", None)
  1000. self.sha = kwargs.pop("sha", None)
  1001. created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
  1002. self.created_at = parse_datetime(created_at) if created_at else None
  1003. last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
  1004. self.last_modified = parse_datetime(last_modified) if last_modified else None
  1005. self.private = kwargs.pop("private", None)
  1006. self.gated = kwargs.pop("gated", None)
  1007. self.disabled = kwargs.pop("disabled", None)
  1008. self.host = kwargs.pop("host", None)
  1009. self.subdomain = kwargs.pop("subdomain", None)
  1010. self.likes = kwargs.pop("likes", None)
  1011. self.sdk = kwargs.pop("sdk", None)
  1012. self.tags = kwargs.pop("tags", None)
  1013. self.trending_score = kwargs.pop("trendingScore", None)
  1014. card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
  1015. self.card_data = (
  1016. SpaceCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
  1017. )
  1018. siblings = kwargs.pop("siblings", None)
  1019. self.siblings = (
  1020. [
  1021. RepoSibling(
  1022. rfilename=sibling["rfilename"],
  1023. size=sibling.get("size"),
  1024. blob_id=sibling.get("blobId"),
  1025. lfs=(
  1026. BlobLfsInfo(
  1027. size=sibling["lfs"]["size"],
  1028. sha256=sibling["lfs"]["sha256"],
  1029. pointer_size=sibling["lfs"]["pointerSize"],
  1030. )
  1031. if sibling.get("lfs")
  1032. else None
  1033. ),
  1034. )
  1035. for sibling in siblings
  1036. ]
  1037. if siblings is not None
  1038. else None
  1039. )
  1040. runtime = kwargs.pop("runtime", None)
  1041. self.runtime = SpaceRuntime(runtime) if runtime else None
  1042. self.models = kwargs.pop("models", None)
  1043. self.datasets = kwargs.pop("datasets", None)
  1044. self.xet_enabled = kwargs.pop("xetEnabled", None)
  1045. # backwards compatibility
  1046. self.lastModified = self.last_modified
  1047. self.cardData = self.card_data
  1048. self.__dict__.update(**kwargs)
  1049. @dataclass
  1050. class CollectionItem:
  1051. """
  1052. Contains information about an item of a Collection (model, dataset, Space, paper or collection).
  1053. Attributes:
  1054. item_object_id (`str`):
  1055. Unique ID of the item in the collection.
  1056. item_id (`str`):
  1057. ID of the underlying object on the Hub. Can be either a repo_id, a paper id or a collection slug.
  1058. e.g. `"jbilcke-hf/ai-comic-factory"`, `"2307.09288"`, `"celinah/cerebras-function-calling-682607169c35fbfa98b30b9a"`.
  1059. item_type (`str`):
  1060. Type of the underlying object. Can be one of `"model"`, `"dataset"`, `"space"`, `"paper"` or `"collection"`.
  1061. position (`int`):
  1062. Position of the item in the collection.
  1063. note (`str`, *optional*):
  1064. Note associated with the item, as plain text.
  1065. """
  1066. item_object_id: str # id in database
  1067. item_id: str # repo_id or paper id
  1068. item_type: str
  1069. position: int
  1070. note: Optional[str] = None
  1071. def __init__(
  1072. self,
  1073. _id: str,
  1074. id: str,
  1075. type: CollectionItemType_T,
  1076. position: int,
  1077. note: Optional[Dict] = None,
  1078. **kwargs,
  1079. ) -> None:
  1080. self.item_object_id: str = _id # id in database
  1081. self.item_id: str = id # repo_id or paper id
  1082. # if the item is a collection, override item_id with the slug
  1083. slug = kwargs.get("slug")
  1084. if slug is not None:
  1085. self.item_id = slug # collection slug
  1086. self.item_type: CollectionItemType_T = type
  1087. self.position: int = position
  1088. self.note: str = note["text"] if note is not None else None
  1089. @dataclass
  1090. class Collection:
  1091. """
  1092. Contains information about a Collection on the Hub.
  1093. Attributes:
  1094. slug (`str`):
  1095. Slug of the collection. E.g. `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  1096. title (`str`):
  1097. Title of the collection. E.g. `"Recent models"`.
  1098. owner (`str`):
  1099. Owner of the collection. E.g. `"TheBloke"`.
  1100. items (`List[CollectionItem]`):
  1101. List of items in the collection.
  1102. last_updated (`datetime`):
  1103. Date of the last update of the collection.
  1104. position (`int`):
  1105. Position of the collection in the list of collections of the owner.
  1106. private (`bool`):
  1107. Whether the collection is private or not.
  1108. theme (`str`):
  1109. Theme of the collection. E.g. `"green"`.
  1110. upvotes (`int`):
  1111. Number of upvotes of the collection.
  1112. description (`str`, *optional*):
  1113. Description of the collection, as plain text.
  1114. url (`str`):
  1115. (property) URL of the collection on the Hub.
  1116. """
  1117. slug: str
  1118. title: str
  1119. owner: str
  1120. items: List[CollectionItem]
  1121. last_updated: datetime
  1122. position: int
  1123. private: bool
  1124. theme: str
  1125. upvotes: int
  1126. description: Optional[str] = None
  1127. def __init__(self, **kwargs) -> None:
  1128. self.slug = kwargs.pop("slug")
  1129. self.title = kwargs.pop("title")
  1130. self.owner = kwargs.pop("owner")
  1131. self.items = [CollectionItem(**item) for item in kwargs.pop("items")]
  1132. self.last_updated = parse_datetime(kwargs.pop("lastUpdated"))
  1133. self.position = kwargs.pop("position")
  1134. self.private = kwargs.pop("private")
  1135. self.theme = kwargs.pop("theme")
  1136. self.upvotes = kwargs.pop("upvotes")
  1137. self.description = kwargs.pop("description", None)
  1138. endpoint = kwargs.pop("endpoint", None)
  1139. if endpoint is None:
  1140. endpoint = constants.ENDPOINT
  1141. self._url = f"{endpoint}/collections/{self.slug}"
  1142. @property
  1143. def url(self) -> str:
  1144. """Returns the URL of the collection on the Hub."""
  1145. return self._url
  1146. @dataclass
  1147. class GitRefInfo:
  1148. """
  1149. Contains information about a git reference for a repo on the Hub.
  1150. Attributes:
  1151. name (`str`):
  1152. Name of the reference (e.g. tag name or branch name).
  1153. ref (`str`):
  1154. Full git ref on the Hub (e.g. `"refs/heads/main"` or `"refs/tags/v1.0"`).
  1155. target_commit (`str`):
  1156. OID of the target commit for the ref (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`)
  1157. """
  1158. name: str
  1159. ref: str
  1160. target_commit: str
  1161. @dataclass
  1162. class GitRefs:
  1163. """
  1164. Contains information about all git references for a repo on the Hub.
  1165. Object is returned by [`list_repo_refs`].
  1166. Attributes:
  1167. branches (`List[GitRefInfo]`):
  1168. A list of [`GitRefInfo`] containing information about branches on the repo.
  1169. converts (`List[GitRefInfo]`):
  1170. A list of [`GitRefInfo`] containing information about "convert" refs on the repo.
  1171. Converts are refs used (internally) to push preprocessed data in Dataset repos.
  1172. tags (`List[GitRefInfo]`):
  1173. A list of [`GitRefInfo`] containing information about tags on the repo.
  1174. pull_requests (`List[GitRefInfo]`, *optional*):
  1175. A list of [`GitRefInfo`] containing information about pull requests on the repo.
  1176. Only returned if `include_prs=True` is set.
  1177. """
  1178. branches: List[GitRefInfo]
  1179. converts: List[GitRefInfo]
  1180. tags: List[GitRefInfo]
  1181. pull_requests: Optional[List[GitRefInfo]] = None
  1182. @dataclass
  1183. class GitCommitInfo:
  1184. """
  1185. Contains information about a git commit for a repo on the Hub. Check out [`list_repo_commits`] for more details.
  1186. Attributes:
  1187. commit_id (`str`):
  1188. OID of the commit (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`)
  1189. authors (`List[str]`):
  1190. List of authors of the commit.
  1191. created_at (`datetime`):
  1192. Datetime when the commit was created.
  1193. title (`str`):
  1194. Title of the commit. This is a free-text value entered by the authors.
  1195. message (`str`):
  1196. Description of the commit. This is a free-text value entered by the authors.
  1197. formatted_title (`str`):
  1198. Title of the commit formatted as HTML. Only returned if `formatted=True` is set.
  1199. formatted_message (`str`):
  1200. Description of the commit formatted as HTML. Only returned if `formatted=True` is set.
  1201. """
  1202. commit_id: str
  1203. authors: List[str]
  1204. created_at: datetime
  1205. title: str
  1206. message: str
  1207. formatted_title: Optional[str]
  1208. formatted_message: Optional[str]
  1209. @dataclass
  1210. class UserLikes:
  1211. """
  1212. Contains information about a user likes on the Hub.
  1213. Attributes:
  1214. user (`str`):
  1215. Name of the user for which we fetched the likes.
  1216. total (`int`):
  1217. Total number of likes.
  1218. datasets (`List[str]`):
  1219. List of datasets liked by the user (as repo_ids).
  1220. models (`List[str]`):
  1221. List of models liked by the user (as repo_ids).
  1222. spaces (`List[str]`):
  1223. List of spaces liked by the user (as repo_ids).
  1224. """
  1225. # Metadata
  1226. user: str
  1227. total: int
  1228. # User likes
  1229. datasets: List[str]
  1230. models: List[str]
  1231. spaces: List[str]
  1232. @dataclass
  1233. class Organization:
  1234. """
  1235. Contains information about an organization on the Hub.
  1236. Attributes:
  1237. avatar_url (`str`):
  1238. URL of the organization's avatar.
  1239. name (`str`):
  1240. Name of the organization on the Hub (unique).
  1241. fullname (`str`):
  1242. Organization's full name.
  1243. details (`str`, *optional*):
  1244. Organization's description.
  1245. is_verified (`bool`, *optional*):
  1246. Whether the organization is verified.
  1247. is_following (`bool`, *optional*):
  1248. Whether the authenticated user follows this organization.
  1249. num_users (`int`, *optional*):
  1250. Number of members in the organization.
  1251. num_models (`int`, *optional*):
  1252. Number of models owned by the organization.
  1253. num_spaces (`int`, *optional*):
  1254. Number of Spaces owned by the organization.
  1255. num_datasets (`int`, *optional*):
  1256. Number of datasets owned by the organization.
  1257. num_followers (`int`, *optional*):
  1258. Number of followers of the organization.
  1259. """
  1260. avatar_url: str
  1261. name: str
  1262. fullname: str
  1263. details: Optional[str] = None
  1264. is_verified: Optional[bool] = None
  1265. is_following: Optional[bool] = None
  1266. num_users: Optional[int] = None
  1267. num_models: Optional[int] = None
  1268. num_spaces: Optional[int] = None
  1269. num_datasets: Optional[int] = None
  1270. num_followers: Optional[int] = None
  1271. def __init__(self, **kwargs) -> None:
  1272. self.avatar_url = kwargs.pop("avatarUrl", "")
  1273. self.name = kwargs.pop("name", "")
  1274. self.fullname = kwargs.pop("fullname", "")
  1275. self.details = kwargs.pop("details", None)
  1276. self.is_verified = kwargs.pop("isVerified", None)
  1277. self.is_following = kwargs.pop("isFollowing", None)
  1278. self.num_users = kwargs.pop("numUsers", None)
  1279. self.num_models = kwargs.pop("numModels", None)
  1280. self.num_spaces = kwargs.pop("numSpaces", None)
  1281. self.num_datasets = kwargs.pop("numDatasets", None)
  1282. self.num_followers = kwargs.pop("numFollowers", None)
  1283. # forward compatibility
  1284. self.__dict__.update(**kwargs)
  1285. @dataclass
  1286. class User:
  1287. """
  1288. Contains information about a user on the Hub.
  1289. Attributes:
  1290. username (`str`):
  1291. Name of the user on the Hub (unique).
  1292. fullname (`str`):
  1293. User's full name.
  1294. avatar_url (`str`):
  1295. URL of the user's avatar.
  1296. details (`str`, *optional*):
  1297. User's details.
  1298. is_following (`bool`, *optional*):
  1299. Whether the authenticated user is following this user.
  1300. is_pro (`bool`, *optional*):
  1301. Whether the user is a pro user.
  1302. num_models (`int`, *optional*):
  1303. Number of models created by the user.
  1304. num_datasets (`int`, *optional*):
  1305. Number of datasets created by the user.
  1306. num_spaces (`int`, *optional*):
  1307. Number of spaces created by the user.
  1308. num_discussions (`int`, *optional*):
  1309. Number of discussions initiated by the user.
  1310. num_papers (`int`, *optional*):
  1311. Number of papers authored by the user.
  1312. num_upvotes (`int`, *optional*):
  1313. Number of upvotes received by the user.
  1314. num_likes (`int`, *optional*):
  1315. Number of likes given by the user.
  1316. num_following (`int`, *optional*):
  1317. Number of users this user is following.
  1318. num_followers (`int`, *optional*):
  1319. Number of users following this user.
  1320. orgs (list of [`Organization`]):
  1321. List of organizations the user is part of.
  1322. """
  1323. # Metadata
  1324. username: str
  1325. fullname: str
  1326. avatar_url: str
  1327. details: Optional[str] = None
  1328. is_following: Optional[bool] = None
  1329. is_pro: Optional[bool] = None
  1330. num_models: Optional[int] = None
  1331. num_datasets: Optional[int] = None
  1332. num_spaces: Optional[int] = None
  1333. num_discussions: Optional[int] = None
  1334. num_papers: Optional[int] = None
  1335. num_upvotes: Optional[int] = None
  1336. num_likes: Optional[int] = None
  1337. num_following: Optional[int] = None
  1338. num_followers: Optional[int] = None
  1339. orgs: List[Organization] = field(default_factory=list)
  1340. def __init__(self, **kwargs) -> None:
  1341. self.username = kwargs.pop("user", "")
  1342. self.fullname = kwargs.pop("fullname", "")
  1343. self.avatar_url = kwargs.pop("avatarUrl", "")
  1344. self.is_following = kwargs.pop("isFollowing", None)
  1345. self.is_pro = kwargs.pop("isPro", None)
  1346. self.details = kwargs.pop("details", None)
  1347. self.num_models = kwargs.pop("numModels", None)
  1348. self.num_datasets = kwargs.pop("numDatasets", None)
  1349. self.num_spaces = kwargs.pop("numSpaces", None)
  1350. self.num_discussions = kwargs.pop("numDiscussions", None)
  1351. self.num_papers = kwargs.pop("numPapers", None)
  1352. self.num_upvotes = kwargs.pop("numUpvotes", None)
  1353. self.num_likes = kwargs.pop("numLikes", None)
  1354. self.num_following = kwargs.pop("numFollowing", None)
  1355. self.num_followers = kwargs.pop("numFollowers", None)
  1356. self.user_type = kwargs.pop("type", None)
  1357. self.orgs = [Organization(**org) for org in kwargs.pop("orgs", [])]
  1358. # forward compatibility
  1359. self.__dict__.update(**kwargs)
  1360. @dataclass
  1361. class PaperInfo:
  1362. """
  1363. Contains information about a paper on the Hub.
  1364. Attributes:
  1365. id (`str`):
  1366. arXiv paper ID.
  1367. authors (`List[str]`, **optional**):
  1368. Names of paper authors
  1369. published_at (`datetime`, **optional**):
  1370. Date paper published.
  1371. title (`str`, **optional**):
  1372. Title of the paper.
  1373. summary (`str`, **optional**):
  1374. Summary of the paper.
  1375. upvotes (`int`, **optional**):
  1376. Number of upvotes for the paper on the Hub.
  1377. discussion_id (`str`, **optional**):
  1378. Discussion ID for the paper on the Hub.
  1379. source (`str`, **optional**):
  1380. Source of the paper.
  1381. comments (`int`, **optional**):
  1382. Number of comments for the paper on the Hub.
  1383. submitted_at (`datetime`, **optional**):
  1384. Date paper appeared in daily papers on the Hub.
  1385. submitted_by (`User`, **optional**):
  1386. Information about who submitted the daily paper.
  1387. """
  1388. id: str
  1389. authors: Optional[List[str]]
  1390. published_at: Optional[datetime]
  1391. title: Optional[str]
  1392. summary: Optional[str]
  1393. upvotes: Optional[int]
  1394. discussion_id: Optional[str]
  1395. source: Optional[str]
  1396. comments: Optional[int]
  1397. submitted_at: Optional[datetime]
  1398. submitted_by: Optional[User]
  1399. def __init__(self, **kwargs) -> None:
  1400. paper = kwargs.pop("paper", {})
  1401. self.id = kwargs.pop("id", None) or paper.pop("id", None)
  1402. authors = paper.pop("authors", None) or kwargs.pop("authors", None)
  1403. self.authors = [author.pop("name", None) for author in authors] if authors else None
  1404. published_at = paper.pop("publishedAt", None) or kwargs.pop("publishedAt", None)
  1405. self.published_at = parse_datetime(published_at) if published_at else None
  1406. self.title = kwargs.pop("title", None)
  1407. self.source = kwargs.pop("source", None)
  1408. self.summary = paper.pop("summary", None) or kwargs.pop("summary", None)
  1409. self.upvotes = paper.pop("upvotes", None) or kwargs.pop("upvotes", None)
  1410. self.discussion_id = paper.pop("discussionId", None) or kwargs.pop("discussionId", None)
  1411. self.comments = kwargs.pop("numComments", 0)
  1412. submitted_at = kwargs.pop("publishedAt", None) or kwargs.pop("submittedOnDailyAt", None)
  1413. self.submitted_at = parse_datetime(submitted_at) if submitted_at else None
  1414. submitted_by = kwargs.pop("submittedBy", None) or kwargs.pop("submittedOnDailyBy", None)
  1415. self.submitted_by = User(**submitted_by) if submitted_by else None
  1416. # forward compatibility
  1417. self.__dict__.update(**kwargs)
  1418. @dataclass
  1419. class LFSFileInfo:
  1420. """
  1421. Contains information about a file stored as LFS on a repo on the Hub.
  1422. Used in the context of listing and permanently deleting LFS files from a repo to free-up space.
  1423. See [`list_lfs_files`] and [`permanently_delete_lfs_files`] for more details.
  1424. Git LFS files are tracked using SHA-256 object IDs, rather than file paths, to optimize performance
  1425. This approach is necessary because a single object can be referenced by multiple paths across different commits,
  1426. 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)
  1427. to learn how to know which filename(s) is(are) associated with each SHA.
  1428. Attributes:
  1429. file_oid (`str`):
  1430. SHA-256 object ID of the file. This is the identifier to pass when permanently deleting the file.
  1431. filename (`str`):
  1432. Possible filename for the LFS object. See the note above for more information.
  1433. oid (`str`):
  1434. OID of the LFS object.
  1435. pushed_at (`datetime`):
  1436. Date the LFS object was pushed to the repo.
  1437. ref (`str`, *optional*):
  1438. Ref where the LFS object has been pushed (if any).
  1439. size (`int`):
  1440. Size of the LFS object.
  1441. Example:
  1442. ```py
  1443. >>> from huggingface_hub import HfApi
  1444. >>> api = HfApi()
  1445. >>> lfs_files = api.list_lfs_files("username/my-cool-repo")
  1446. # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
  1447. # e.g. select only LFS files in the "checkpoints" folder
  1448. >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
  1449. # Permanently delete LFS files
  1450. >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
  1451. ```
  1452. """
  1453. file_oid: str
  1454. filename: str
  1455. oid: str
  1456. pushed_at: datetime
  1457. ref: Optional[str]
  1458. size: int
  1459. def __init__(self, **kwargs) -> None:
  1460. self.file_oid = kwargs.pop("fileOid")
  1461. self.filename = kwargs.pop("filename")
  1462. self.oid = kwargs.pop("oid")
  1463. self.pushed_at = parse_datetime(kwargs.pop("pushedAt"))
  1464. self.ref = kwargs.pop("ref", None)
  1465. self.size = kwargs.pop("size")
  1466. # forward compatibility
  1467. self.__dict__.update(**kwargs)
  1468. def future_compatible(fn: CallableT) -> CallableT:
  1469. """Wrap a method of `HfApi` to handle `run_as_future=True`.
  1470. A method flagged as "future_compatible" will be called in a thread if `run_as_future=True` and return a
  1471. `concurrent.futures.Future` instance. Otherwise, it will be called normally and return the result.
  1472. """
  1473. sig = inspect.signature(fn)
  1474. args_params = list(sig.parameters)[1:] # remove "self" from list
  1475. @wraps(fn)
  1476. def _inner(self, *args, **kwargs):
  1477. # Get `run_as_future` value if provided (default to False)
  1478. if "run_as_future" in kwargs:
  1479. run_as_future = kwargs["run_as_future"]
  1480. kwargs["run_as_future"] = False # avoid recursion error
  1481. else:
  1482. run_as_future = False
  1483. for param, value in zip(args_params, args):
  1484. if param == "run_as_future":
  1485. run_as_future = value
  1486. break
  1487. # Call the function in a thread if `run_as_future=True`
  1488. if run_as_future:
  1489. return self.run_as_future(fn, self, *args, **kwargs)
  1490. # Otherwise, call the function normally
  1491. return fn(self, *args, **kwargs)
  1492. _inner.is_future_compatible = True # type: ignore
  1493. return _inner # type: ignore
  1494. class HfApi:
  1495. """
  1496. Client to interact with the Hugging Face Hub via HTTP.
  1497. The client is initialized with some high-level settings used in all requests
  1498. made to the Hub (HF endpoint, authentication, user agents...). Using the `HfApi`
  1499. client is preferred but not mandatory as all of its public methods are exposed
  1500. directly at the root of `huggingface_hub`.
  1501. Args:
  1502. endpoint (`str`, *optional*):
  1503. Endpoint of the Hub. Defaults to <https://huggingface.co>.
  1504. token (`bool` or `str`, *optional*):
  1505. A valid user access token (string). Defaults to the locally saved
  1506. token, which is the recommended method for authentication (see
  1507. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  1508. To disable authentication, pass `False`.
  1509. library_name (`str`, *optional*):
  1510. The name of the library that is making the HTTP request. Will be added to
  1511. the user-agent header. Example: `"transformers"`.
  1512. library_version (`str`, *optional*):
  1513. The version of the library that is making the HTTP request. Will be added
  1514. to the user-agent header. Example: `"4.24.0"`.
  1515. user_agent (`str`, `dict`, *optional*):
  1516. The user agent info in the form of a dictionary or a single string. It will
  1517. be completed with information about the installed packages.
  1518. headers (`dict`, *optional*):
  1519. Additional headers to be sent with each request. Example: `{"X-My-Header": "value"}`.
  1520. Headers passed here are taking precedence over the default headers.
  1521. """
  1522. def __init__(
  1523. self,
  1524. endpoint: Optional[str] = None,
  1525. token: Union[str, bool, None] = None,
  1526. library_name: Optional[str] = None,
  1527. library_version: Optional[str] = None,
  1528. user_agent: Union[Dict, str, None] = None,
  1529. headers: Optional[Dict[str, str]] = None,
  1530. ) -> None:
  1531. self.endpoint = endpoint if endpoint is not None else constants.ENDPOINT
  1532. self.token = token
  1533. self.library_name = library_name
  1534. self.library_version = library_version
  1535. self.user_agent = user_agent
  1536. self.headers = headers
  1537. self._thread_pool: Optional[ThreadPoolExecutor] = None
  1538. def run_as_future(self, fn: Callable[..., R], *args, **kwargs) -> Future[R]:
  1539. """
  1540. Run a method in the background and return a Future instance.
  1541. The main goal is to run methods without blocking the main thread (e.g. to push data during a training).
  1542. Background jobs are queued to preserve order but are not ran in parallel. If you need to speed-up your scripts
  1543. 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).
  1544. Note: Most-used methods like [`upload_file`], [`upload_folder`] and [`create_commit`] have a `run_as_future: bool`
  1545. argument to directly call them in the background. This is equivalent to calling `api.run_as_future(...)` on them
  1546. but less verbose.
  1547. Args:
  1548. fn (`Callable`):
  1549. The method to run in the background.
  1550. *args, **kwargs:
  1551. Arguments with which the method will be called.
  1552. Return:
  1553. `Future`: a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) instance to
  1554. get the result of the task.
  1555. Example:
  1556. ```py
  1557. >>> from huggingface_hub import HfApi
  1558. >>> api = HfApi()
  1559. >>> future = api.run_as_future(api.whoami) # instant
  1560. >>> future.done()
  1561. False
  1562. >>> future.result() # wait until complete and return result
  1563. (...)
  1564. >>> future.done()
  1565. True
  1566. ```
  1567. """
  1568. if self._thread_pool is None:
  1569. self._thread_pool = ThreadPoolExecutor(max_workers=1)
  1570. self._thread_pool
  1571. return self._thread_pool.submit(fn, *args, **kwargs)
  1572. @validate_hf_hub_args
  1573. def whoami(self, token: Union[bool, str, None] = None) -> Dict:
  1574. """
  1575. Call HF API to know "whoami".
  1576. Args:
  1577. token (`bool` or `str`, *optional*):
  1578. A valid user access token (string). Defaults to the locally saved
  1579. token, which is the recommended method for authentication (see
  1580. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  1581. To disable authentication, pass `False`.
  1582. """
  1583. # Get the effective token using the helper function get_token
  1584. effective_token = token or self.token or get_token() or True
  1585. r = get_session().get(
  1586. f"{self.endpoint}/api/whoami-v2",
  1587. headers=self._build_hf_headers(token=effective_token),
  1588. )
  1589. try:
  1590. hf_raise_for_status(r)
  1591. except HTTPError as e:
  1592. if e.response.status_code == 401:
  1593. error_message = "Invalid user token."
  1594. # Check which token is the effective one and generate the error message accordingly
  1595. if effective_token == _get_token_from_google_colab():
  1596. error_message += " The token from Google Colab vault is invalid. Please update it from the UI."
  1597. elif effective_token == _get_token_from_environment():
  1598. error_message += (
  1599. " The token from HF_TOKEN environment variable is invalid. "
  1600. "Note that HF_TOKEN takes precedence over `hf auth login`."
  1601. )
  1602. elif effective_token == _get_token_from_file():
  1603. error_message += " The token stored is invalid. Please run `hf auth login` to update it."
  1604. raise HTTPError(error_message, request=e.request, response=e.response) from e
  1605. raise
  1606. return r.json()
  1607. @_deprecate_method(
  1608. version="1.0",
  1609. message=(
  1610. "Permissions are more complex than when `get_token_permission` was first introduced. "
  1611. "OAuth and fine-grain tokens allows for more detailed permissions. "
  1612. "If you need to know the permissions associated with a token, please use `whoami` and check the `'auth'` key."
  1613. ),
  1614. )
  1615. def get_token_permission(
  1616. self, token: Union[bool, str, None] = None
  1617. ) -> Literal["read", "write", "fineGrained", None]:
  1618. """
  1619. Check if a given `token` is valid and return its permissions.
  1620. > [!WARNING]
  1621. > This method is deprecated and will be removed in version 1.0. Permissions are more complex than when
  1622. > `get_token_permission` was first introduced. OAuth and fine-grain tokens allows for more detailed permissions.
  1623. > If you need to know the permissions associated with a token, please use `whoami` and check the `'auth'` key.
  1624. For more details about tokens, please refer to https://huggingface.co/docs/hub/security-tokens#what-are-user-access-tokens.
  1625. Args:
  1626. token (`bool` or `str`, *optional*):
  1627. A valid user access token (string). Defaults to the locally saved
  1628. token, which is the recommended method for authentication (see
  1629. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  1630. To disable authentication, pass `False`.
  1631. Returns:
  1632. `Literal["read", "write", "fineGrained", None]`: Permission granted by the token ("read" or "write"). Returns `None` if no
  1633. token passed, if token is invalid or if role is not returned by the server. This typically happens when the token is an OAuth token.
  1634. """
  1635. try:
  1636. return self.whoami(token=token)["auth"]["accessToken"]["role"]
  1637. except (LocalTokenNotFoundError, HTTPError, KeyError):
  1638. return None
  1639. def get_model_tags(self) -> Dict:
  1640. """
  1641. List all valid model tags as a nested namespace object
  1642. """
  1643. path = f"{self.endpoint}/api/models-tags-by-type"
  1644. r = get_session().get(path)
  1645. hf_raise_for_status(r)
  1646. return r.json()
  1647. def get_dataset_tags(self) -> Dict:
  1648. """
  1649. List all valid dataset tags as a nested namespace object.
  1650. """
  1651. path = f"{self.endpoint}/api/datasets-tags-by-type"
  1652. r = get_session().get(path)
  1653. hf_raise_for_status(r)
  1654. return r.json()
  1655. @_deprecate_arguments(
  1656. version="1.0", deprecated_args=["language", "library", "task", "tags"], custom_message="Use `filter` instead."
  1657. )
  1658. @validate_hf_hub_args
  1659. def list_models(
  1660. self,
  1661. *,
  1662. # Search-query parameter
  1663. filter: Union[str, Iterable[str], None] = None,
  1664. author: Optional[str] = None,
  1665. apps: Optional[Union[str, List[str]]] = None,
  1666. gated: Optional[bool] = None,
  1667. inference: Optional[Literal["warm"]] = None,
  1668. inference_provider: Optional[Union[Literal["all"], "PROVIDER_T", List["PROVIDER_T"]]] = None,
  1669. model_name: Optional[str] = None,
  1670. trained_dataset: Optional[Union[str, List[str]]] = None,
  1671. search: Optional[str] = None,
  1672. pipeline_tag: Optional[str] = None,
  1673. emissions_thresholds: Optional[Tuple[float, float]] = None,
  1674. # Sorting and pagination parameters
  1675. sort: Union[Literal["last_modified"], str, None] = None,
  1676. direction: Optional[Literal[-1]] = None,
  1677. limit: Optional[int] = None,
  1678. # Additional data to fetch
  1679. expand: Optional[List[ExpandModelProperty_T]] = None,
  1680. full: Optional[bool] = None,
  1681. cardData: bool = False,
  1682. fetch_config: bool = False,
  1683. token: Union[bool, str, None] = None,
  1684. # Deprecated arguments - use `filter` instead
  1685. language: Optional[Union[str, List[str]]] = None,
  1686. library: Optional[Union[str, List[str]]] = None,
  1687. tags: Optional[Union[str, List[str]]] = None,
  1688. task: Optional[Union[str, List[str]]] = None,
  1689. ) -> Iterable[ModelInfo]:
  1690. """
  1691. List models hosted on the Huggingface Hub, given some filters.
  1692. Args:
  1693. filter (`str` or `Iterable[str]`, *optional*):
  1694. A string or list of string to filter models on the Hub.
  1695. Models can be filtered by library, language, task, tags, and more.
  1696. author (`str`, *optional*):
  1697. A string which identify the author (user or organization) of the
  1698. returned models.
  1699. apps (`str` or `List`, *optional*):
  1700. A string or list of strings to filter models on the Hub that
  1701. support the specified apps. Example values include `"ollama"` or `["ollama", "vllm"]`.
  1702. gated (`bool`, *optional*):
  1703. A boolean to filter models on the Hub that are gated or not. By default, all models are returned.
  1704. If `gated=True` is passed, only gated models are returned.
  1705. If `gated=False` is passed, only non-gated models are returned.
  1706. inference (`Literal["warm"]`, *optional*):
  1707. If "warm", filter models on the Hub currently served by at least one provider.
  1708. inference_provider (`Literal["all"]` or `str`, *optional*):
  1709. A string to filter models on the Hub that are served by a specific provider.
  1710. Pass `"all"` to get all models served by at least one provider.
  1711. library (`str` or `List`, *optional*):
  1712. Deprecated. Pass a library name in `filter` to filter models by library.
  1713. language (`str` or `List`, *optional*):
  1714. Deprecated. Pass a language in `filter` to filter models by language.
  1715. model_name (`str`, *optional*):
  1716. A string that contain complete or partial names for models on the
  1717. Hub, such as "bert" or "bert-base-cased"
  1718. task (`str` or `List`, *optional*):
  1719. Deprecated. Pass a task in `filter` to filter models by task.
  1720. trained_dataset (`str` or `List`, *optional*):
  1721. A string tag or a list of string tags of the trained dataset for a
  1722. model on the Hub.
  1723. tags (`str` or `List`, *optional*):
  1724. Deprecated. Pass tags in `filter` to filter models by tags.
  1725. search (`str`, *optional*):
  1726. A string that will be contained in the returned model ids.
  1727. pipeline_tag (`str`, *optional*):
  1728. A string pipeline tag to filter models on the Hub by, such as `summarization`.
  1729. emissions_thresholds (`Tuple`, *optional*):
  1730. A tuple of two ints or floats representing a minimum and maximum
  1731. carbon footprint to filter the resulting models with in grams.
  1732. sort (`Literal["last_modified"]` or `str`, *optional*):
  1733. The key with which to sort the resulting models. Possible values are "last_modified", "trending_score",
  1734. "created_at", "downloads" and "likes".
  1735. direction (`Literal[-1]` or `int`, *optional*):
  1736. Direction in which to sort. The value `-1` sorts by descending
  1737. order while all other values sort by ascending order.
  1738. limit (`int`, *optional*):
  1739. The limit on the number of models fetched. Leaving this option
  1740. to `None` fetches all models.
  1741. expand (`List[ExpandModelProperty_T]`, *optional*):
  1742. List properties to return in the response. When used, only the properties in the list will be returned.
  1743. This parameter cannot be used if `full`, `cardData` or `fetch_config` are passed.
  1744. Possible values are `"author"`, `"cardData"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"gguf"`, `"inference"`, `"inferenceProviderMapping"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, `"resourceGroup"` and `"xetEnabled"`.
  1745. full (`bool`, *optional*):
  1746. Whether to fetch all model data, including the `last_modified`,
  1747. the `sha`, the files and the `tags`. This is set to `True` by
  1748. default when using a filter.
  1749. cardData (`bool`, *optional*):
  1750. Whether to grab the metadata for the model as well. Can contain
  1751. useful information such as carbon emissions, metrics, and
  1752. datasets trained on.
  1753. fetch_config (`bool`, *optional*):
  1754. Whether to fetch the model configs as well. This is not included
  1755. in `full` due to its size.
  1756. token (`bool` or `str`, *optional*):
  1757. A valid user access token (string). Defaults to the locally saved
  1758. token, which is the recommended method for authentication (see
  1759. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  1760. To disable authentication, pass `False`.
  1761. Returns:
  1762. `Iterable[ModelInfo]`: an iterable of [`huggingface_hub.hf_api.ModelInfo`] objects.
  1763. Example:
  1764. ```python
  1765. >>> from huggingface_hub import HfApi
  1766. >>> api = HfApi()
  1767. # List all models
  1768. >>> api.list_models()
  1769. # List text classification models
  1770. >>> api.list_models(filter="text-classification")
  1771. # List models from the KerasHub library
  1772. >>> api.list_models(filter="keras-hub")
  1773. # List models served by Cohere
  1774. >>> api.list_models(inference_provider="cohere")
  1775. # List models with "bert" in their name
  1776. >>> api.list_models(search="bert")
  1777. # List models with "bert" in their name and pushed by google
  1778. >>> api.list_models(search="bert", author="google")
  1779. ```
  1780. """
  1781. if expand and (full or cardData or fetch_config):
  1782. raise ValueError("`expand` cannot be used if `full`, `cardData` or `fetch_config` are passed.")
  1783. if emissions_thresholds is not None and not cardData:
  1784. raise ValueError("`emissions_thresholds` were passed without setting `cardData=True`.")
  1785. path = f"{self.endpoint}/api/models"
  1786. headers = self._build_hf_headers(token=token)
  1787. params: Dict[str, Any] = {}
  1788. # Build the filter list
  1789. filter_list: List[str] = []
  1790. if filter:
  1791. filter_list.extend([filter] if isinstance(filter, str) else filter)
  1792. if library:
  1793. filter_list.extend([library] if isinstance(library, str) else library)
  1794. if task:
  1795. filter_list.extend([task] if isinstance(task, str) else task)
  1796. if trained_dataset:
  1797. if isinstance(trained_dataset, str):
  1798. trained_dataset = [trained_dataset]
  1799. for dataset in trained_dataset:
  1800. if not dataset.startswith("dataset:"):
  1801. dataset = f"dataset:{dataset}"
  1802. filter_list.append(dataset)
  1803. if language:
  1804. filter_list.extend([language] if isinstance(language, str) else language)
  1805. if tags:
  1806. filter_list.extend([tags] if isinstance(tags, str) else tags)
  1807. if len(filter_list) > 0:
  1808. params["filter"] = filter_list
  1809. # Handle other query params
  1810. if author:
  1811. params["author"] = author
  1812. if apps:
  1813. if isinstance(apps, str):
  1814. apps = [apps]
  1815. params["apps"] = apps
  1816. if gated is not None:
  1817. params["gated"] = gated
  1818. if inference is not None:
  1819. params["inference"] = inference
  1820. if inference_provider is not None:
  1821. params["inference_provider"] = inference_provider
  1822. if pipeline_tag:
  1823. params["pipeline_tag"] = pipeline_tag
  1824. search_list = []
  1825. if model_name:
  1826. search_list.append(model_name)
  1827. if search:
  1828. search_list.append(search)
  1829. if len(search_list) > 0:
  1830. params["search"] = search_list
  1831. if sort is not None:
  1832. params["sort"] = (
  1833. "lastModified"
  1834. if sort == "last_modified"
  1835. else "trendingScore"
  1836. if sort == "trending_score"
  1837. else "createdAt"
  1838. if sort == "created_at"
  1839. else sort
  1840. )
  1841. if direction is not None:
  1842. params["direction"] = direction
  1843. if limit is not None:
  1844. params["limit"] = limit
  1845. # Request additional data
  1846. if full:
  1847. params["full"] = True
  1848. if fetch_config:
  1849. params["config"] = True
  1850. if cardData:
  1851. params["cardData"] = True
  1852. if expand:
  1853. params["expand"] = expand
  1854. # `items` is a generator
  1855. items = paginate(path, params=params, headers=headers)
  1856. if limit is not None:
  1857. items = islice(items, limit) # Do not iterate over all pages
  1858. for item in items:
  1859. if "siblings" not in item:
  1860. item["siblings"] = None
  1861. model_info = ModelInfo(**item)
  1862. if emissions_thresholds is None or _is_emission_within_threshold(model_info, *emissions_thresholds):
  1863. yield model_info
  1864. @_deprecate_arguments(version="1.0", deprecated_args=["tags"], custom_message="Use `filter` instead.")
  1865. @validate_hf_hub_args
  1866. def list_datasets(
  1867. self,
  1868. *,
  1869. # Search-query parameter
  1870. filter: Union[str, Iterable[str], None] = None,
  1871. author: Optional[str] = None,
  1872. benchmark: Optional[Union[str, List[str]]] = None,
  1873. dataset_name: Optional[str] = None,
  1874. gated: Optional[bool] = None,
  1875. language_creators: Optional[Union[str, List[str]]] = None,
  1876. language: Optional[Union[str, List[str]]] = None,
  1877. multilinguality: Optional[Union[str, List[str]]] = None,
  1878. size_categories: Optional[Union[str, List[str]]] = None,
  1879. task_categories: Optional[Union[str, List[str]]] = None,
  1880. task_ids: Optional[Union[str, List[str]]] = None,
  1881. search: Optional[str] = None,
  1882. # Sorting and pagination parameters
  1883. sort: Optional[Union[Literal["last_modified"], str]] = None,
  1884. direction: Optional[Literal[-1]] = None,
  1885. limit: Optional[int] = None,
  1886. # Additional data to fetch
  1887. expand: Optional[List[ExpandDatasetProperty_T]] = None,
  1888. full: Optional[bool] = None,
  1889. token: Union[bool, str, None] = None,
  1890. # Deprecated arguments - use `filter` instead
  1891. tags: Optional[Union[str, List[str]]] = None,
  1892. ) -> Iterable[DatasetInfo]:
  1893. """
  1894. List datasets hosted on the Huggingface Hub, given some filters.
  1895. Args:
  1896. filter (`str` or `Iterable[str]`, *optional*):
  1897. A string or list of string to filter datasets on the hub.
  1898. author (`str`, *optional*):
  1899. A string which identify the author of the returned datasets.
  1900. benchmark (`str` or `List`, *optional*):
  1901. A string or list of strings that can be used to identify datasets on
  1902. the Hub by their official benchmark.
  1903. dataset_name (`str`, *optional*):
  1904. A string or list of strings that can be used to identify datasets on
  1905. the Hub by its name, such as `SQAC` or `wikineural`
  1906. gated (`bool`, *optional*):
  1907. A boolean to filter datasets on the Hub that are gated or not. By default, all datasets are returned.
  1908. If `gated=True` is passed, only gated datasets are returned.
  1909. If `gated=False` is passed, only non-gated datasets are returned.
  1910. language_creators (`str` or `List`, *optional*):
  1911. A string or list of strings that can be used to identify datasets on
  1912. the Hub with how the data was curated, such as `crowdsourced` or
  1913. `machine_generated`.
  1914. language (`str` or `List`, *optional*):
  1915. A string or list of strings representing a two-character language to
  1916. filter datasets by on the Hub.
  1917. multilinguality (`str` or `List`, *optional*):
  1918. A string or list of strings representing a filter for datasets that
  1919. contain multiple languages.
  1920. size_categories (`str` or `List`, *optional*):
  1921. A string or list of strings that can be used to identify datasets on
  1922. the Hub by the size of the dataset such as `100K<n<1M` or
  1923. `1M<n<10M`.
  1924. tags (`str` or `List`, *optional*):
  1925. Deprecated. Pass tags in `filter` to filter datasets by tags.
  1926. task_categories (`str` or `List`, *optional*):
  1927. A string or list of strings that can be used to identify datasets on
  1928. the Hub by the designed task, such as `audio_classification` or
  1929. `named_entity_recognition`.
  1930. task_ids (`str` or `List`, *optional*):
  1931. A string or list of strings that can be used to identify datasets on
  1932. the Hub by the specific task such as `speech_emotion_recognition` or
  1933. `paraphrase`.
  1934. search (`str`, *optional*):
  1935. A string that will be contained in the returned datasets.
  1936. sort (`Literal["last_modified"]` or `str`, *optional*):
  1937. The key with which to sort the resulting models. Possible values are "last_modified", "trending_score",
  1938. "created_at", "downloads" and "likes".
  1939. direction (`Literal[-1]` or `int`, *optional*):
  1940. Direction in which to sort. The value `-1` sorts by descending
  1941. order while all other values sort by ascending order.
  1942. limit (`int`, *optional*):
  1943. The limit on the number of datasets fetched. Leaving this option
  1944. to `None` fetches all datasets.
  1945. expand (`List[ExpandDatasetProperty_T]`, *optional*):
  1946. List properties to return in the response. When used, only the properties in the list will be returned.
  1947. This parameter cannot be used if `full` is passed.
  1948. Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, `"resourceGroup"` and `"xetEnabled"`.
  1949. full (`bool`, *optional*):
  1950. Whether to fetch all dataset data, including the `last_modified`,
  1951. the `card_data` and the files. Can contain useful information such as the
  1952. PapersWithCode ID.
  1953. token (`bool` or `str`, *optional*):
  1954. A valid user access token (string). Defaults to the locally saved
  1955. token, which is the recommended method for authentication (see
  1956. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  1957. To disable authentication, pass `False`.
  1958. Returns:
  1959. `Iterable[DatasetInfo]`: an iterable of [`huggingface_hub.hf_api.DatasetInfo`] objects.
  1960. Example usage with the `filter` argument:
  1961. ```python
  1962. >>> from huggingface_hub import HfApi
  1963. >>> api = HfApi()
  1964. # List all datasets
  1965. >>> api.list_datasets()
  1966. # List only the text classification datasets
  1967. >>> api.list_datasets(filter="task_categories:text-classification")
  1968. # List only the datasets in russian for language modeling
  1969. >>> api.list_datasets(
  1970. ... filter=("language:ru", "task_ids:language-modeling")
  1971. ... )
  1972. # List FiftyOne datasets (identified by the tag "fiftyone" in dataset card)
  1973. >>> api.list_datasets(tags="fiftyone")
  1974. ```
  1975. Example usage with the `search` argument:
  1976. ```python
  1977. >>> from huggingface_hub import HfApi
  1978. >>> api = HfApi()
  1979. # List all datasets with "text" in their name
  1980. >>> api.list_datasets(search="text")
  1981. # List all datasets with "text" in their name made by google
  1982. >>> api.list_datasets(search="text", author="google")
  1983. ```
  1984. """
  1985. if expand and full:
  1986. raise ValueError("`expand` cannot be used if `full` is passed.")
  1987. path = f"{self.endpoint}/api/datasets"
  1988. headers = self._build_hf_headers(token=token)
  1989. params: Dict[str, Any] = {}
  1990. # Build `filter` list
  1991. filter_list = []
  1992. if filter is not None:
  1993. if isinstance(filter, str):
  1994. filter_list.append(filter)
  1995. else:
  1996. filter_list.extend(filter)
  1997. for key, value in (
  1998. ("benchmark", benchmark),
  1999. ("language_creators", language_creators),
  2000. ("language", language),
  2001. ("multilinguality", multilinguality),
  2002. ("size_categories", size_categories),
  2003. ("task_categories", task_categories),
  2004. ("task_ids", task_ids),
  2005. ):
  2006. if value:
  2007. if isinstance(value, str):
  2008. value = [value]
  2009. for value_item in value:
  2010. if not value_item.startswith(f"{key}:"):
  2011. data = f"{key}:{value_item}"
  2012. filter_list.append(data)
  2013. if tags is not None:
  2014. filter_list.extend([tags] if isinstance(tags, str) else tags)
  2015. if len(filter_list) > 0:
  2016. params["filter"] = filter_list
  2017. # Handle other query params
  2018. if author:
  2019. params["author"] = author
  2020. if gated is not None:
  2021. params["gated"] = gated
  2022. search_list = []
  2023. if dataset_name:
  2024. search_list.append(dataset_name)
  2025. if search:
  2026. search_list.append(search)
  2027. if len(search_list) > 0:
  2028. params["search"] = search_list
  2029. if sort is not None:
  2030. params["sort"] = (
  2031. "lastModified"
  2032. if sort == "last_modified"
  2033. else "trendingScore"
  2034. if sort == "trending_score"
  2035. else "createdAt"
  2036. if sort == "created_at"
  2037. else sort
  2038. )
  2039. if direction is not None:
  2040. params["direction"] = direction
  2041. if limit is not None:
  2042. params["limit"] = limit
  2043. # Request additional data
  2044. if expand:
  2045. params["expand"] = expand
  2046. if full:
  2047. params["full"] = True
  2048. items = paginate(path, params=params, headers=headers)
  2049. if limit is not None:
  2050. items = islice(items, limit) # Do not iterate over all pages
  2051. for item in items:
  2052. if "siblings" not in item:
  2053. item["siblings"] = None
  2054. yield DatasetInfo(**item)
  2055. @validate_hf_hub_args
  2056. def list_spaces(
  2057. self,
  2058. *,
  2059. # Search-query parameter
  2060. filter: Union[str, Iterable[str], None] = None,
  2061. author: Optional[str] = None,
  2062. search: Optional[str] = None,
  2063. datasets: Union[str, Iterable[str], None] = None,
  2064. models: Union[str, Iterable[str], None] = None,
  2065. linked: bool = False,
  2066. # Sorting and pagination parameters
  2067. sort: Union[Literal["last_modified"], str, None] = None,
  2068. direction: Optional[Literal[-1]] = None,
  2069. limit: Optional[int] = None,
  2070. # Additional data to fetch
  2071. expand: Optional[List[ExpandSpaceProperty_T]] = None,
  2072. full: Optional[bool] = None,
  2073. token: Union[bool, str, None] = None,
  2074. ) -> Iterable[SpaceInfo]:
  2075. """
  2076. List spaces hosted on the Huggingface Hub, given some filters.
  2077. Args:
  2078. filter (`str` or `Iterable`, *optional*):
  2079. A string tag or list of tags that can be used to identify Spaces on the Hub.
  2080. author (`str`, *optional*):
  2081. A string which identify the author of the returned Spaces.
  2082. search (`str`, *optional*):
  2083. A string that will be contained in the returned Spaces.
  2084. datasets (`str` or `Iterable`, *optional*):
  2085. Whether to return Spaces that make use of a dataset.
  2086. The name of a specific dataset can be passed as a string.
  2087. models (`str` or `Iterable`, *optional*):
  2088. Whether to return Spaces that make use of a model.
  2089. The name of a specific model can be passed as a string.
  2090. linked (`bool`, *optional*):
  2091. Whether to return Spaces that make use of either a model or a dataset.
  2092. sort (`Literal["last_modified"]` or `str`, *optional*):
  2093. The key with which to sort the resulting models. Possible values are "last_modified", "trending_score",
  2094. "created_at" and "likes".
  2095. direction (`Literal[-1]` or `int`, *optional*):
  2096. Direction in which to sort. The value `-1` sorts by descending
  2097. order while all other values sort by ascending order.
  2098. limit (`int`, *optional*):
  2099. The limit on the number of Spaces fetched. Leaving this option
  2100. to `None` fetches all Spaces.
  2101. expand (`List[ExpandSpaceProperty_T]`, *optional*):
  2102. List properties to return in the response. When used, only the properties in the list will be returned.
  2103. This parameter cannot be used if `full` is passed.
  2104. Possible values are `"author"`, `"cardData"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"createdAt"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, `"resourceGroup"` and `"xetEnabled"`.
  2105. full (`bool`, *optional*):
  2106. Whether to fetch all Spaces data, including the `last_modified`, `siblings`
  2107. and `card_data` fields.
  2108. token (`bool` or `str`, *optional*):
  2109. A valid user access token (string). Defaults to the locally saved
  2110. token, which is the recommended method for authentication (see
  2111. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2112. To disable authentication, pass `False`.
  2113. Returns:
  2114. `Iterable[SpaceInfo]`: an iterable of [`huggingface_hub.hf_api.SpaceInfo`] objects.
  2115. """
  2116. if expand and full:
  2117. raise ValueError("`expand` cannot be used if `full` is passed.")
  2118. path = f"{self.endpoint}/api/spaces"
  2119. headers = self._build_hf_headers(token=token)
  2120. params: Dict[str, Any] = {}
  2121. if filter is not None:
  2122. params["filter"] = filter
  2123. if author is not None:
  2124. params["author"] = author
  2125. if search is not None:
  2126. params["search"] = search
  2127. if sort is not None:
  2128. params["sort"] = (
  2129. "lastModified"
  2130. if sort == "last_modified"
  2131. else "trendingScore"
  2132. if sort == "trending_score"
  2133. else "createdAt"
  2134. if sort == "created_at"
  2135. else sort
  2136. )
  2137. if direction is not None:
  2138. params["direction"] = direction
  2139. if limit is not None:
  2140. params["limit"] = limit
  2141. if linked:
  2142. params["linked"] = True
  2143. if datasets is not None:
  2144. params["datasets"] = datasets
  2145. if models is not None:
  2146. params["models"] = models
  2147. # Request additional data
  2148. if expand:
  2149. params["expand"] = expand
  2150. if full:
  2151. params["full"] = True
  2152. items = paginate(path, params=params, headers=headers)
  2153. if limit is not None:
  2154. items = islice(items, limit) # Do not iterate over all pages
  2155. for item in items:
  2156. if "siblings" not in item:
  2157. item["siblings"] = None
  2158. yield SpaceInfo(**item)
  2159. @validate_hf_hub_args
  2160. def unlike(
  2161. self,
  2162. repo_id: str,
  2163. *,
  2164. token: Union[bool, str, None] = None,
  2165. repo_type: Optional[str] = None,
  2166. ) -> None:
  2167. """
  2168. Unlike a given repo on the Hub (e.g. remove from favorite list).
  2169. To prevent spam usage, it is not possible to `like` a repository from a script.
  2170. See also [`list_liked_repos`].
  2171. Args:
  2172. repo_id (`str`):
  2173. The repository to unlike. Example: `"user/my-cool-model"`.
  2174. token (`bool` or `str`, *optional*):
  2175. A valid user access token (string). Defaults to the locally saved
  2176. token, which is the recommended method for authentication (see
  2177. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2178. To disable authentication, pass `False`.
  2179. repo_type (`str`, *optional*):
  2180. Set to `"dataset"` or `"space"` if unliking a dataset or space, `None` or
  2181. `"model"` if unliking a model. Default is `None`.
  2182. Raises:
  2183. [`~utils.RepositoryNotFoundError`]:
  2184. If repository is not found (error 404): wrong repo_id/repo_type, private
  2185. but not authenticated or repo does not exist.
  2186. Example:
  2187. ```python
  2188. >>> from huggingface_hub import list_liked_repos, unlike
  2189. >>> "gpt2" in list_liked_repos().models # we assume you have already liked gpt2
  2190. True
  2191. >>> unlike("gpt2")
  2192. >>> "gpt2" in list_liked_repos().models
  2193. False
  2194. ```
  2195. """
  2196. if repo_type is None:
  2197. repo_type = constants.REPO_TYPE_MODEL
  2198. response = get_session().delete(
  2199. url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/like", headers=self._build_hf_headers(token=token)
  2200. )
  2201. hf_raise_for_status(response)
  2202. @validate_hf_hub_args
  2203. def list_liked_repos(
  2204. self,
  2205. user: Optional[str] = None,
  2206. *,
  2207. token: Union[bool, str, None] = None,
  2208. ) -> UserLikes:
  2209. """
  2210. List all public repos liked by a user on huggingface.co.
  2211. This list is public so token is optional. If `user` is not passed, it defaults to
  2212. the logged in user.
  2213. See also [`unlike`].
  2214. Args:
  2215. user (`str`, *optional*):
  2216. Name of the user for which you want to fetch the likes.
  2217. token (`bool` or `str`, *optional*):
  2218. A valid user access token (string). Defaults to the locally saved
  2219. token, which is the recommended method for authentication (see
  2220. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2221. To disable authentication, pass `False`.
  2222. Returns:
  2223. [`UserLikes`]: object containing the user name and 3 lists of repo ids (1 for
  2224. models, 1 for datasets and 1 for Spaces).
  2225. Raises:
  2226. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  2227. If `user` is not passed and no token found (either from argument or from machine).
  2228. Example:
  2229. ```python
  2230. >>> from huggingface_hub import list_liked_repos
  2231. >>> likes = list_liked_repos("julien-c")
  2232. >>> likes.user
  2233. "julien-c"
  2234. >>> likes.models
  2235. ["osanseviero/streamlit_1.15", "Xhaheen/ChatGPT_HF", ...]
  2236. ```
  2237. """
  2238. # User is either provided explicitly or retrieved from current token.
  2239. if user is None:
  2240. me = self.whoami(token=token)
  2241. if me["type"] == "user":
  2242. user = me["name"]
  2243. else:
  2244. raise ValueError(
  2245. "Cannot list liked repos. You must provide a 'user' as input or be logged in as a user."
  2246. )
  2247. path = f"{self.endpoint}/api/users/{user}/likes"
  2248. headers = self._build_hf_headers(token=token)
  2249. likes = list(paginate(path, params={}, headers=headers))
  2250. # Looping over a list of items similar to:
  2251. # {
  2252. # 'createdAt': '2021-09-09T21:53:27.000Z',
  2253. # 'repo': {
  2254. # 'name': 'PaddlePaddle/PaddleOCR',
  2255. # 'type': 'space'
  2256. # }
  2257. # }
  2258. # Let's loop 3 times over the received list. Less efficient but more straightforward to read.
  2259. return UserLikes(
  2260. user=user,
  2261. total=len(likes),
  2262. models=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "model"],
  2263. datasets=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "dataset"],
  2264. spaces=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "space"],
  2265. )
  2266. @validate_hf_hub_args
  2267. def list_repo_likers(
  2268. self,
  2269. repo_id: str,
  2270. *,
  2271. repo_type: Optional[str] = None,
  2272. token: Union[bool, str, None] = None,
  2273. ) -> Iterable[User]:
  2274. """
  2275. List all users who liked a given repo on the hugging Face Hub.
  2276. See also [`list_liked_repos`].
  2277. Args:
  2278. repo_id (`str`):
  2279. The repository to retrieve . Example: `"user/my-cool-model"`.
  2280. token (`bool` or `str`, *optional*):
  2281. A valid user access token (string). Defaults to the locally saved
  2282. token, which is the recommended method for authentication (see
  2283. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2284. To disable authentication, pass `False`.
  2285. repo_type (`str`, *optional*):
  2286. Set to `"dataset"` or `"space"` if uploading to a dataset or
  2287. space, `None` or `"model"` if uploading to a model. Default is
  2288. `None`.
  2289. Returns:
  2290. `Iterable[User]`: an iterable of [`huggingface_hub.hf_api.User`] objects.
  2291. """
  2292. # Construct the API endpoint
  2293. if repo_type is None:
  2294. repo_type = constants.REPO_TYPE_MODEL
  2295. path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/likers"
  2296. for liker in paginate(path, params={}, headers=self._build_hf_headers(token=token)):
  2297. yield User(username=liker["user"], fullname=liker["fullname"], avatar_url=liker["avatarUrl"])
  2298. @validate_hf_hub_args
  2299. def model_info(
  2300. self,
  2301. repo_id: str,
  2302. *,
  2303. revision: Optional[str] = None,
  2304. timeout: Optional[float] = None,
  2305. securityStatus: Optional[bool] = None,
  2306. files_metadata: bool = False,
  2307. expand: Optional[List[ExpandModelProperty_T]] = None,
  2308. token: Union[bool, str, None] = None,
  2309. ) -> ModelInfo:
  2310. """
  2311. Get info on one specific model on huggingface.co
  2312. Model can be private if you pass an acceptable token or are logged in.
  2313. Args:
  2314. repo_id (`str`):
  2315. A namespace (user or an organization) and a repo name separated
  2316. by a `/`.
  2317. revision (`str`, *optional*):
  2318. The revision of the model repository from which to get the
  2319. information.
  2320. timeout (`float`, *optional*):
  2321. Whether to set a timeout for the request to the Hub.
  2322. securityStatus (`bool`, *optional*):
  2323. Whether to retrieve the security status from the model
  2324. repository as well. The security status will be returned in the `security_repo_status` field.
  2325. files_metadata (`bool`, *optional*):
  2326. Whether or not to retrieve metadata for files in the repository
  2327. (size, LFS metadata, etc). Defaults to `False`.
  2328. expand (`List[ExpandModelProperty_T]`, *optional*):
  2329. List properties to return in the response. When used, only the properties in the list will be returned.
  2330. This parameter cannot be used if `securityStatus` or `files_metadata` are passed.
  2331. Possible values are `"author"`, `"baseModels"`, `"cardData"`, `"childrenModelCount"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"gguf"`, `"inference"`, `"inferenceProviderMapping"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, `"usedStorage"`, `"resourceGroup"` and `"xetEnabled"`.
  2332. token (`bool` or `str`, *optional*):
  2333. A valid user access token (string). Defaults to the locally saved
  2334. token, which is the recommended method for authentication (see
  2335. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2336. To disable authentication, pass `False`.
  2337. Returns:
  2338. [`huggingface_hub.hf_api.ModelInfo`]: The model repository information.
  2339. > [!TIP]
  2340. > Raises the following errors:
  2341. >
  2342. > - [`~utils.RepositoryNotFoundError`]
  2343. > If the repository to download from cannot be found. This may be because it doesn't exist,
  2344. > or because it is set to `private` and you do not have access.
  2345. > - [`~utils.RevisionNotFoundError`]
  2346. > If the revision to download from cannot be found.
  2347. """
  2348. if expand and (securityStatus or files_metadata):
  2349. raise ValueError("`expand` cannot be used if `securityStatus` or `files_metadata` are set.")
  2350. headers = self._build_hf_headers(token=token)
  2351. path = (
  2352. f"{self.endpoint}/api/models/{repo_id}"
  2353. if revision is None
  2354. else (f"{self.endpoint}/api/models/{repo_id}/revision/{quote(revision, safe='')}")
  2355. )
  2356. params: Dict = {}
  2357. if securityStatus:
  2358. params["securityStatus"] = True
  2359. if files_metadata:
  2360. params["blobs"] = True
  2361. if expand:
  2362. params["expand"] = expand
  2363. r = get_session().get(path, headers=headers, timeout=timeout, params=params)
  2364. hf_raise_for_status(r)
  2365. data = r.json()
  2366. return ModelInfo(**data)
  2367. @validate_hf_hub_args
  2368. def dataset_info(
  2369. self,
  2370. repo_id: str,
  2371. *,
  2372. revision: Optional[str] = None,
  2373. timeout: Optional[float] = None,
  2374. files_metadata: bool = False,
  2375. expand: Optional[List[ExpandDatasetProperty_T]] = None,
  2376. token: Union[bool, str, None] = None,
  2377. ) -> DatasetInfo:
  2378. """
  2379. Get info on one specific dataset on huggingface.co.
  2380. Dataset can be private if you pass an acceptable token.
  2381. Args:
  2382. repo_id (`str`):
  2383. A namespace (user or an organization) and a repo name separated
  2384. by a `/`.
  2385. revision (`str`, *optional*):
  2386. The revision of the dataset repository from which to get the
  2387. information.
  2388. timeout (`float`, *optional*):
  2389. Whether to set a timeout for the request to the Hub.
  2390. files_metadata (`bool`, *optional*):
  2391. Whether or not to retrieve metadata for files in the repository
  2392. (size, LFS metadata, etc). Defaults to `False`.
  2393. expand (`List[ExpandDatasetProperty_T]`, *optional*):
  2394. List properties to return in the response. When used, only the properties in the list will be returned.
  2395. This parameter cannot be used if `files_metadata` is passed.
  2396. Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`,`"usedStorage"`, `"resourceGroup"` and `"xetEnabled"`.
  2397. token (`bool` or `str`, *optional*):
  2398. A valid user access token (string). Defaults to the locally saved
  2399. token, which is the recommended method for authentication (see
  2400. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2401. To disable authentication, pass `False`.
  2402. Returns:
  2403. [`hf_api.DatasetInfo`]: The dataset repository information.
  2404. > [!TIP]
  2405. > Raises the following errors:
  2406. >
  2407. > - [`~utils.RepositoryNotFoundError`]
  2408. > If the repository to download from cannot be found. This may be because it doesn't exist,
  2409. > or because it is set to `private` and you do not have access.
  2410. > - [`~utils.RevisionNotFoundError`]
  2411. > If the revision to download from cannot be found.
  2412. """
  2413. if expand and files_metadata:
  2414. raise ValueError("`expand` cannot be used if `files_metadata` is set.")
  2415. headers = self._build_hf_headers(token=token)
  2416. path = (
  2417. f"{self.endpoint}/api/datasets/{repo_id}"
  2418. if revision is None
  2419. else (f"{self.endpoint}/api/datasets/{repo_id}/revision/{quote(revision, safe='')}")
  2420. )
  2421. params: Dict = {}
  2422. if files_metadata:
  2423. params["blobs"] = True
  2424. if expand:
  2425. params["expand"] = expand
  2426. r = get_session().get(path, headers=headers, timeout=timeout, params=params)
  2427. hf_raise_for_status(r)
  2428. data = r.json()
  2429. return DatasetInfo(**data)
  2430. @validate_hf_hub_args
  2431. def space_info(
  2432. self,
  2433. repo_id: str,
  2434. *,
  2435. revision: Optional[str] = None,
  2436. timeout: Optional[float] = None,
  2437. files_metadata: bool = False,
  2438. expand: Optional[List[ExpandSpaceProperty_T]] = None,
  2439. token: Union[bool, str, None] = None,
  2440. ) -> SpaceInfo:
  2441. """
  2442. Get info on one specific Space on huggingface.co.
  2443. Space can be private if you pass an acceptable token.
  2444. Args:
  2445. repo_id (`str`):
  2446. A namespace (user or an organization) and a repo name separated
  2447. by a `/`.
  2448. revision (`str`, *optional*):
  2449. The revision of the space repository from which to get the
  2450. information.
  2451. timeout (`float`, *optional*):
  2452. Whether to set a timeout for the request to the Hub.
  2453. files_metadata (`bool`, *optional*):
  2454. Whether or not to retrieve metadata for files in the repository
  2455. (size, LFS metadata, etc). Defaults to `False`.
  2456. expand (`List[ExpandSpaceProperty_T]`, *optional*):
  2457. List properties to return in the response. When used, only the properties in the list will be returned.
  2458. This parameter cannot be used if `full` is passed.
  2459. Possible values are `"author"`, `"cardData"`, `"createdAt"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, `"resourceGroup"` and `"xetEnabled"`.
  2460. token (`bool` or `str`, *optional*):
  2461. A valid user access token (string). Defaults to the locally saved
  2462. token, which is the recommended method for authentication (see
  2463. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2464. To disable authentication, pass `False`.
  2465. Returns:
  2466. [`~hf_api.SpaceInfo`]: The space repository information.
  2467. > [!TIP]
  2468. > Raises the following errors:
  2469. >
  2470. > - [`~utils.RepositoryNotFoundError`]
  2471. > If the repository to download from cannot be found. This may be because it doesn't exist,
  2472. > or because it is set to `private` and you do not have access.
  2473. > - [`~utils.RevisionNotFoundError`]
  2474. > If the revision to download from cannot be found.
  2475. """
  2476. if expand and files_metadata:
  2477. raise ValueError("`expand` cannot be used if `files_metadata` is set.")
  2478. headers = self._build_hf_headers(token=token)
  2479. path = (
  2480. f"{self.endpoint}/api/spaces/{repo_id}"
  2481. if revision is None
  2482. else (f"{self.endpoint}/api/spaces/{repo_id}/revision/{quote(revision, safe='')}")
  2483. )
  2484. params: Dict = {}
  2485. if files_metadata:
  2486. params["blobs"] = True
  2487. if expand:
  2488. params["expand"] = expand
  2489. r = get_session().get(path, headers=headers, timeout=timeout, params=params)
  2490. hf_raise_for_status(r)
  2491. data = r.json()
  2492. return SpaceInfo(**data)
  2493. @validate_hf_hub_args
  2494. def repo_info(
  2495. self,
  2496. repo_id: str,
  2497. *,
  2498. revision: Optional[str] = None,
  2499. repo_type: Optional[str] = None,
  2500. timeout: Optional[float] = None,
  2501. files_metadata: bool = False,
  2502. expand: Optional[Union[ExpandModelProperty_T, ExpandDatasetProperty_T, ExpandSpaceProperty_T]] = None,
  2503. token: Union[bool, str, None] = None,
  2504. ) -> Union[ModelInfo, DatasetInfo, SpaceInfo]:
  2505. """
  2506. Get the info object for a given repo of a given type.
  2507. Args:
  2508. repo_id (`str`):
  2509. A namespace (user or an organization) and a repo name separated
  2510. by a `/`.
  2511. revision (`str`, *optional*):
  2512. The revision of the repository from which to get the
  2513. information.
  2514. repo_type (`str`, *optional*):
  2515. Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
  2516. `None` or `"model"` if getting repository info from a model. Default is `None`.
  2517. timeout (`float`, *optional*):
  2518. Whether to set a timeout for the request to the Hub.
  2519. expand (`ExpandModelProperty_T` or `ExpandDatasetProperty_T` or `ExpandSpaceProperty_T`, *optional*):
  2520. List properties to return in the response. When used, only the properties in the list will be returned.
  2521. This parameter cannot be used if `files_metadata` is passed.
  2522. For an exhaustive list of available properties, check out [`model_info`], [`dataset_info`] or [`space_info`].
  2523. files_metadata (`bool`, *optional*):
  2524. Whether or not to retrieve metadata for files in the repository
  2525. (size, LFS metadata, etc). Defaults to `False`.
  2526. token (`bool` or `str`, *optional*):
  2527. A valid user access token (string). Defaults to the locally saved
  2528. token, which is the recommended method for authentication (see
  2529. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2530. To disable authentication, pass `False`.
  2531. Returns:
  2532. `Union[SpaceInfo, DatasetInfo, ModelInfo]`: The repository information, as a
  2533. [`huggingface_hub.hf_api.DatasetInfo`], [`huggingface_hub.hf_api.ModelInfo`]
  2534. or [`huggingface_hub.hf_api.SpaceInfo`] object.
  2535. > [!TIP]
  2536. > Raises the following errors:
  2537. >
  2538. > - [`~utils.RepositoryNotFoundError`]
  2539. > If the repository to download from cannot be found. This may be because it doesn't exist,
  2540. > or because it is set to `private` and you do not have access.
  2541. > - [`~utils.RevisionNotFoundError`]
  2542. > If the revision to download from cannot be found.
  2543. """
  2544. if repo_type is None or repo_type == "model":
  2545. method = self.model_info
  2546. elif repo_type == "dataset":
  2547. method = self.dataset_info # type: ignore
  2548. elif repo_type == "space":
  2549. method = self.space_info # type: ignore
  2550. else:
  2551. raise ValueError("Unsupported repo type.")
  2552. return method(
  2553. repo_id,
  2554. revision=revision,
  2555. token=token,
  2556. timeout=timeout,
  2557. expand=expand, # type: ignore[arg-type]
  2558. files_metadata=files_metadata,
  2559. )
  2560. @validate_hf_hub_args
  2561. def repo_exists(
  2562. self,
  2563. repo_id: str,
  2564. *,
  2565. repo_type: Optional[str] = None,
  2566. token: Union[str, bool, None] = None,
  2567. ) -> bool:
  2568. """
  2569. Checks if a repository exists on the Hugging Face Hub.
  2570. Args:
  2571. repo_id (`str`):
  2572. A namespace (user or an organization) and a repo name separated
  2573. by a `/`.
  2574. repo_type (`str`, *optional*):
  2575. Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
  2576. `None` or `"model"` if getting repository info from a model. Default is `None`.
  2577. token (`bool` or `str`, *optional*):
  2578. A valid user access token (string). Defaults to the locally saved
  2579. token, which is the recommended method for authentication (see
  2580. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2581. To disable authentication, pass `False`.
  2582. Returns:
  2583. True if the repository exists, False otherwise.
  2584. Examples:
  2585. ```py
  2586. >>> from huggingface_hub import repo_exists
  2587. >>> repo_exists("google/gemma-7b")
  2588. True
  2589. >>> repo_exists("google/not-a-repo")
  2590. False
  2591. ```
  2592. """
  2593. try:
  2594. self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token)
  2595. return True
  2596. except GatedRepoError:
  2597. return True # we don't have access but it exists
  2598. except RepositoryNotFoundError:
  2599. return False
  2600. @validate_hf_hub_args
  2601. def revision_exists(
  2602. self,
  2603. repo_id: str,
  2604. revision: str,
  2605. *,
  2606. repo_type: Optional[str] = None,
  2607. token: Union[str, bool, None] = None,
  2608. ) -> bool:
  2609. """
  2610. Checks if a specific revision exists on a repo on the Hugging Face Hub.
  2611. Args:
  2612. repo_id (`str`):
  2613. A namespace (user or an organization) and a repo name separated
  2614. by a `/`.
  2615. revision (`str`):
  2616. The revision of the repository to check.
  2617. repo_type (`str`, *optional*):
  2618. Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
  2619. `None` or `"model"` if getting repository info from a model. Default is `None`.
  2620. token (`bool` or `str`, *optional*):
  2621. A valid user access token (string). Defaults to the locally saved
  2622. token, which is the recommended method for authentication (see
  2623. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2624. To disable authentication, pass `False`.
  2625. Returns:
  2626. True if the repository and the revision exists, False otherwise.
  2627. Examples:
  2628. ```py
  2629. >>> from huggingface_hub import revision_exists
  2630. >>> revision_exists("google/gemma-7b", "float16")
  2631. True
  2632. >>> revision_exists("google/gemma-7b", "not-a-revision")
  2633. False
  2634. ```
  2635. """
  2636. try:
  2637. self.repo_info(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token)
  2638. return True
  2639. except RevisionNotFoundError:
  2640. return False
  2641. except RepositoryNotFoundError:
  2642. return False
  2643. @validate_hf_hub_args
  2644. def file_exists(
  2645. self,
  2646. repo_id: str,
  2647. filename: str,
  2648. *,
  2649. repo_type: Optional[str] = None,
  2650. revision: Optional[str] = None,
  2651. token: Union[str, bool, None] = None,
  2652. ) -> bool:
  2653. """
  2654. Checks if a file exists in a repository on the Hugging Face Hub.
  2655. Args:
  2656. repo_id (`str`):
  2657. A namespace (user or an organization) and a repo name separated
  2658. by a `/`.
  2659. filename (`str`):
  2660. The name of the file to check, for example:
  2661. `"config.json"`
  2662. repo_type (`str`, *optional*):
  2663. Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
  2664. `None` or `"model"` if getting repository info from a model. Default is `None`.
  2665. revision (`str`, *optional*):
  2666. The revision of the repository from which to get the information. Defaults to `"main"` branch.
  2667. token (`bool` or `str`, *optional*):
  2668. A valid user access token (string). Defaults to the locally saved
  2669. token, which is the recommended method for authentication (see
  2670. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2671. To disable authentication, pass `False`.
  2672. Returns:
  2673. True if the file exists, False otherwise.
  2674. Examples:
  2675. ```py
  2676. >>> from huggingface_hub import file_exists
  2677. >>> file_exists("bigcode/starcoder", "config.json")
  2678. True
  2679. >>> file_exists("bigcode/starcoder", "not-a-file")
  2680. False
  2681. >>> file_exists("bigcode/not-a-repo", "config.json")
  2682. False
  2683. ```
  2684. """
  2685. url = hf_hub_url(
  2686. repo_id=repo_id, repo_type=repo_type, revision=revision, filename=filename, endpoint=self.endpoint
  2687. )
  2688. try:
  2689. if token is None:
  2690. token = self.token
  2691. get_hf_file_metadata(url, token=token)
  2692. return True
  2693. except GatedRepoError: # raise specifically on gated repo
  2694. raise
  2695. except (RepositoryNotFoundError, EntryNotFoundError, RevisionNotFoundError):
  2696. return False
  2697. @validate_hf_hub_args
  2698. def list_repo_files(
  2699. self,
  2700. repo_id: str,
  2701. *,
  2702. revision: Optional[str] = None,
  2703. repo_type: Optional[str] = None,
  2704. token: Union[str, bool, None] = None,
  2705. ) -> List[str]:
  2706. """
  2707. Get the list of files in a given repo.
  2708. Args:
  2709. repo_id (`str`):
  2710. A namespace (user or an organization) and a repo name separated by a `/`.
  2711. revision (`str`, *optional*):
  2712. The revision of the repository from which to get the information.
  2713. repo_type (`str`, *optional*):
  2714. Set to `"dataset"` or `"space"` if uploading to a dataset or space, `None` or `"model"` if uploading to
  2715. a model. Default is `None`.
  2716. token (`bool` or `str`, *optional*):
  2717. A valid user access token (string). Defaults to the locally saved
  2718. token, which is the recommended method for authentication (see
  2719. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2720. To disable authentication, pass `False`.
  2721. Returns:
  2722. `List[str]`: the list of files in a given repository.
  2723. """
  2724. return [
  2725. f.rfilename
  2726. for f in self.list_repo_tree(
  2727. repo_id=repo_id, recursive=True, revision=revision, repo_type=repo_type, token=token
  2728. )
  2729. if isinstance(f, RepoFile)
  2730. ]
  2731. @validate_hf_hub_args
  2732. def list_repo_tree(
  2733. self,
  2734. repo_id: str,
  2735. path_in_repo: Optional[str] = None,
  2736. *,
  2737. recursive: bool = False,
  2738. expand: bool = False,
  2739. revision: Optional[str] = None,
  2740. repo_type: Optional[str] = None,
  2741. token: Union[str, bool, None] = None,
  2742. ) -> Iterable[Union[RepoFile, RepoFolder]]:
  2743. """
  2744. List a repo tree's files and folders and get information about them.
  2745. Args:
  2746. repo_id (`str`):
  2747. A namespace (user or an organization) and a repo name separated by a `/`.
  2748. path_in_repo (`str`, *optional*):
  2749. Relative path of the tree (folder) in the repo, for example:
  2750. `"checkpoints/1fec34a/results"`. Will default to the root tree (folder) of the repository.
  2751. recursive (`bool`, *optional*, defaults to `False`):
  2752. Whether to list tree's files and folders recursively.
  2753. expand (`bool`, *optional*, defaults to `False`):
  2754. Whether to fetch more information about the tree's files and folders (e.g. last commit and files' security scan results). This
  2755. operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
  2756. As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
  2757. takes to get the results.
  2758. revision (`str`, *optional*):
  2759. The revision of the repository from which to get the tree. Defaults to `"main"` branch.
  2760. repo_type (`str`, *optional*):
  2761. The type of the repository from which to get the tree (`"model"`, `"dataset"` or `"space"`.
  2762. Defaults to `"model"`.
  2763. token (`bool` or `str`, *optional*):
  2764. A valid user access token (string). Defaults to the locally saved
  2765. token, which is the recommended method for authentication (see
  2766. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2767. To disable authentication, pass `False`.
  2768. Returns:
  2769. `Iterable[Union[RepoFile, RepoFolder]]`:
  2770. 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
  2771. not guaranteed.
  2772. Raises:
  2773. [`~utils.RepositoryNotFoundError`]:
  2774. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  2775. does not exist.
  2776. [`~utils.RevisionNotFoundError`]:
  2777. If revision is not found (error 404) on the repo.
  2778. [`~utils.EntryNotFoundError`]:
  2779. If the tree (folder) does not exist (error 404) on the repo.
  2780. Examples:
  2781. Get information about a repo's tree.
  2782. ```py
  2783. >>> from huggingface_hub import list_repo_tree
  2784. >>> repo_tree = list_repo_tree("lysandre/arxiv-nlp")
  2785. >>> repo_tree
  2786. <generator object HfApi.list_repo_tree at 0x7fa4088e1ac0>
  2787. >>> list(repo_tree)
  2788. [
  2789. RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None),
  2790. RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None),
  2791. RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None),
  2792. RepoFile(
  2793. path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e',
  2794. lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None
  2795. ),
  2796. RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None),
  2797. RepoFile(
  2798. path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523',
  2799. lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None
  2800. ),
  2801. RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)]
  2802. ]
  2803. ```
  2804. Get even more information about a repo's tree (last commit and files' security scan results)
  2805. ```py
  2806. >>> from huggingface_hub import list_repo_tree
  2807. >>> repo_tree = list_repo_tree("prompthero/openjourney-v4", expand=True)
  2808. >>> list(repo_tree)
  2809. [
  2810. RepoFolder(
  2811. path='feature_extractor',
  2812. tree_id='aa536c4ea18073388b5b0bc791057a7296a00398',
  2813. last_commit={
  2814. 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
  2815. 'title': 'Upload diffusers weights (#48)',
  2816. 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
  2817. }
  2818. ),
  2819. RepoFolder(
  2820. path='safety_checker',
  2821. tree_id='65aef9d787e5557373fdf714d6c34d4fcdd70440',
  2822. last_commit={
  2823. 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
  2824. 'title': 'Upload diffusers weights (#48)',
  2825. 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
  2826. }
  2827. ),
  2828. RepoFile(
  2829. path='model_index.json',
  2830. size=582,
  2831. blob_id='d3d7c1e8c3e78eeb1640b8e2041ee256e24c9ee1',
  2832. lfs=None,
  2833. last_commit={
  2834. 'oid': 'b195ed2d503f3eb29637050a886d77bd81d35f0e',
  2835. 'title': 'Fix deprecation warning by changing `CLIPFeatureExtractor` to `CLIPImageProcessor`. (#54)',
  2836. 'date': datetime.datetime(2023, 5, 15, 21, 41, 59, tzinfo=datetime.timezone.utc)
  2837. },
  2838. security={
  2839. 'safe': True,
  2840. 'av_scan': {'virusFound': False, 'virusNames': None},
  2841. 'pickle_import_scan': None
  2842. }
  2843. )
  2844. ...
  2845. ]
  2846. ```
  2847. """
  2848. repo_type = repo_type or constants.REPO_TYPE_MODEL
  2849. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  2850. headers = self._build_hf_headers(token=token)
  2851. encoded_path_in_repo = "/" + quote(path_in_repo, safe="") if path_in_repo else ""
  2852. tree_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tree/{revision}{encoded_path_in_repo}"
  2853. for path_info in paginate(path=tree_url, headers=headers, params={"recursive": recursive, "expand": expand}):
  2854. yield (RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info))
  2855. @validate_hf_hub_args
  2856. def list_repo_refs(
  2857. self,
  2858. repo_id: str,
  2859. *,
  2860. repo_type: Optional[str] = None,
  2861. include_pull_requests: bool = False,
  2862. token: Union[str, bool, None] = None,
  2863. ) -> GitRefs:
  2864. """
  2865. Get the list of refs of a given repo (both tags and branches).
  2866. Args:
  2867. repo_id (`str`):
  2868. A namespace (user or an organization) and a repo name separated
  2869. by a `/`.
  2870. repo_type (`str`, *optional*):
  2871. Set to `"dataset"` or `"space"` if listing refs from a dataset or a Space,
  2872. `None` or `"model"` if listing from a model. Default is `None`.
  2873. include_pull_requests (`bool`, *optional*):
  2874. Whether to include refs from pull requests in the list. Defaults to `False`.
  2875. token (`bool` or `str`, *optional*):
  2876. A valid user access token (string). Defaults to the locally saved
  2877. token, which is the recommended method for authentication (see
  2878. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2879. To disable authentication, pass `False`.
  2880. Example:
  2881. ```py
  2882. >>> from huggingface_hub import HfApi
  2883. >>> api = HfApi()
  2884. >>> api.list_repo_refs("gpt2")
  2885. GitRefs(branches=[GitRefInfo(name='main', ref='refs/heads/main', target_commit='e7da7f221d5bf496a48136c0cd264e630fe9fcc8')], converts=[], tags=[])
  2886. >>> api.list_repo_refs("bigcode/the-stack", repo_type='dataset')
  2887. GitRefs(
  2888. branches=[
  2889. GitRefInfo(name='main', ref='refs/heads/main', target_commit='18edc1591d9ce72aa82f56c4431b3c969b210ae3'),
  2890. GitRefInfo(name='v1.1.a1', ref='refs/heads/v1.1.a1', target_commit='f9826b862d1567f3822d3d25649b0d6d22ace714')
  2891. ],
  2892. converts=[],
  2893. tags=[
  2894. GitRefInfo(name='v1.0', ref='refs/tags/v1.0', target_commit='c37a8cd1e382064d8aced5e05543c5f7753834da')
  2895. ]
  2896. )
  2897. ```
  2898. Returns:
  2899. [`GitRefs`]: object containing all information about branches and tags for a
  2900. repo on the Hub.
  2901. """
  2902. repo_type = repo_type or constants.REPO_TYPE_MODEL
  2903. response = get_session().get(
  2904. f"{self.endpoint}/api/{repo_type}s/{repo_id}/refs",
  2905. headers=self._build_hf_headers(token=token),
  2906. params={"include_prs": 1} if include_pull_requests else {},
  2907. )
  2908. hf_raise_for_status(response)
  2909. data = response.json()
  2910. def _format_as_git_ref_info(item: Dict) -> GitRefInfo:
  2911. return GitRefInfo(name=item["name"], ref=item["ref"], target_commit=item["targetCommit"])
  2912. return GitRefs(
  2913. branches=[_format_as_git_ref_info(item) for item in data["branches"]],
  2914. converts=[_format_as_git_ref_info(item) for item in data["converts"]],
  2915. tags=[_format_as_git_ref_info(item) for item in data["tags"]],
  2916. pull_requests=[_format_as_git_ref_info(item) for item in data["pullRequests"]]
  2917. if include_pull_requests
  2918. else None,
  2919. )
  2920. @validate_hf_hub_args
  2921. def list_repo_commits(
  2922. self,
  2923. repo_id: str,
  2924. *,
  2925. repo_type: Optional[str] = None,
  2926. token: Union[bool, str, None] = None,
  2927. revision: Optional[str] = None,
  2928. formatted: bool = False,
  2929. ) -> List[GitCommitInfo]:
  2930. """
  2931. Get the list of commits of a given revision for a repo on the Hub.
  2932. Commits are sorted by date (last commit first).
  2933. Args:
  2934. repo_id (`str`):
  2935. A namespace (user or an organization) and a repo name separated by a `/`.
  2936. repo_type (`str`, *optional*):
  2937. Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
  2938. listing from a model. Default is `None`.
  2939. token (`bool` or `str`, *optional*):
  2940. A valid user access token (string). Defaults to the locally saved
  2941. token, which is the recommended method for authentication (see
  2942. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  2943. To disable authentication, pass `False`.
  2944. revision (`str`, *optional*):
  2945. The git revision to commit from. Defaults to the head of the `"main"` branch.
  2946. formatted (`bool`):
  2947. Whether to return the HTML-formatted title and description of the commits. Defaults to False.
  2948. Example:
  2949. ```py
  2950. >>> from huggingface_hub import HfApi
  2951. >>> api = HfApi()
  2952. # Commits are sorted by date (last commit first)
  2953. >>> initial_commit = api.list_repo_commits("gpt2")[-1]
  2954. # Initial commit is always a system commit containing the `.gitattributes` file.
  2955. >>> initial_commit
  2956. GitCommitInfo(
  2957. commit_id='9b865efde13a30c13e0a33e536cf3e4a5a9d71d8',
  2958. authors=['system'],
  2959. created_at=datetime.datetime(2019, 2, 18, 10, 36, 15, tzinfo=datetime.timezone.utc),
  2960. title='initial commit',
  2961. message='',
  2962. formatted_title=None,
  2963. formatted_message=None
  2964. )
  2965. # Create an empty branch by deriving from initial commit
  2966. >>> api.create_branch("gpt2", "new_empty_branch", revision=initial_commit.commit_id)
  2967. ```
  2968. Returns:
  2969. List[[`GitCommitInfo`]]: list of objects containing information about the commits for a repo on the Hub.
  2970. Raises:
  2971. [`~utils.RepositoryNotFoundError`]:
  2972. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  2973. does not exist.
  2974. [`~utils.RevisionNotFoundError`]:
  2975. If revision is not found (error 404) on the repo.
  2976. """
  2977. repo_type = repo_type or constants.REPO_TYPE_MODEL
  2978. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  2979. # Paginate over results and return the list of commits.
  2980. return [
  2981. GitCommitInfo(
  2982. commit_id=item["id"],
  2983. authors=[author["user"] for author in item["authors"]],
  2984. created_at=parse_datetime(item["date"]),
  2985. title=item["title"],
  2986. message=item["message"],
  2987. formatted_title=item.get("formatted", {}).get("title"),
  2988. formatted_message=item.get("formatted", {}).get("message"),
  2989. )
  2990. for item in paginate(
  2991. f"{self.endpoint}/api/{repo_type}s/{repo_id}/commits/{revision}",
  2992. headers=self._build_hf_headers(token=token),
  2993. params={"expand[]": "formatted"} if formatted else {},
  2994. )
  2995. ]
  2996. @validate_hf_hub_args
  2997. def get_paths_info(
  2998. self,
  2999. repo_id: str,
  3000. paths: Union[List[str], str],
  3001. *,
  3002. expand: bool = False,
  3003. revision: Optional[str] = None,
  3004. repo_type: Optional[str] = None,
  3005. token: Union[str, bool, None] = None,
  3006. ) -> List[Union[RepoFile, RepoFolder]]:
  3007. """
  3008. Get information about a repo's paths.
  3009. Args:
  3010. repo_id (`str`):
  3011. A namespace (user or an organization) and a repo name separated by a `/`.
  3012. paths (`Union[List[str], str]`, *optional*):
  3013. The paths to get information about. If a path do not exist, it is ignored without raising
  3014. an exception.
  3015. expand (`bool`, *optional*, defaults to `False`):
  3016. Whether to fetch more information about the paths (e.g. last commit and files' security scan results). This
  3017. operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
  3018. As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
  3019. takes to get the results.
  3020. revision (`str`, *optional*):
  3021. The revision of the repository from which to get the information. Defaults to `"main"` branch.
  3022. repo_type (`str`, *optional*):
  3023. The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`.
  3024. Defaults to `"model"`.
  3025. token (`bool` or `str`, *optional*):
  3026. A valid user access token (string). Defaults to the locally saved
  3027. token, which is the recommended method for authentication (see
  3028. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3029. To disable authentication, pass `False`.
  3030. Returns:
  3031. `List[Union[RepoFile, RepoFolder]]`:
  3032. The information about the paths, as a list of [`RepoFile`] and [`RepoFolder`] objects.
  3033. Raises:
  3034. [`~utils.RepositoryNotFoundError`]:
  3035. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  3036. does not exist.
  3037. [`~utils.RevisionNotFoundError`]:
  3038. If revision is not found (error 404) on the repo.
  3039. Example:
  3040. ```py
  3041. >>> from huggingface_hub import get_paths_info
  3042. >>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset")
  3043. >>> paths_info
  3044. [
  3045. RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None),
  3046. RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None)
  3047. ]
  3048. ```
  3049. """
  3050. repo_type = repo_type or constants.REPO_TYPE_MODEL
  3051. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  3052. headers = self._build_hf_headers(token=token)
  3053. response = get_session().post(
  3054. f"{self.endpoint}/api/{repo_type}s/{repo_id}/paths-info/{revision}",
  3055. data={
  3056. "paths": paths if isinstance(paths, list) else [paths],
  3057. "expand": expand,
  3058. },
  3059. headers=headers,
  3060. )
  3061. hf_raise_for_status(response)
  3062. paths_info = response.json()
  3063. return [
  3064. RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info)
  3065. for path_info in paths_info
  3066. ]
  3067. @validate_hf_hub_args
  3068. def super_squash_history(
  3069. self,
  3070. repo_id: str,
  3071. *,
  3072. branch: Optional[str] = None,
  3073. commit_message: Optional[str] = None,
  3074. repo_type: Optional[str] = None,
  3075. token: Union[str, bool, None] = None,
  3076. ) -> None:
  3077. """Squash commit history on a branch for a repo on the Hub.
  3078. Squashing the repo history is useful when you know you'll make hundreds of commits and you don't want to
  3079. clutter the history. Squashing commits can only be performed from the head of a branch.
  3080. > [!WARNING]
  3081. > Once squashed, the commit history cannot be retrieved. This is a non-revertible operation.
  3082. > [!WARNING]
  3083. > Once the history of a branch has been squashed, it is not possible to merge it back into another branch since
  3084. > their history will have diverged.
  3085. Args:
  3086. repo_id (`str`):
  3087. A namespace (user or an organization) and a repo name separated by a `/`.
  3088. branch (`str`, *optional*):
  3089. The branch to squash. Defaults to the head of the `"main"` branch.
  3090. commit_message (`str`, *optional*):
  3091. The commit message to use for the squashed commit.
  3092. repo_type (`str`, *optional*):
  3093. Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
  3094. listing from a model. Default is `None`.
  3095. token (`bool` or `str`, *optional*):
  3096. A valid user access token (string). Defaults to the locally saved
  3097. token, which is the recommended method for authentication (see
  3098. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3099. To disable authentication, pass `False`.
  3100. Raises:
  3101. [`~utils.RepositoryNotFoundError`]:
  3102. If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
  3103. does not exist.
  3104. [`~utils.RevisionNotFoundError`]:
  3105. If the branch to squash cannot be found.
  3106. [`~utils.BadRequestError`]:
  3107. If invalid reference for a branch. You cannot squash history on tags.
  3108. Example:
  3109. ```py
  3110. >>> from huggingface_hub import HfApi
  3111. >>> api = HfApi()
  3112. # Create repo
  3113. >>> repo_id = api.create_repo("test-squash").repo_id
  3114. # Make a lot of commits.
  3115. >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content")
  3116. >>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content")
  3117. >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content")
  3118. # Squash history
  3119. >>> api.super_squash_history(repo_id=repo_id)
  3120. ```
  3121. """
  3122. if repo_type is None:
  3123. repo_type = constants.REPO_TYPE_MODEL
  3124. if repo_type not in constants.REPO_TYPES:
  3125. raise ValueError("Invalid repo type")
  3126. if branch is None:
  3127. branch = constants.DEFAULT_REVISION
  3128. # Prepare request
  3129. url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/super-squash/{quote(branch, safe='')}"
  3130. headers = self._build_hf_headers(token=token)
  3131. commit_message = commit_message or f"Super-squash branch '{branch}' using huggingface_hub"
  3132. # Super-squash
  3133. response = get_session().post(url=url, headers=headers, json={"message": commit_message})
  3134. hf_raise_for_status(response)
  3135. @validate_hf_hub_args
  3136. def list_lfs_files(
  3137. self,
  3138. repo_id: str,
  3139. *,
  3140. repo_type: Optional[str] = None,
  3141. token: Union[bool, str, None] = None,
  3142. ) -> Iterable[LFSFileInfo]:
  3143. """
  3144. List all LFS files in a repo on the Hub.
  3145. This is primarily useful to count how much storage a repo is using and to eventually clean up large files
  3146. with [`permanently_delete_lfs_files`]. Note that this would be a permanent action that will affect all commits
  3147. referencing this deleted files and that cannot be undone.
  3148. Args:
  3149. repo_id (`str`):
  3150. The repository for which you are listing LFS files.
  3151. repo_type (`str`, *optional*):
  3152. Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or
  3153. `"model"` if listing from a model. Default is `None`.
  3154. token (`bool` or `str`, *optional*):
  3155. A valid user access token (string). Defaults to the locally saved
  3156. token, which is the recommended method for authentication (see
  3157. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3158. To disable authentication, pass `False`.
  3159. Returns:
  3160. `Iterable[LFSFileInfo]`: An iterator of [`LFSFileInfo`] objects.
  3161. Example:
  3162. ```py
  3163. >>> from huggingface_hub import HfApi
  3164. >>> api = HfApi()
  3165. >>> lfs_files = api.list_lfs_files("username/my-cool-repo")
  3166. # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
  3167. # e.g. select only LFS files in the "checkpoints" folder
  3168. >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
  3169. # Permanently delete LFS files
  3170. >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
  3171. ```
  3172. """
  3173. # Prepare request
  3174. if repo_type is None:
  3175. repo_type = constants.REPO_TYPE_MODEL
  3176. url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/lfs-files"
  3177. headers = self._build_hf_headers(token=token)
  3178. # Paginate over LFS items
  3179. for item in paginate(url, params={}, headers=headers):
  3180. yield LFSFileInfo(**item)
  3181. @validate_hf_hub_args
  3182. def permanently_delete_lfs_files(
  3183. self,
  3184. repo_id: str,
  3185. lfs_files: Iterable[LFSFileInfo],
  3186. *,
  3187. rewrite_history: bool = True,
  3188. repo_type: Optional[str] = None,
  3189. token: Union[bool, str, None] = None,
  3190. ) -> None:
  3191. """
  3192. Permanently delete LFS files from a repo on the Hub.
  3193. > [!WARNING]
  3194. > This is a permanent action that will affect all commits referencing the deleted files and might corrupt your
  3195. > repository. This is a non-revertible operation. Use it only if you know what you are doing.
  3196. Args:
  3197. repo_id (`str`):
  3198. The repository for which you are listing LFS files.
  3199. lfs_files (`Iterable[LFSFileInfo]`):
  3200. An iterable of [`LFSFileInfo`] items to permanently delete from the repo. Use [`list_lfs_files`] to list
  3201. all LFS files from a repo.
  3202. rewrite_history (`bool`, *optional*, default to `True`):
  3203. Whether to rewrite repository history to remove file pointers referencing the deleted LFS files (recommended).
  3204. repo_type (`str`, *optional*):
  3205. Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or
  3206. `"model"` if listing from a model. Default is `None`.
  3207. token (`bool` or `str`, *optional*):
  3208. A valid user access token (string). Defaults to the locally saved
  3209. token, which is the recommended method for authentication (see
  3210. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3211. To disable authentication, pass `False`.
  3212. Example:
  3213. ```py
  3214. >>> from huggingface_hub import HfApi
  3215. >>> api = HfApi()
  3216. >>> lfs_files = api.list_lfs_files("username/my-cool-repo")
  3217. # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
  3218. # e.g. select only LFS files in the "checkpoints" folder
  3219. >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
  3220. # Permanently delete LFS files
  3221. >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
  3222. ```
  3223. """
  3224. # Prepare request
  3225. if repo_type is None:
  3226. repo_type = constants.REPO_TYPE_MODEL
  3227. url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/lfs-files/batch"
  3228. headers = self._build_hf_headers(token=token)
  3229. # Delete LFS items by batches of 1000
  3230. for batch in chunk_iterable(lfs_files, 1000):
  3231. shas = [item.file_oid for item in batch]
  3232. if len(shas) == 0:
  3233. return
  3234. payload = {
  3235. "deletions": {
  3236. "sha": shas,
  3237. "rewriteHistory": rewrite_history,
  3238. }
  3239. }
  3240. response = get_session().post(url, headers=headers, json=payload)
  3241. hf_raise_for_status(response)
  3242. @validate_hf_hub_args
  3243. def create_repo(
  3244. self,
  3245. repo_id: str,
  3246. *,
  3247. token: Union[str, bool, None] = None,
  3248. private: Optional[bool] = None,
  3249. repo_type: Optional[str] = None,
  3250. exist_ok: bool = False,
  3251. resource_group_id: Optional[str] = None,
  3252. space_sdk: Optional[str] = None,
  3253. space_hardware: Optional[SpaceHardware] = None,
  3254. space_storage: Optional[SpaceStorage] = None,
  3255. space_sleep_time: Optional[int] = None,
  3256. space_secrets: Optional[List[Dict[str, str]]] = None,
  3257. space_variables: Optional[List[Dict[str, str]]] = None,
  3258. ) -> RepoUrl:
  3259. """Create an empty repo on the HuggingFace Hub.
  3260. Args:
  3261. repo_id (`str`):
  3262. A namespace (user or an organization) and a repo name separated
  3263. by a `/`.
  3264. token (`bool` or `str`, *optional*):
  3265. A valid user access token (string). Defaults to the locally saved
  3266. token, which is the recommended method for authentication (see
  3267. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3268. To disable authentication, pass `False`.
  3269. private (`bool`, *optional*):
  3270. 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.
  3271. repo_type (`str`, *optional*):
  3272. Set to `"dataset"` or `"space"` if uploading to a dataset or
  3273. space, `None` or `"model"` if uploading to a model. Default is
  3274. `None`.
  3275. exist_ok (`bool`, *optional*, defaults to `False`):
  3276. If `True`, do not raise an error if repo already exists.
  3277. resource_group_id (`str`, *optional*):
  3278. Resource group in which to create the repo. Resource groups is only available for Enterprise Hub organizations and
  3279. allow to define which members of the organization can access the resource. The ID of a resource group
  3280. can be found in the URL of the resource's page on the Hub (e.g. `"66670e5163145ca562cb1988"`).
  3281. To learn more about resource groups, see https://huggingface.co/docs/hub/en/security-resource-groups.
  3282. space_sdk (`str`, *optional*):
  3283. Choice of SDK to use if repo_type is "space". Can be "streamlit", "gradio", "docker", or "static".
  3284. space_hardware (`SpaceHardware` or `str`, *optional*):
  3285. Choice of Hardware if repo_type is "space". See [`SpaceHardware`] for a complete list.
  3286. space_storage (`SpaceStorage` or `str`, *optional*):
  3287. Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
  3288. space_sleep_time (`int`, *optional*):
  3289. Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
  3290. your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
  3291. the sleep time (value is fixed to 48 hours of inactivity).
  3292. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  3293. space_secrets (`List[Dict[str, str]]`, *optional*):
  3294. A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
  3295. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  3296. space_variables (`List[Dict[str, str]]`, *optional*):
  3297. A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
  3298. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
  3299. Returns:
  3300. [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
  3301. attributes like `endpoint`, `repo_type` and `repo_id`.
  3302. """
  3303. organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id)
  3304. path = f"{self.endpoint}/api/repos/create"
  3305. if repo_type not in constants.REPO_TYPES:
  3306. raise ValueError("Invalid repo type")
  3307. json: Dict[str, Any] = {"name": name, "organization": organization}
  3308. if private is not None:
  3309. json["private"] = private
  3310. if repo_type is not None:
  3311. json["type"] = repo_type
  3312. if repo_type == "space":
  3313. if space_sdk is None:
  3314. raise ValueError(
  3315. "No space_sdk provided. `create_repo` expects space_sdk to be one"
  3316. f" of {constants.SPACES_SDK_TYPES} when repo_type is 'space'`"
  3317. )
  3318. if space_sdk not in constants.SPACES_SDK_TYPES:
  3319. raise ValueError(f"Invalid space_sdk. Please choose one of {constants.SPACES_SDK_TYPES}.")
  3320. json["sdk"] = space_sdk
  3321. if space_sdk is not None and repo_type != "space":
  3322. warnings.warn("Ignoring provided space_sdk because repo_type is not 'space'.")
  3323. function_args = [
  3324. "space_hardware",
  3325. "space_storage",
  3326. "space_sleep_time",
  3327. "space_secrets",
  3328. "space_variables",
  3329. ]
  3330. json_keys = ["hardware", "storageTier", "sleepTimeSeconds", "secrets", "variables"]
  3331. values = [space_hardware, space_storage, space_sleep_time, space_secrets, space_variables]
  3332. if repo_type == "space":
  3333. json.update({k: v for k, v in zip(json_keys, values) if v is not None})
  3334. else:
  3335. provided_space_args = [key for key, value in zip(function_args, values) if value is not None]
  3336. if provided_space_args:
  3337. warnings.warn(f"Ignoring provided {', '.join(provided_space_args)} because repo_type is not 'space'.")
  3338. if getattr(self, "_lfsmultipartthresh", None):
  3339. # Testing purposes only.
  3340. # See https://github.com/huggingface/huggingface_hub/pull/733/files#r820604472
  3341. json["lfsmultipartthresh"] = self._lfsmultipartthresh # type: ignore
  3342. if resource_group_id is not None:
  3343. json["resourceGroupId"] = resource_group_id
  3344. headers = self._build_hf_headers(token=token)
  3345. while True:
  3346. r = get_session().post(path, headers=headers, json=json)
  3347. if r.status_code == 409 and "Cannot create repo: another conflicting operation is in progress" in r.text:
  3348. # Since https://github.com/huggingface/moon-landing/pull/7272 (private repo), it is not possible to
  3349. # concurrently create repos on the Hub for a same user. This is rarely an issue, except when running
  3350. # tests. To avoid any inconvenience, we retry to create the repo for this specific error.
  3351. # NOTE: This could have being fixed directly in the tests but adding it here should fixed CIs for all
  3352. # dependent libraries.
  3353. # NOTE: If a fix is implemented server-side, we should be able to remove this retry mechanism.
  3354. logger.debug("Create repo failed due to a concurrency issue. Retrying...")
  3355. continue
  3356. break
  3357. try:
  3358. hf_raise_for_status(r)
  3359. except HTTPError as err:
  3360. if exist_ok and err.response.status_code == 409:
  3361. # Repo already exists and `exist_ok=True`
  3362. pass
  3363. elif exist_ok and err.response.status_code == 403:
  3364. # No write permission on the namespace but repo might already exist
  3365. try:
  3366. self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token)
  3367. if repo_type is None or repo_type == constants.REPO_TYPE_MODEL:
  3368. return RepoUrl(f"{self.endpoint}/{repo_id}")
  3369. return RepoUrl(f"{self.endpoint}/{repo_type}/{repo_id}")
  3370. except HfHubHTTPError:
  3371. raise err
  3372. else:
  3373. raise
  3374. d = r.json()
  3375. return RepoUrl(d["url"], endpoint=self.endpoint)
  3376. @validate_hf_hub_args
  3377. def delete_repo(
  3378. self,
  3379. repo_id: str,
  3380. *,
  3381. token: Union[str, bool, None] = None,
  3382. repo_type: Optional[str] = None,
  3383. missing_ok: bool = False,
  3384. ) -> None:
  3385. """
  3386. Delete a repo from the HuggingFace Hub. CAUTION: this is irreversible.
  3387. Args:
  3388. repo_id (`str`):
  3389. A namespace (user or an organization) and a repo name separated
  3390. by a `/`.
  3391. token (`bool` or `str`, *optional*):
  3392. A valid user access token (string). Defaults to the locally saved
  3393. token, which is the recommended method for authentication (see
  3394. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3395. To disable authentication, pass `False`.
  3396. repo_type (`str`, *optional*):
  3397. Set to `"dataset"` or `"space"` if uploading to a dataset or
  3398. space, `None` or `"model"` if uploading to a model.
  3399. missing_ok (`bool`, *optional*, defaults to `False`):
  3400. If `True`, do not raise an error if repo does not exist.
  3401. Raises:
  3402. [`~utils.RepositoryNotFoundError`]
  3403. If the repository to delete from cannot be found and `missing_ok` is set to False (default).
  3404. """
  3405. organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id)
  3406. path = f"{self.endpoint}/api/repos/delete"
  3407. if repo_type not in constants.REPO_TYPES:
  3408. raise ValueError("Invalid repo type")
  3409. json = {"name": name, "organization": organization}
  3410. if repo_type is not None:
  3411. json["type"] = repo_type
  3412. headers = self._build_hf_headers(token=token)
  3413. r = get_session().delete(path, headers=headers, json=json)
  3414. try:
  3415. hf_raise_for_status(r)
  3416. except RepositoryNotFoundError:
  3417. if not missing_ok:
  3418. raise
  3419. @_deprecate_method(version="0.32", message="Please use `update_repo_settings` instead.")
  3420. @validate_hf_hub_args
  3421. def update_repo_visibility(
  3422. self,
  3423. repo_id: str,
  3424. private: bool = False,
  3425. *,
  3426. token: Union[str, bool, None] = None,
  3427. repo_type: Optional[str] = None,
  3428. ) -> Dict[str, bool]:
  3429. """Update the visibility setting of a repository.
  3430. Deprecated. Use `update_repo_settings` instead.
  3431. Args:
  3432. repo_id (`str`, *optional*):
  3433. A namespace (user or an organization) and a repo name separated by a `/`.
  3434. private (`bool`, *optional*, defaults to `False`):
  3435. Whether the repository should be private.
  3436. token (`bool` or `str`, *optional*):
  3437. A valid user access token (string). Defaults to the locally saved
  3438. token, which is the recommended method for authentication (see
  3439. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3440. To disable authentication, pass `False`.
  3441. repo_type (`str`, *optional*):
  3442. Set to `"dataset"` or `"space"` if uploading to a dataset or
  3443. space, `None` or `"model"` if uploading to a model. Default is
  3444. `None`.
  3445. Returns:
  3446. The HTTP response in json.
  3447. > [!TIP]
  3448. > Raises the following errors:
  3449. >
  3450. > - [`~utils.RepositoryNotFoundError`]
  3451. > If the repository to download from cannot be found. This may be because it doesn't exist,
  3452. > or because it is set to `private` and you do not have access.
  3453. """
  3454. if repo_type not in constants.REPO_TYPES:
  3455. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  3456. if repo_type is None:
  3457. repo_type = constants.REPO_TYPE_MODEL # default repo type
  3458. r = get_session().put(
  3459. url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/settings",
  3460. headers=self._build_hf_headers(token=token),
  3461. json={"private": private},
  3462. )
  3463. hf_raise_for_status(r)
  3464. return r.json()
  3465. @validate_hf_hub_args
  3466. def update_repo_settings(
  3467. self,
  3468. repo_id: str,
  3469. *,
  3470. gated: Optional[Literal["auto", "manual", False]] = None,
  3471. private: Optional[bool] = None,
  3472. token: Union[str, bool, None] = None,
  3473. repo_type: Optional[str] = None,
  3474. xet_enabled: Optional[bool] = None,
  3475. ) -> None:
  3476. """
  3477. Update the settings of a repository, including gated access and visibility.
  3478. To give more control over how repos are used, the Hub allows repo authors to enable
  3479. access requests for their repos, and also to set the visibility of the repo to private.
  3480. Args:
  3481. repo_id (`str`):
  3482. A namespace (user or an organization) and a repo name separated by a /.
  3483. gated (`Literal["auto", "manual", False]`, *optional*):
  3484. The gated status for the repository. If set to `None` (default), the `gated` setting of the repository won't be updated.
  3485. * "auto": The repository is gated, and access requests are automatically approved or denied based on predefined criteria.
  3486. * "manual": The repository is gated, and access requests require manual approval.
  3487. * False : The repository is not gated, and anyone can access it.
  3488. private (`bool`, *optional*):
  3489. Whether the repository should be private.
  3490. token (`Union[str, bool, None]`, *optional*):
  3491. A valid user access token (string). Defaults to the locally saved token,
  3492. which is the recommended method for authentication (see
  3493. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3494. To disable authentication, pass False.
  3495. repo_type (`str`, *optional*):
  3496. The type of the repository to update settings from (`"model"`, `"dataset"` or `"space"`).
  3497. Defaults to `"model"`.
  3498. xet_enabled (`bool`, *optional*):
  3499. Whether the repository should be enabled for Xet Storage.
  3500. Raises:
  3501. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  3502. If gated is not one of "auto", "manual", or False.
  3503. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  3504. If repo_type is not one of the values in constants.REPO_TYPES.
  3505. [`~utils.HfHubHTTPError`]:
  3506. If the request to the Hugging Face Hub API fails.
  3507. [`~utils.RepositoryNotFoundError`]
  3508. If the repository to download from cannot be found. This may be because it doesn't exist,
  3509. or because it is set to `private` and you do not have access.
  3510. """
  3511. if repo_type not in constants.REPO_TYPES:
  3512. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  3513. if repo_type is None:
  3514. repo_type = constants.REPO_TYPE_MODEL # default repo type
  3515. # Prepare the JSON payload for the PUT request
  3516. payload: Dict = {}
  3517. if gated is not None:
  3518. if gated not in ["auto", "manual", False]:
  3519. raise ValueError(f"Invalid gated status, must be one of 'auto', 'manual', or False. Got '{gated}'.")
  3520. payload["gated"] = gated
  3521. if private is not None:
  3522. payload["private"] = private
  3523. if xet_enabled is not None:
  3524. payload["xetEnabled"] = xet_enabled
  3525. if len(payload) == 0:
  3526. raise ValueError("At least one setting must be updated.")
  3527. # Build headers
  3528. headers = self._build_hf_headers(token=token)
  3529. r = get_session().put(
  3530. url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/settings",
  3531. headers=headers,
  3532. json=payload,
  3533. )
  3534. hf_raise_for_status(r)
  3535. def move_repo(
  3536. self,
  3537. from_id: str,
  3538. to_id: str,
  3539. *,
  3540. repo_type: Optional[str] = None,
  3541. token: Union[str, bool, None] = None,
  3542. ):
  3543. """
  3544. Moving a repository from namespace1/repo_name1 to namespace2/repo_name2
  3545. Note there are certain limitations. For more information about moving
  3546. repositories, please see
  3547. https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.
  3548. Args:
  3549. from_id (`str`):
  3550. A namespace (user or an organization) and a repo name separated
  3551. by a `/`. Original repository identifier.
  3552. to_id (`str`):
  3553. A namespace (user or an organization) and a repo name separated
  3554. by a `/`. Final repository identifier.
  3555. repo_type (`str`, *optional*):
  3556. Set to `"dataset"` or `"space"` if uploading to a dataset or
  3557. space, `None` or `"model"` if uploading to a model. Default is
  3558. `None`.
  3559. token (`bool` or `str`, *optional*):
  3560. A valid user access token (string). Defaults to the locally saved
  3561. token, which is the recommended method for authentication (see
  3562. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3563. To disable authentication, pass `False`.
  3564. > [!TIP]
  3565. > Raises the following errors:
  3566. >
  3567. > - [`~utils.RepositoryNotFoundError`]
  3568. > If the repository to download from cannot be found. This may be because it doesn't exist,
  3569. > or because it is set to `private` and you do not have access.
  3570. """
  3571. if len(from_id.split("/")) != 2:
  3572. raise ValueError(f"Invalid repo_id: {from_id}. It should have a namespace (:namespace:/:repo_name:)")
  3573. if len(to_id.split("/")) != 2:
  3574. raise ValueError(f"Invalid repo_id: {to_id}. It should have a namespace (:namespace:/:repo_name:)")
  3575. if repo_type is None:
  3576. repo_type = constants.REPO_TYPE_MODEL # Hub won't accept `None`.
  3577. json = {"fromRepo": from_id, "toRepo": to_id, "type": repo_type}
  3578. path = f"{self.endpoint}/api/repos/move"
  3579. headers = self._build_hf_headers(token=token)
  3580. r = get_session().post(path, headers=headers, json=json)
  3581. try:
  3582. hf_raise_for_status(r)
  3583. except HfHubHTTPError as e:
  3584. e.append_to_message(
  3585. "\nFor additional documentation please see"
  3586. " https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo."
  3587. )
  3588. raise
  3589. @overload
  3590. def create_commit( # type: ignore
  3591. self,
  3592. repo_id: str,
  3593. operations: Iterable[CommitOperation],
  3594. *,
  3595. commit_message: str,
  3596. commit_description: Optional[str] = None,
  3597. token: Union[str, bool, None] = None,
  3598. repo_type: Optional[str] = None,
  3599. revision: Optional[str] = None,
  3600. create_pr: Optional[bool] = None,
  3601. num_threads: int = 5,
  3602. parent_commit: Optional[str] = None,
  3603. run_as_future: Literal[False] = ...,
  3604. ) -> CommitInfo: ...
  3605. @overload
  3606. def create_commit(
  3607. self,
  3608. repo_id: str,
  3609. operations: Iterable[CommitOperation],
  3610. *,
  3611. commit_message: str,
  3612. commit_description: Optional[str] = None,
  3613. token: Union[str, bool, None] = None,
  3614. repo_type: Optional[str] = None,
  3615. revision: Optional[str] = None,
  3616. create_pr: Optional[bool] = None,
  3617. num_threads: int = 5,
  3618. parent_commit: Optional[str] = None,
  3619. run_as_future: Literal[True] = ...,
  3620. ) -> Future[CommitInfo]: ...
  3621. @validate_hf_hub_args
  3622. @future_compatible
  3623. def create_commit(
  3624. self,
  3625. repo_id: str,
  3626. operations: Iterable[CommitOperation],
  3627. *,
  3628. commit_message: str,
  3629. commit_description: Optional[str] = None,
  3630. token: Union[str, bool, None] = None,
  3631. repo_type: Optional[str] = None,
  3632. revision: Optional[str] = None,
  3633. create_pr: Optional[bool] = None,
  3634. num_threads: int = 5,
  3635. parent_commit: Optional[str] = None,
  3636. run_as_future: bool = False,
  3637. ) -> Union[CommitInfo, Future[CommitInfo]]:
  3638. """
  3639. Creates a commit in the given repo, deleting & uploading files as needed.
  3640. > [!WARNING]
  3641. > The input list of `CommitOperation` will be mutated during the commit process. Do not reuse the same objects
  3642. > for multiple commits.
  3643. > [!WARNING]
  3644. > `create_commit` assumes that the repo already exists on the Hub. If you get a
  3645. > Client error 404, please make sure you are authenticated and that `repo_id` and
  3646. > `repo_type` are set correctly. If repo does not exist, create it first using
  3647. > [`~hf_api.create_repo`].
  3648. > [!WARNING]
  3649. > `create_commit` is limited to 25k LFS files and a 1GB payload for regular files.
  3650. Args:
  3651. repo_id (`str`):
  3652. The repository in which the commit will be created, for example:
  3653. `"username/custom_transformers"`
  3654. operations (`Iterable` of [`~hf_api.CommitOperation`]):
  3655. An iterable of operations to include in the commit, either:
  3656. - [`~hf_api.CommitOperationAdd`] to upload a file
  3657. - [`~hf_api.CommitOperationDelete`] to delete a file
  3658. - [`~hf_api.CommitOperationCopy`] to copy a file
  3659. Operation objects will be mutated to include information relative to the upload. Do not reuse the
  3660. same objects for multiple commits.
  3661. commit_message (`str`):
  3662. The summary (first line) of the commit that will be created.
  3663. commit_description (`str`, *optional*):
  3664. The description of the commit that will be created
  3665. token (`bool` or `str`, *optional*):
  3666. A valid user access token (string). Defaults to the locally saved
  3667. token, which is the recommended method for authentication (see
  3668. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3669. To disable authentication, pass `False`.
  3670. repo_type (`str`, *optional*):
  3671. Set to `"dataset"` or `"space"` if uploading to a dataset or
  3672. space, `None` or `"model"` if uploading to a model. Default is
  3673. `None`.
  3674. revision (`str`, *optional*):
  3675. The git revision to commit from. Defaults to the head of the `"main"` branch.
  3676. create_pr (`boolean`, *optional*):
  3677. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  3678. If `revision` is not set, PR is opened against the `"main"` branch. If
  3679. `revision` is set and is a branch, PR is opened against this branch. If
  3680. `revision` is set and is not a branch name (example: a commit oid), an
  3681. `RevisionNotFoundError` is returned by the server.
  3682. num_threads (`int`, *optional*):
  3683. Number of concurrent threads for uploading files. Defaults to 5.
  3684. Setting it to 2 means at most 2 files will be uploaded concurrently.
  3685. parent_commit (`str`, *optional*):
  3686. The OID / SHA of the parent commit, as a hexadecimal string.
  3687. Shorthands (7 first characters) are also supported. If specified and `create_pr` is `False`,
  3688. the commit will fail if `revision` does not point to `parent_commit`. If specified and `create_pr`
  3689. is `True`, the pull request will be created from `parent_commit`. Specifying `parent_commit`
  3690. ensures the repo has not changed before committing the changes, and can be especially useful
  3691. if the repo is updated / committed to concurrently.
  3692. run_as_future (`bool`, *optional*):
  3693. Whether or not to run this method in the background. Background jobs are run sequentially without
  3694. blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
  3695. object. Defaults to `False`.
  3696. Returns:
  3697. [`CommitInfo`] or `Future`:
  3698. Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
  3699. url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
  3700. contain the result when executed.
  3701. Raises:
  3702. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  3703. If commit message is empty.
  3704. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  3705. If parent commit is not a valid commit OID.
  3706. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  3707. If a README.md file with an invalid metadata section is committed. In this case, the commit will fail
  3708. early, before trying to upload any file.
  3709. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  3710. If `create_pr` is `True` and revision is neither `None` nor `"main"`.
  3711. [`~utils.RepositoryNotFoundError`]:
  3712. If repository is not found (error 404): wrong repo_id/repo_type, private
  3713. but not authenticated or repo does not exist.
  3714. """
  3715. if parent_commit is not None and not constants.REGEX_COMMIT_OID.fullmatch(parent_commit):
  3716. raise ValueError(
  3717. f"`parent_commit` is not a valid commit OID. It must match the following regex: {constants.REGEX_COMMIT_OID}"
  3718. )
  3719. if commit_message is None or len(commit_message) == 0:
  3720. raise ValueError("`commit_message` can't be empty, please pass a value.")
  3721. commit_description = commit_description if commit_description is not None else ""
  3722. repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL
  3723. if repo_type not in constants.REPO_TYPES:
  3724. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  3725. unquoted_revision = revision or constants.DEFAULT_REVISION
  3726. revision = quote(unquoted_revision, safe="")
  3727. create_pr = create_pr if create_pr is not None else False
  3728. headers = self._build_hf_headers(token=token)
  3729. operations = list(operations)
  3730. additions = [op for op in operations if isinstance(op, CommitOperationAdd)]
  3731. copies = [op for op in operations if isinstance(op, CommitOperationCopy)]
  3732. nb_additions = len(additions)
  3733. nb_copies = len(copies)
  3734. nb_deletions = len(operations) - nb_additions - nb_copies
  3735. for addition in additions:
  3736. if addition._is_committed:
  3737. raise ValueError(
  3738. f"CommitOperationAdd {addition} has already being committed and cannot be reused. Please create a"
  3739. " new CommitOperationAdd object if you want to create a new commit."
  3740. )
  3741. if repo_type != "dataset":
  3742. for addition in additions:
  3743. if addition.path_in_repo.endswith((".arrow", ".parquet")):
  3744. warnings.warn(
  3745. f"It seems that you are about to commit a data file ({addition.path_in_repo}) to a {repo_type}"
  3746. " repository. You are sure this is intended? If you are trying to upload a dataset, please"
  3747. " set `repo_type='dataset'` or `--repo-type=dataset` in a CLI."
  3748. )
  3749. logger.debug(
  3750. f"About to commit to the hub: {len(additions)} addition(s), {len(copies)} copie(s) and"
  3751. f" {nb_deletions} deletion(s)."
  3752. )
  3753. # If updating a README.md file, make sure the metadata format is valid
  3754. # It's better to fail early than to fail after all the files have been uploaded.
  3755. for addition in additions:
  3756. if addition.path_in_repo == "README.md":
  3757. with addition.as_file() as file:
  3758. content = file.read().decode()
  3759. self._validate_yaml(content, repo_type=repo_type, token=token)
  3760. # Skip other additions after `README.md` has been processed
  3761. break
  3762. # If updating twice the same file or update then delete a file in a single commit
  3763. _warn_on_overwriting_operations(operations)
  3764. self.preupload_lfs_files(
  3765. repo_id=repo_id,
  3766. additions=additions,
  3767. token=token,
  3768. repo_type=repo_type,
  3769. revision=unquoted_revision, # first-class methods take unquoted revision
  3770. create_pr=create_pr,
  3771. num_threads=num_threads,
  3772. free_memory=False, # do not remove `CommitOperationAdd.path_or_fileobj` on LFS files for "normal" users
  3773. )
  3774. files_to_copy = _fetch_files_to_copy(
  3775. copies=copies,
  3776. repo_type=repo_type,
  3777. repo_id=repo_id,
  3778. headers=headers,
  3779. revision=unquoted_revision,
  3780. endpoint=self.endpoint,
  3781. )
  3782. # Remove no-op operations (files that have not changed)
  3783. operations_without_no_op = []
  3784. for operation in operations:
  3785. if (
  3786. isinstance(operation, CommitOperationAdd)
  3787. and operation._remote_oid is not None
  3788. and operation._remote_oid == operation._local_oid
  3789. ):
  3790. # File already exists on the Hub and has not changed: we can skip it.
  3791. logger.debug(f"Skipping upload for '{operation.path_in_repo}' as the file has not changed.")
  3792. continue
  3793. if (
  3794. isinstance(operation, CommitOperationCopy)
  3795. and operation._dest_oid is not None
  3796. and operation._dest_oid == operation._src_oid
  3797. ):
  3798. # Source and destination files are identical - skip
  3799. logger.debug(
  3800. 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."
  3801. )
  3802. continue
  3803. operations_without_no_op.append(operation)
  3804. if len(operations) != len(operations_without_no_op):
  3805. logger.info(
  3806. f"Removing {len(operations) - len(operations_without_no_op)} file(s) from commit that have not changed."
  3807. )
  3808. # Return early if empty commit
  3809. if len(operations_without_no_op) == 0:
  3810. logger.warning("No files have been modified since last commit. Skipping to prevent empty commit.")
  3811. # Get latest commit info
  3812. try:
  3813. info = self.repo_info(repo_id=repo_id, repo_type=repo_type, revision=unquoted_revision, token=token)
  3814. except RepositoryNotFoundError as e:
  3815. e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE)
  3816. raise
  3817. # Return commit info based on latest commit
  3818. url_prefix = self.endpoint
  3819. if repo_type is not None and repo_type != constants.REPO_TYPE_MODEL:
  3820. url_prefix = f"{url_prefix}/{repo_type}s"
  3821. return CommitInfo(
  3822. commit_url=f"{url_prefix}/{repo_id}/commit/{info.sha}",
  3823. commit_message=commit_message,
  3824. commit_description=commit_description,
  3825. oid=info.sha, # type: ignore[arg-type]
  3826. )
  3827. commit_payload = _prepare_commit_payload(
  3828. operations=operations,
  3829. files_to_copy=files_to_copy,
  3830. commit_message=commit_message,
  3831. commit_description=commit_description,
  3832. parent_commit=parent_commit,
  3833. )
  3834. commit_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/commit/{revision}"
  3835. def _payload_as_ndjson() -> Iterable[bytes]:
  3836. for item in commit_payload:
  3837. yield json.dumps(item).encode()
  3838. yield b"\n"
  3839. headers = {
  3840. # See https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
  3841. "Content-Type": "application/x-ndjson",
  3842. **headers,
  3843. }
  3844. data = b"".join(_payload_as_ndjson())
  3845. params = {"create_pr": "1"} if create_pr else None
  3846. try:
  3847. commit_resp = get_session().post(url=commit_url, headers=headers, data=data, params=params)
  3848. hf_raise_for_status(commit_resp, endpoint_name="commit")
  3849. except RepositoryNotFoundError as e:
  3850. e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE)
  3851. raise
  3852. except EntryNotFoundError as e:
  3853. if nb_deletions > 0 and "A file with this name doesn't exist" in str(e):
  3854. e.append_to_message(
  3855. "\nMake sure to differentiate file and folder paths in delete"
  3856. " operations with a trailing '/' or using `is_folder=True/False`."
  3857. )
  3858. raise
  3859. # Mark additions as committed (cannot be reused in another commit)
  3860. for addition in additions:
  3861. addition._is_committed = True
  3862. commit_data = commit_resp.json()
  3863. return CommitInfo(
  3864. commit_url=commit_data["commitUrl"],
  3865. commit_message=commit_message,
  3866. commit_description=commit_description,
  3867. oid=commit_data["commitOid"],
  3868. pr_url=commit_data["pullRequestUrl"] if create_pr else None,
  3869. )
  3870. def preupload_lfs_files(
  3871. self,
  3872. repo_id: str,
  3873. additions: Iterable[CommitOperationAdd],
  3874. *,
  3875. token: Union[str, bool, None] = None,
  3876. repo_type: Optional[str] = None,
  3877. revision: Optional[str] = None,
  3878. create_pr: Optional[bool] = None,
  3879. num_threads: int = 5,
  3880. free_memory: bool = True,
  3881. gitignore_content: Optional[str] = None,
  3882. ):
  3883. """Pre-upload LFS files to S3 in preparation on a future commit.
  3884. This method is useful if you are generating the files to upload on-the-fly and you don't want to store them
  3885. in memory before uploading them all at once.
  3886. > [!WARNING]
  3887. > This is a power-user method. You shouldn't need to call it directly to make a normal commit.
  3888. > Use [`create_commit`] directly instead.
  3889. > [!WARNING]
  3890. > Commit operations will be mutated during the process. In particular, the attached `path_or_fileobj` will be
  3891. > removed after the upload to save memory (and replaced by an empty `bytes` object). Do not reuse the same
  3892. > objects except to pass them to [`create_commit`]. If you don't want to remove the attached content from the
  3893. > commit operation object, pass `free_memory=False`.
  3894. Args:
  3895. repo_id (`str`):
  3896. The repository in which you will commit the files, for example: `"username/custom_transformers"`.
  3897. operations (`Iterable` of [`CommitOperationAdd`]):
  3898. The list of files to upload. Warning: the objects in this list will be mutated to include information
  3899. relative to the upload. Do not reuse the same objects for multiple commits.
  3900. token (`bool` or `str`, *optional*):
  3901. A valid user access token (string). Defaults to the locally saved
  3902. token, which is the recommended method for authentication (see
  3903. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  3904. To disable authentication, pass `False`.
  3905. repo_type (`str`, *optional*):
  3906. The type of repository to upload to (e.g. `"model"` -default-, `"dataset"` or `"space"`).
  3907. revision (`str`, *optional*):
  3908. The git revision to commit from. Defaults to the head of the `"main"` branch.
  3909. create_pr (`boolean`, *optional*):
  3910. Whether or not you plan to create a Pull Request with that commit. Defaults to `False`.
  3911. num_threads (`int`, *optional*):
  3912. Number of concurrent threads for uploading files. Defaults to 5.
  3913. Setting it to 2 means at most 2 files will be uploaded concurrently.
  3914. gitignore_content (`str`, *optional*):
  3915. The content of the `.gitignore` file to know which files should be ignored. The order of priority
  3916. is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
  3917. in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
  3918. (if any).
  3919. Example:
  3920. ```py
  3921. >>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo
  3922. >>> repo_id = create_repo("test_preupload").repo_id
  3923. # Generate and preupload LFS files one by one
  3924. >>> operations = [] # List of all `CommitOperationAdd` objects that will be generated
  3925. >>> for i in range(5):
  3926. ... content = ... # generate binary content
  3927. ... addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content)
  3928. ... preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory
  3929. ... operations.append(addition)
  3930. # Create commit
  3931. >>> create_commit(repo_id, operations=operations, commit_message="Commit all shards")
  3932. ```
  3933. """
  3934. repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL
  3935. if repo_type not in constants.REPO_TYPES:
  3936. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  3937. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  3938. create_pr = create_pr if create_pr is not None else False
  3939. headers = self._build_hf_headers(token=token)
  3940. # Check if a `gitignore` file is being committed to the Hub.
  3941. additions = list(additions)
  3942. if gitignore_content is None:
  3943. for addition in additions:
  3944. if addition.path_in_repo == ".gitignore":
  3945. with addition.as_file() as f:
  3946. gitignore_content = f.read().decode()
  3947. break
  3948. # Filter out already uploaded files
  3949. new_additions = [addition for addition in additions if not addition._is_uploaded]
  3950. # Check which new files are LFS
  3951. # For some items, we might have already fetched the upload mode (in case of upload_large_folder)
  3952. additions_no_upload_mode = [addition for addition in new_additions if addition._upload_mode is None]
  3953. if len(additions_no_upload_mode) > 0:
  3954. try:
  3955. _fetch_upload_modes(
  3956. additions=additions_no_upload_mode,
  3957. repo_type=repo_type,
  3958. repo_id=repo_id,
  3959. headers=headers,
  3960. revision=revision,
  3961. endpoint=self.endpoint,
  3962. create_pr=create_pr or False,
  3963. gitignore_content=gitignore_content,
  3964. )
  3965. except RepositoryNotFoundError as e:
  3966. e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE)
  3967. raise
  3968. # Filter out regular files
  3969. new_lfs_additions = [addition for addition in new_additions if addition._upload_mode == "lfs"]
  3970. # Filter out files listed in .gitignore
  3971. new_lfs_additions_to_upload = []
  3972. for addition in new_lfs_additions:
  3973. if addition._should_ignore:
  3974. logger.debug(f"Skipping upload for LFS file '{addition.path_in_repo}' (ignored by gitignore file).")
  3975. else:
  3976. new_lfs_additions_to_upload.append(addition)
  3977. if len(new_lfs_additions) != len(new_lfs_additions_to_upload):
  3978. logger.info(
  3979. f"Skipped upload for {len(new_lfs_additions) - len(new_lfs_additions_to_upload)} LFS file(s) "
  3980. "(ignored by gitignore file)."
  3981. )
  3982. # If no LFS files remain to upload, keep previous behavior and log explicitly
  3983. if len(new_lfs_additions_to_upload) == 0:
  3984. logger.debug("No LFS files to upload.")
  3985. return
  3986. # Prepare upload parameters
  3987. upload_kwargs = {
  3988. "additions": new_lfs_additions_to_upload,
  3989. "repo_type": repo_type,
  3990. "repo_id": repo_id,
  3991. "headers": headers,
  3992. "endpoint": self.endpoint,
  3993. # If `create_pr`, we don't want to check user permission on the revision as users with read permission
  3994. # should still be able to create PRs even if they don't have write permission on the target branch of the
  3995. # PR (i.e. `revision`).
  3996. "revision": revision if not create_pr else None,
  3997. }
  3998. _upload_files(**upload_kwargs, num_threads=num_threads, create_pr=create_pr) # type: ignore [arg-type]
  3999. for addition in new_lfs_additions_to_upload:
  4000. addition._is_uploaded = True
  4001. if free_memory:
  4002. addition.path_or_fileobj = b""
  4003. @overload
  4004. def upload_file( # type: ignore
  4005. self,
  4006. *,
  4007. path_or_fileobj: Union[str, Path, bytes, BinaryIO],
  4008. path_in_repo: str,
  4009. repo_id: str,
  4010. token: Union[str, bool, None] = None,
  4011. repo_type: Optional[str] = None,
  4012. revision: Optional[str] = None,
  4013. commit_message: Optional[str] = None,
  4014. commit_description: Optional[str] = None,
  4015. create_pr: Optional[bool] = None,
  4016. parent_commit: Optional[str] = None,
  4017. run_as_future: Literal[False] = ...,
  4018. ) -> CommitInfo: ...
  4019. @overload
  4020. def upload_file(
  4021. self,
  4022. *,
  4023. path_or_fileobj: Union[str, Path, bytes, BinaryIO],
  4024. path_in_repo: str,
  4025. repo_id: str,
  4026. token: Union[str, bool, None] = None,
  4027. repo_type: Optional[str] = None,
  4028. revision: Optional[str] = None,
  4029. commit_message: Optional[str] = None,
  4030. commit_description: Optional[str] = None,
  4031. create_pr: Optional[bool] = None,
  4032. parent_commit: Optional[str] = None,
  4033. run_as_future: Literal[True] = ...,
  4034. ) -> Future[CommitInfo]: ...
  4035. @validate_hf_hub_args
  4036. @future_compatible
  4037. def upload_file(
  4038. self,
  4039. *,
  4040. path_or_fileobj: Union[str, Path, bytes, BinaryIO],
  4041. path_in_repo: str,
  4042. repo_id: str,
  4043. token: Union[str, bool, None] = None,
  4044. repo_type: Optional[str] = None,
  4045. revision: Optional[str] = None,
  4046. commit_message: Optional[str] = None,
  4047. commit_description: Optional[str] = None,
  4048. create_pr: Optional[bool] = None,
  4049. parent_commit: Optional[str] = None,
  4050. run_as_future: bool = False,
  4051. ) -> Union[CommitInfo, Future[CommitInfo]]:
  4052. """
  4053. Upload a local file (up to 50 GB) to the given repo. The upload is done
  4054. through a HTTP post request, and doesn't require git or git-lfs to be
  4055. installed.
  4056. Args:
  4057. path_or_fileobj (`str`, `Path`, `bytes`, or `IO`):
  4058. Path to a file on the local machine or binary data stream /
  4059. fileobj / buffer.
  4060. path_in_repo (`str`):
  4061. Relative filepath in the repo, for example:
  4062. `"checkpoints/1fec34a/weights.bin"`
  4063. repo_id (`str`):
  4064. The repository to which the file will be uploaded, for example:
  4065. `"username/custom_transformers"`
  4066. token (`bool` or `str`, *optional*):
  4067. A valid user access token (string). Defaults to the locally saved
  4068. token, which is the recommended method for authentication (see
  4069. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4070. To disable authentication, pass `False`.
  4071. repo_type (`str`, *optional*):
  4072. Set to `"dataset"` or `"space"` if uploading to a dataset or
  4073. space, `None` or `"model"` if uploading to a model. Default is
  4074. `None`.
  4075. revision (`str`, *optional*):
  4076. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4077. commit_message (`str`, *optional*):
  4078. The summary / title / first line of the generated commit
  4079. commit_description (`str` *optional*)
  4080. The description of the generated commit
  4081. create_pr (`boolean`, *optional*):
  4082. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  4083. If `revision` is not set, PR is opened against the `"main"` branch. If
  4084. `revision` is set and is a branch, PR is opened against this branch. If
  4085. `revision` is set and is not a branch name (example: a commit oid), an
  4086. `RevisionNotFoundError` is returned by the server.
  4087. parent_commit (`str`, *optional*):
  4088. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  4089. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  4090. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  4091. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  4092. especially useful if the repo is updated / committed to concurrently.
  4093. run_as_future (`bool`, *optional*):
  4094. Whether or not to run this method in the background. Background jobs are run sequentially without
  4095. blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
  4096. object. Defaults to `False`.
  4097. Returns:
  4098. [`CommitInfo`] or `Future`:
  4099. Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
  4100. url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
  4101. contain the result when executed.
  4102. > [!TIP]
  4103. > Raises the following errors:
  4104. >
  4105. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  4106. > if the HuggingFace API returned an error
  4107. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4108. > if some parameter value is invalid
  4109. > - [`~utils.RepositoryNotFoundError`]
  4110. > If the repository to download from cannot be found. This may be because it doesn't exist,
  4111. > or because it is set to `private` and you do not have access.
  4112. > - [`~utils.RevisionNotFoundError`]
  4113. > If the revision to download from cannot be found.
  4114. > [!WARNING]
  4115. > `upload_file` assumes that the repo already exists on the Hub. If you get a
  4116. > Client error 404, please make sure you are authenticated and that `repo_id` and
  4117. > `repo_type` are set correctly. If repo does not exist, create it first using
  4118. > [`~hf_api.create_repo`].
  4119. Example:
  4120. ```python
  4121. >>> from huggingface_hub import upload_file
  4122. >>> with open("./local/filepath", "rb") as fobj:
  4123. ... upload_file(
  4124. ... path_or_fileobj=fileobj,
  4125. ... path_in_repo="remote/file/path.h5",
  4126. ... repo_id="username/my-dataset",
  4127. ... repo_type="dataset",
  4128. ... token="my_token",
  4129. ... )
  4130. "https://huggingface.co/datasets/username/my-dataset/blob/main/remote/file/path.h5"
  4131. >>> upload_file(
  4132. ... path_or_fileobj=".\\\\local\\\\file\\\\path",
  4133. ... path_in_repo="remote/file/path.h5",
  4134. ... repo_id="username/my-model",
  4135. ... token="my_token",
  4136. ... )
  4137. "https://huggingface.co/username/my-model/blob/main/remote/file/path.h5"
  4138. >>> upload_file(
  4139. ... path_or_fileobj=".\\\\local\\\\file\\\\path",
  4140. ... path_in_repo="remote/file/path.h5",
  4141. ... repo_id="username/my-model",
  4142. ... token="my_token",
  4143. ... create_pr=True,
  4144. ... )
  4145. "https://huggingface.co/username/my-model/blob/refs%2Fpr%2F1/remote/file/path.h5"
  4146. ```
  4147. """
  4148. if repo_type not in constants.REPO_TYPES:
  4149. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  4150. commit_message = (
  4151. commit_message if commit_message is not None else f"Upload {path_in_repo} with huggingface_hub"
  4152. )
  4153. operation = CommitOperationAdd(
  4154. path_or_fileobj=path_or_fileobj,
  4155. path_in_repo=path_in_repo,
  4156. )
  4157. commit_info = self.create_commit(
  4158. repo_id=repo_id,
  4159. repo_type=repo_type,
  4160. operations=[operation],
  4161. commit_message=commit_message,
  4162. commit_description=commit_description,
  4163. token=token,
  4164. revision=revision,
  4165. create_pr=create_pr,
  4166. parent_commit=parent_commit,
  4167. )
  4168. if commit_info.pr_url is not None:
  4169. revision = quote(_parse_revision_from_pr_url(commit_info.pr_url), safe="")
  4170. if repo_type in constants.REPO_TYPES_URL_PREFIXES:
  4171. repo_id = constants.REPO_TYPES_URL_PREFIXES[repo_type] + repo_id
  4172. revision = revision if revision is not None else constants.DEFAULT_REVISION
  4173. return CommitInfo(
  4174. commit_url=commit_info.commit_url,
  4175. commit_message=commit_info.commit_message,
  4176. commit_description=commit_info.commit_description,
  4177. oid=commit_info.oid,
  4178. pr_url=commit_info.pr_url,
  4179. # Similar to `hf_hub_url` but it's "blob" instead of "resolve"
  4180. # TODO: remove this in v1.0
  4181. _url=f"{self.endpoint}/{repo_id}/blob/{revision}/{path_in_repo}",
  4182. )
  4183. @overload
  4184. def upload_folder( # type: ignore
  4185. self,
  4186. *,
  4187. repo_id: str,
  4188. folder_path: Union[str, Path],
  4189. path_in_repo: Optional[str] = None,
  4190. commit_message: Optional[str] = None,
  4191. commit_description: Optional[str] = None,
  4192. token: Union[str, bool, None] = None,
  4193. repo_type: Optional[str] = None,
  4194. revision: Optional[str] = None,
  4195. create_pr: Optional[bool] = None,
  4196. parent_commit: Optional[str] = None,
  4197. allow_patterns: Optional[Union[List[str], str]] = None,
  4198. ignore_patterns: Optional[Union[List[str], str]] = None,
  4199. delete_patterns: Optional[Union[List[str], str]] = None,
  4200. run_as_future: Literal[False] = ...,
  4201. ) -> CommitInfo: ...
  4202. @overload
  4203. def upload_folder( # type: ignore
  4204. self,
  4205. *,
  4206. repo_id: str,
  4207. folder_path: Union[str, Path],
  4208. path_in_repo: Optional[str] = None,
  4209. commit_message: Optional[str] = None,
  4210. commit_description: Optional[str] = None,
  4211. token: Union[str, bool, None] = None,
  4212. repo_type: Optional[str] = None,
  4213. revision: Optional[str] = None,
  4214. create_pr: Optional[bool] = None,
  4215. parent_commit: Optional[str] = None,
  4216. allow_patterns: Optional[Union[List[str], str]] = None,
  4217. ignore_patterns: Optional[Union[List[str], str]] = None,
  4218. delete_patterns: Optional[Union[List[str], str]] = None,
  4219. run_as_future: Literal[True] = ...,
  4220. ) -> Future[CommitInfo]: ...
  4221. @validate_hf_hub_args
  4222. @future_compatible
  4223. def upload_folder(
  4224. self,
  4225. *,
  4226. repo_id: str,
  4227. folder_path: Union[str, Path],
  4228. path_in_repo: Optional[str] = None,
  4229. commit_message: Optional[str] = None,
  4230. commit_description: Optional[str] = None,
  4231. token: Union[str, bool, None] = None,
  4232. repo_type: Optional[str] = None,
  4233. revision: Optional[str] = None,
  4234. create_pr: Optional[bool] = None,
  4235. parent_commit: Optional[str] = None,
  4236. allow_patterns: Optional[Union[List[str], str]] = None,
  4237. ignore_patterns: Optional[Union[List[str], str]] = None,
  4238. delete_patterns: Optional[Union[List[str], str]] = None,
  4239. run_as_future: bool = False,
  4240. ) -> Union[CommitInfo, Future[CommitInfo]]:
  4241. """
  4242. Upload a local folder to the given repo. The upload is done through a HTTP requests, and doesn't require git or
  4243. git-lfs to be installed.
  4244. The structure of the folder will be preserved. Files with the same name already present in the repository will
  4245. be overwritten. Others will be left untouched.
  4246. Use the `allow_patterns` and `ignore_patterns` arguments to specify which files to upload. These parameters
  4247. accept either a single pattern or a list of patterns. Patterns are Standard Wildcards (globbing patterns) as
  4248. documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). If both `allow_patterns` and
  4249. `ignore_patterns` are provided, both constraints apply. By default, all files from the folder are uploaded.
  4250. Use the `delete_patterns` argument to specify remote files you want to delete. Input type is the same as for
  4251. `allow_patterns` (see above). If `path_in_repo` is also provided, the patterns are matched against paths
  4252. relative to this folder. For example, `upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*")`
  4253. will delete any remote file under `./experiment/logs/`. Note that the `.gitattributes` file will not be deleted
  4254. even if it matches the patterns.
  4255. Any `.git/` folder present in any subdirectory will be ignored. However, please be aware that the `.gitignore`
  4256. file is not taken into account.
  4257. Uses `HfApi.create_commit` under the hood.
  4258. Args:
  4259. repo_id (`str`):
  4260. The repository to which the file will be uploaded, for example:
  4261. `"username/custom_transformers"`
  4262. folder_path (`str` or `Path`):
  4263. Path to the folder to upload on the local file system
  4264. path_in_repo (`str`, *optional*):
  4265. Relative path of the directory in the repo, for example:
  4266. `"checkpoints/1fec34a/results"`. Will default to the root folder of the repository.
  4267. token (`bool` or `str`, *optional*):
  4268. A valid user access token (string). Defaults to the locally saved
  4269. token, which is the recommended method for authentication (see
  4270. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4271. To disable authentication, pass `False`.
  4272. repo_type (`str`, *optional*):
  4273. Set to `"dataset"` or `"space"` if uploading to a dataset or
  4274. space, `None` or `"model"` if uploading to a model. Default is
  4275. `None`.
  4276. revision (`str`, *optional*):
  4277. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4278. commit_message (`str`, *optional*):
  4279. The summary / title / first line of the generated commit. Defaults to:
  4280. `f"Upload {path_in_repo} with huggingface_hub"`
  4281. commit_description (`str` *optional*):
  4282. The description of the generated commit
  4283. create_pr (`boolean`, *optional*):
  4284. Whether or not to create a Pull Request with that commit. Defaults to `False`. If `revision` is not
  4285. set, PR is opened against the `"main"` branch. If `revision` is set and is a branch, PR is opened
  4286. against this branch. If `revision` is set and is not a branch name (example: a commit oid), an
  4287. `RevisionNotFoundError` is returned by the server.
  4288. parent_commit (`str`, *optional*):
  4289. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  4290. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  4291. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  4292. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  4293. especially useful if the repo is updated / committed to concurrently.
  4294. allow_patterns (`List[str]` or `str`, *optional*):
  4295. If provided, only files matching at least one pattern are uploaded.
  4296. ignore_patterns (`List[str]` or `str`, *optional*):
  4297. If provided, files matching any of the patterns are not uploaded.
  4298. delete_patterns (`List[str]` or `str`, *optional*):
  4299. If provided, remote files matching any of the patterns will be deleted from the repo while committing
  4300. new files. This is useful if you don't know which files have already been uploaded.
  4301. Note: to avoid discrepancies the `.gitattributes` file is not deleted even if it matches the pattern.
  4302. run_as_future (`bool`, *optional*):
  4303. Whether or not to run this method in the background. Background jobs are run sequentially without
  4304. blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
  4305. object. Defaults to `False`.
  4306. Returns:
  4307. [`CommitInfo`] or `Future`:
  4308. Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
  4309. url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
  4310. contain the result when executed.
  4311. > [!TIP]
  4312. > Raises the following errors:
  4313. >
  4314. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  4315. > if the HuggingFace API returned an error
  4316. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4317. > if some parameter value is invalid
  4318. > [!WARNING]
  4319. > `upload_folder` assumes that the repo already exists on the Hub. If you get a Client error 404, please make
  4320. > sure you are authenticated and that `repo_id` and `repo_type` are set correctly. If repo does not exist, create
  4321. > it first using [`~hf_api.create_repo`].
  4322. > [!TIP]
  4323. > When dealing with a large folder (thousands of files or hundreds of GB), we recommend using [`~hf_api.upload_large_folder`] instead.
  4324. Example:
  4325. ```python
  4326. # Upload checkpoints folder except the log files
  4327. >>> upload_folder(
  4328. ... folder_path="local/checkpoints",
  4329. ... path_in_repo="remote/experiment/checkpoints",
  4330. ... repo_id="username/my-dataset",
  4331. ... repo_type="datasets",
  4332. ... token="my_token",
  4333. ... ignore_patterns="**/logs/*.txt",
  4334. ... )
  4335. # "https://huggingface.co/datasets/username/my-dataset/tree/main/remote/experiment/checkpoints"
  4336. # Upload checkpoints folder including logs while deleting existing logs from the repo
  4337. # Useful if you don't know exactly which log files have already being pushed
  4338. >>> upload_folder(
  4339. ... folder_path="local/checkpoints",
  4340. ... path_in_repo="remote/experiment/checkpoints",
  4341. ... repo_id="username/my-dataset",
  4342. ... repo_type="datasets",
  4343. ... token="my_token",
  4344. ... delete_patterns="**/logs/*.txt",
  4345. ... )
  4346. "https://huggingface.co/datasets/username/my-dataset/tree/main/remote/experiment/checkpoints"
  4347. # Upload checkpoints folder while creating a PR
  4348. >>> upload_folder(
  4349. ... folder_path="local/checkpoints",
  4350. ... path_in_repo="remote/experiment/checkpoints",
  4351. ... repo_id="username/my-dataset",
  4352. ... repo_type="datasets",
  4353. ... token="my_token",
  4354. ... create_pr=True,
  4355. ... )
  4356. "https://huggingface.co/datasets/username/my-dataset/tree/refs%2Fpr%2F1/remote/experiment/checkpoints"
  4357. ```
  4358. """
  4359. if repo_type not in constants.REPO_TYPES:
  4360. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  4361. # By default, upload folder to the root directory in repo.
  4362. if path_in_repo is None:
  4363. path_in_repo = ""
  4364. # Do not upload .git folder
  4365. if ignore_patterns is None:
  4366. ignore_patterns = []
  4367. elif isinstance(ignore_patterns, str):
  4368. ignore_patterns = [ignore_patterns]
  4369. ignore_patterns += DEFAULT_IGNORE_PATTERNS
  4370. delete_operations = self._prepare_folder_deletions(
  4371. repo_id=repo_id,
  4372. repo_type=repo_type,
  4373. revision=constants.DEFAULT_REVISION if create_pr else revision,
  4374. token=token,
  4375. path_in_repo=path_in_repo,
  4376. delete_patterns=delete_patterns,
  4377. )
  4378. add_operations = self._prepare_upload_folder_additions(
  4379. folder_path,
  4380. path_in_repo,
  4381. allow_patterns=allow_patterns,
  4382. ignore_patterns=ignore_patterns,
  4383. token=token,
  4384. repo_type=repo_type,
  4385. )
  4386. # Optimize operations: if some files will be overwritten, we don't need to delete them first
  4387. if len(add_operations) > 0:
  4388. added_paths = set(op.path_in_repo for op in add_operations)
  4389. delete_operations = [
  4390. delete_op for delete_op in delete_operations if delete_op.path_in_repo not in added_paths
  4391. ]
  4392. commit_operations = delete_operations + add_operations
  4393. commit_message = commit_message or "Upload folder using huggingface_hub"
  4394. commit_info = self.create_commit(
  4395. repo_type=repo_type,
  4396. repo_id=repo_id,
  4397. operations=commit_operations,
  4398. commit_message=commit_message,
  4399. commit_description=commit_description,
  4400. token=token,
  4401. revision=revision,
  4402. create_pr=create_pr,
  4403. parent_commit=parent_commit,
  4404. )
  4405. # Create url to uploaded folder (for legacy return value)
  4406. if create_pr and commit_info.pr_url is not None:
  4407. revision = quote(_parse_revision_from_pr_url(commit_info.pr_url), safe="")
  4408. if repo_type in constants.REPO_TYPES_URL_PREFIXES:
  4409. repo_id = constants.REPO_TYPES_URL_PREFIXES[repo_type] + repo_id
  4410. revision = revision if revision is not None else constants.DEFAULT_REVISION
  4411. return CommitInfo(
  4412. commit_url=commit_info.commit_url,
  4413. commit_message=commit_info.commit_message,
  4414. commit_description=commit_info.commit_description,
  4415. oid=commit_info.oid,
  4416. pr_url=commit_info.pr_url,
  4417. # Similar to `hf_hub_url` but it's "tree" instead of "resolve"
  4418. # TODO: remove this in v1.0
  4419. _url=f"{self.endpoint}/{repo_id}/tree/{revision}/{path_in_repo}",
  4420. )
  4421. @validate_hf_hub_args
  4422. def delete_file(
  4423. self,
  4424. path_in_repo: str,
  4425. repo_id: str,
  4426. *,
  4427. token: Union[str, bool, None] = None,
  4428. repo_type: Optional[str] = None,
  4429. revision: Optional[str] = None,
  4430. commit_message: Optional[str] = None,
  4431. commit_description: Optional[str] = None,
  4432. create_pr: Optional[bool] = None,
  4433. parent_commit: Optional[str] = None,
  4434. ) -> CommitInfo:
  4435. """
  4436. Deletes a file in the given repo.
  4437. Args:
  4438. path_in_repo (`str`):
  4439. Relative filepath in the repo, for example:
  4440. `"checkpoints/1fec34a/weights.bin"`
  4441. repo_id (`str`):
  4442. The repository from which the file will be deleted, for example:
  4443. `"username/custom_transformers"`
  4444. token (`bool` or `str`, *optional*):
  4445. A valid user access token (string). Defaults to the locally saved
  4446. token, which is the recommended method for authentication (see
  4447. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4448. To disable authentication, pass `False`.
  4449. repo_type (`str`, *optional*):
  4450. Set to `"dataset"` or `"space"` if the file is in a dataset or
  4451. space, `None` or `"model"` if in a model. Default is `None`.
  4452. revision (`str`, *optional*):
  4453. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4454. commit_message (`str`, *optional*):
  4455. The summary / title / first line of the generated commit. Defaults to
  4456. `f"Delete {path_in_repo} with huggingface_hub"`.
  4457. commit_description (`str` *optional*)
  4458. The description of the generated commit
  4459. create_pr (`boolean`, *optional*):
  4460. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  4461. If `revision` is not set, PR is opened against the `"main"` branch. If
  4462. `revision` is set and is a branch, PR is opened against this branch. If
  4463. `revision` is set and is not a branch name (example: a commit oid), an
  4464. `RevisionNotFoundError` is returned by the server.
  4465. parent_commit (`str`, *optional*):
  4466. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  4467. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  4468. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  4469. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  4470. especially useful if the repo is updated / committed to concurrently.
  4471. > [!TIP]
  4472. > Raises the following errors:
  4473. >
  4474. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  4475. > if the HuggingFace API returned an error
  4476. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4477. > if some parameter value is invalid
  4478. > - [`~utils.RepositoryNotFoundError`]
  4479. > If the repository to download from cannot be found. This may be because it doesn't exist,
  4480. > or because it is set to `private` and you do not have access.
  4481. > - [`~utils.RevisionNotFoundError`]
  4482. > If the revision to download from cannot be found.
  4483. > - [`~utils.EntryNotFoundError`]
  4484. > If the file to download cannot be found.
  4485. """
  4486. commit_message = (
  4487. commit_message if commit_message is not None else f"Delete {path_in_repo} with huggingface_hub"
  4488. )
  4489. operations = [CommitOperationDelete(path_in_repo=path_in_repo)]
  4490. return self.create_commit(
  4491. repo_id=repo_id,
  4492. repo_type=repo_type,
  4493. token=token,
  4494. operations=operations,
  4495. revision=revision,
  4496. commit_message=commit_message,
  4497. commit_description=commit_description,
  4498. create_pr=create_pr,
  4499. parent_commit=parent_commit,
  4500. )
  4501. @validate_hf_hub_args
  4502. def delete_files(
  4503. self,
  4504. repo_id: str,
  4505. delete_patterns: List[str],
  4506. *,
  4507. token: Union[bool, str, None] = None,
  4508. repo_type: Optional[str] = None,
  4509. revision: Optional[str] = None,
  4510. commit_message: Optional[str] = None,
  4511. commit_description: Optional[str] = None,
  4512. create_pr: Optional[bool] = None,
  4513. parent_commit: Optional[str] = None,
  4514. ) -> CommitInfo:
  4515. """
  4516. Delete files from a repository on the Hub.
  4517. If a folder path is provided, the entire folder is deleted as well as
  4518. all files it contained.
  4519. Args:
  4520. repo_id (`str`):
  4521. The repository from which the folder will be deleted, for example:
  4522. `"username/custom_transformers"`
  4523. delete_patterns (`List[str]`):
  4524. List of files or folders to delete. Each string can either be
  4525. a file path, a folder path or a Unix shell-style wildcard.
  4526. E.g. `["file.txt", "folder/", "data/*.parquet"]`
  4527. token (`bool` or `str`, *optional*):
  4528. A valid user access token (string). Defaults to the locally saved
  4529. token, which is the recommended method for authentication (see
  4530. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4531. To disable authentication, pass `False`.
  4532. to the stored token.
  4533. repo_type (`str`, *optional*):
  4534. Type of the repo to delete files from. Can be `"model"`,
  4535. `"dataset"` or `"space"`. Defaults to `"model"`.
  4536. revision (`str`, *optional*):
  4537. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4538. commit_message (`str`, *optional*):
  4539. The summary (first line) of the generated commit. Defaults to
  4540. `f"Delete files using huggingface_hub"`.
  4541. commit_description (`str` *optional*)
  4542. The description of the generated commit.
  4543. create_pr (`boolean`, *optional*):
  4544. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  4545. If `revision` is not set, PR is opened against the `"main"` branch. If
  4546. `revision` is set and is a branch, PR is opened against this branch. If
  4547. `revision` is set and is not a branch name (example: a commit oid), an
  4548. `RevisionNotFoundError` is returned by the server.
  4549. parent_commit (`str`, *optional*):
  4550. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  4551. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  4552. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  4553. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  4554. especially useful if the repo is updated / committed to concurrently.
  4555. """
  4556. operations = self._prepare_folder_deletions(
  4557. repo_id=repo_id, repo_type=repo_type, delete_patterns=delete_patterns, path_in_repo="", revision=revision
  4558. )
  4559. if commit_message is None:
  4560. commit_message = f"Delete files {' '.join(delete_patterns)} with huggingface_hub"
  4561. return self.create_commit(
  4562. repo_id=repo_id,
  4563. repo_type=repo_type,
  4564. token=token,
  4565. operations=operations,
  4566. revision=revision,
  4567. commit_message=commit_message,
  4568. commit_description=commit_description,
  4569. create_pr=create_pr,
  4570. parent_commit=parent_commit,
  4571. )
  4572. @validate_hf_hub_args
  4573. def delete_folder(
  4574. self,
  4575. path_in_repo: str,
  4576. repo_id: str,
  4577. *,
  4578. token: Union[bool, str, None] = None,
  4579. repo_type: Optional[str] = None,
  4580. revision: Optional[str] = None,
  4581. commit_message: Optional[str] = None,
  4582. commit_description: Optional[str] = None,
  4583. create_pr: Optional[bool] = None,
  4584. parent_commit: Optional[str] = None,
  4585. ) -> CommitInfo:
  4586. """
  4587. Deletes a folder in the given repo.
  4588. Simple wrapper around [`create_commit`] method.
  4589. Args:
  4590. path_in_repo (`str`):
  4591. Relative folder path in the repo, for example: `"checkpoints/1fec34a"`.
  4592. repo_id (`str`):
  4593. The repository from which the folder will be deleted, for example:
  4594. `"username/custom_transformers"`
  4595. token (`bool` or `str`, *optional*):
  4596. A valid user access token (string). Defaults to the locally saved
  4597. token, which is the recommended method for authentication (see
  4598. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4599. To disable authentication, pass `False`.
  4600. to the stored token.
  4601. repo_type (`str`, *optional*):
  4602. Set to `"dataset"` or `"space"` if the folder is in a dataset or
  4603. space, `None` or `"model"` if in a model. Default is `None`.
  4604. revision (`str`, *optional*):
  4605. The git revision to commit from. Defaults to the head of the `"main"` branch.
  4606. commit_message (`str`, *optional*):
  4607. The summary / title / first line of the generated commit. Defaults to
  4608. `f"Delete folder {path_in_repo} with huggingface_hub"`.
  4609. commit_description (`str` *optional*)
  4610. The description of the generated commit.
  4611. create_pr (`boolean`, *optional*):
  4612. Whether or not to create a Pull Request with that commit. Defaults to `False`.
  4613. If `revision` is not set, PR is opened against the `"main"` branch. If
  4614. `revision` is set and is a branch, PR is opened against this branch. If
  4615. `revision` is set and is not a branch name (example: a commit oid), an
  4616. `RevisionNotFoundError` is returned by the server.
  4617. parent_commit (`str`, *optional*):
  4618. The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
  4619. If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
  4620. If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
  4621. Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
  4622. especially useful if the repo is updated / committed to concurrently.
  4623. """
  4624. return self.create_commit(
  4625. repo_id=repo_id,
  4626. repo_type=repo_type,
  4627. token=token,
  4628. operations=[CommitOperationDelete(path_in_repo=path_in_repo, is_folder=True)],
  4629. revision=revision,
  4630. commit_message=(
  4631. commit_message if commit_message is not None else f"Delete folder {path_in_repo} with huggingface_hub"
  4632. ),
  4633. commit_description=commit_description,
  4634. create_pr=create_pr,
  4635. parent_commit=parent_commit,
  4636. )
  4637. def upload_large_folder(
  4638. self,
  4639. repo_id: str,
  4640. folder_path: Union[str, Path],
  4641. *,
  4642. repo_type: str, # Repo type is required!
  4643. revision: Optional[str] = None,
  4644. private: Optional[bool] = None,
  4645. allow_patterns: Optional[Union[List[str], str]] = None,
  4646. ignore_patterns: Optional[Union[List[str], str]] = None,
  4647. num_workers: Optional[int] = None,
  4648. print_report: bool = True,
  4649. print_report_every: int = 60,
  4650. ) -> None:
  4651. """Upload a large folder to the Hub in the most resilient way possible.
  4652. Several workers are started to upload files in an optimized way. Before being committed to a repo, files must be
  4653. hashed and be pre-uploaded if they are LFS files. Workers will perform these tasks for each file in the folder.
  4654. At each step, some metadata information about the upload process is saved in the folder under `.cache/.huggingface/`
  4655. to be able to resume the process if interrupted. The whole process might result in several commits.
  4656. Args:
  4657. repo_id (`str`):
  4658. The repository to which the file will be uploaded.
  4659. E.g. `"HuggingFaceTB/smollm-corpus"`.
  4660. folder_path (`str` or `Path`):
  4661. Path to the folder to upload on the local file system.
  4662. repo_type (`str`):
  4663. Type of the repository. Must be one of `"model"`, `"dataset"` or `"space"`.
  4664. Unlike in all other `HfApi` methods, `repo_type` is explicitly required here. This is to avoid
  4665. any mistake when uploading a large folder to the Hub, and therefore prevent from having to re-upload
  4666. everything.
  4667. revision (`str`, `optional`):
  4668. The branch to commit to. If not provided, the `main` branch will be used.
  4669. private (`bool`, `optional`):
  4670. Whether the repository should be private.
  4671. If `None` (default), the repo will be public unless the organization's default is private.
  4672. allow_patterns (`List[str]` or `str`, *optional*):
  4673. If provided, only files matching at least one pattern are uploaded.
  4674. ignore_patterns (`List[str]` or `str`, *optional*):
  4675. If provided, files matching any of the patterns are not uploaded.
  4676. num_workers (`int`, *optional*):
  4677. Number of workers to start. Defaults to `os.cpu_count() - 2` (minimum 2).
  4678. A higher number of workers may speed up the process if your machine allows it. However, on machines with a
  4679. slower connection, it is recommended to keep the number of workers low to ensure better resumability.
  4680. Indeed, partially uploaded files will have to be completely re-uploaded if the process is interrupted.
  4681. print_report (`bool`, *optional*):
  4682. Whether to print a report of the upload progress. Defaults to True.
  4683. Report is printed to `sys.stdout` every X seconds (60 by defaults) and overwrites the previous report.
  4684. print_report_every (`int`, *optional*):
  4685. Frequency at which the report is printed. Defaults to 60 seconds.
  4686. > [!TIP]
  4687. > A few things to keep in mind:
  4688. > - Repository limits still apply: https://huggingface.co/docs/hub/repositories-recommendations
  4689. > - Do not start several processes in parallel.
  4690. > - You can interrupt and resume the process at any time.
  4691. > - Do not upload the same folder to several repositories. If you need to do so, you must delete the local `.cache/.huggingface/` folder first.
  4692. > [!WARNING]
  4693. > While being much more robust to upload large folders, `upload_large_folder` is more limited than [`upload_folder`] feature-wise. In practice:
  4694. > - you cannot set a custom `path_in_repo`. If you want to upload to a subfolder, you need to set the proper structure locally.
  4695. > - you cannot set a custom `commit_message` and `commit_description` since multiple commits are created.
  4696. > - you cannot delete from the repo while uploading. Please make a separate commit first.
  4697. > - 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`.
  4698. **Technical details:**
  4699. `upload_large_folder` process is as follow:
  4700. 1. (Check parameters and setup.)
  4701. 2. Create repo if missing.
  4702. 3. List local files to upload.
  4703. 4. Run validation checks and display warnings if repository limits might be exceeded:
  4704. - Warns if the total number of files exceeds 100k (recommended limit).
  4705. - Warns if any folder contains more than 10k files (recommended limit).
  4706. - Warns about files larger than 20GB (recommended) or 50GB (hard limit).
  4707. 5. Start workers. Workers can perform the following tasks:
  4708. - Hash a file.
  4709. - Get upload mode (regular or LFS) for a list of files.
  4710. - Pre-upload an LFS file.
  4711. - Commit a bunch of files.
  4712. Once a worker finishes a task, it will move on to the next task based on the priority list (see below) until
  4713. all files are uploaded and committed.
  4714. 6. While workers are up, regularly print a report to sys.stdout.
  4715. Order of priority:
  4716. 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file).
  4717. 2. Commit if at least 150 files are ready to commit.
  4718. 3. Get upload mode if at least 10 files have been hashed.
  4719. 4. Pre-upload LFS file if at least 1 file and no worker is pre-uploading.
  4720. 5. Hash file if at least 1 file and no worker is hashing.
  4721. 6. Get upload mode if at least 1 file and no worker is getting upload mode.
  4722. 7. Pre-upload LFS file if at least 1 file (exception: if hf_transfer is enabled, only 1 worker can preupload LFS at a time).
  4723. 8. Hash file if at least 1 file to hash.
  4724. 9. Get upload mode if at least 1 file to get upload mode.
  4725. 10. Commit if at least 1 file to commit and at least 1 min since last commit attempt.
  4726. 11. Commit if at least 1 file to commit and all other queues are empty.
  4727. Special rules:
  4728. - If `hf_transfer` is enabled, only 1 LFS uploader at a time. Otherwise the CPU would be bloated by `hf_transfer`.
  4729. - Only one worker can commit at a time.
  4730. - If no tasks are available, the worker waits for 10 seconds before checking again.
  4731. """
  4732. return upload_large_folder_internal(
  4733. self,
  4734. repo_id=repo_id,
  4735. folder_path=folder_path,
  4736. repo_type=repo_type,
  4737. revision=revision,
  4738. private=private,
  4739. allow_patterns=allow_patterns,
  4740. ignore_patterns=ignore_patterns,
  4741. num_workers=num_workers,
  4742. print_report=print_report,
  4743. print_report_every=print_report_every,
  4744. )
  4745. @validate_hf_hub_args
  4746. def get_hf_file_metadata(
  4747. self,
  4748. *,
  4749. url: str,
  4750. token: Union[bool, str, None] = None,
  4751. proxies: Optional[Dict] = None,
  4752. timeout: Optional[float] = constants.DEFAULT_REQUEST_TIMEOUT,
  4753. ) -> HfFileMetadata:
  4754. """Fetch metadata of a file versioned on the Hub for a given url.
  4755. Args:
  4756. url (`str`):
  4757. File url, for example returned by [`hf_hub_url`].
  4758. token (`bool` or `str`, *optional*):
  4759. A valid user access token (string). Defaults to the locally saved
  4760. token, which is the recommended method for authentication (see
  4761. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4762. To disable authentication, pass `False`.
  4763. proxies (`dict`, *optional*):
  4764. Dictionary mapping protocol to the URL of the proxy passed to `requests.request`.
  4765. timeout (`float`, *optional*, defaults to 10):
  4766. How many seconds to wait for the server to send metadata before giving up.
  4767. Returns:
  4768. A [`HfFileMetadata`] object containing metadata such as location, etag, size and commit_hash.
  4769. """
  4770. if token is None:
  4771. # Cannot do `token = token or self.token` as token can be `False`.
  4772. token = self.token
  4773. return get_hf_file_metadata(
  4774. url=url,
  4775. token=token,
  4776. proxies=proxies,
  4777. timeout=timeout,
  4778. library_name=self.library_name,
  4779. library_version=self.library_version,
  4780. user_agent=self.user_agent,
  4781. endpoint=self.endpoint,
  4782. )
  4783. @validate_hf_hub_args
  4784. def hf_hub_download(
  4785. self,
  4786. repo_id: str,
  4787. filename: str,
  4788. *,
  4789. subfolder: Optional[str] = None,
  4790. repo_type: Optional[str] = None,
  4791. revision: Optional[str] = None,
  4792. cache_dir: Union[str, Path, None] = None,
  4793. local_dir: Union[str, Path, None] = None,
  4794. force_download: bool = False,
  4795. proxies: Optional[Dict] = None,
  4796. etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
  4797. token: Union[bool, str, None] = None,
  4798. local_files_only: bool = False,
  4799. # Deprecated args
  4800. resume_download: Optional[bool] = None,
  4801. force_filename: Optional[str] = None,
  4802. local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto",
  4803. ) -> str:
  4804. """Download a given file if it's not already present in the local cache.
  4805. The new cache file layout looks like this:
  4806. - The cache directory contains one subfolder per repo_id (namespaced by repo type)
  4807. - inside each repo folder:
  4808. - refs is a list of the latest known revision => commit_hash pairs
  4809. - blobs contains the actual file blobs (identified by their git-sha or sha256, depending on
  4810. whether they're LFS files or not)
  4811. - snapshots contains one subfolder per commit, each "commit" contains the subset of the files
  4812. that have been resolved at that particular commit. Each filename is a symlink to the blob
  4813. at that particular commit.
  4814. ```
  4815. [ 96] .
  4816. └── [ 160] models--julien-c--EsperBERTo-small
  4817. ├── [ 160] blobs
  4818. │ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
  4819. │ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e
  4820. │ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812
  4821. ├── [ 96] refs
  4822. │ └── [ 40] main
  4823. └── [ 128] snapshots
  4824. ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
  4825. │ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
  4826. │ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
  4827. └── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48
  4828. ├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
  4829. └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
  4830. ```
  4831. If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
  4832. option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
  4833. to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
  4834. cache-system, it's optimized for regularly pulling the latest version of a repository.
  4835. Args:
  4836. repo_id (`str`):
  4837. A user or an organization name and a repo name separated by a `/`.
  4838. filename (`str`):
  4839. The name of the file in the repo.
  4840. subfolder (`str`, *optional*):
  4841. An optional value corresponding to a folder inside the repository.
  4842. repo_type (`str`, *optional*):
  4843. Set to `"dataset"` or `"space"` if downloading from a dataset or space,
  4844. `None` or `"model"` if downloading from a model. Default is `None`.
  4845. revision (`str`, *optional*):
  4846. An optional Git revision id which can be a branch name, a tag, or a
  4847. commit hash.
  4848. cache_dir (`str`, `Path`, *optional*):
  4849. Path to the folder where cached files are stored.
  4850. local_dir (`str` or `Path`, *optional*):
  4851. If provided, the downloaded file will be placed under this directory.
  4852. force_download (`bool`, *optional*, defaults to `False`):
  4853. Whether the file should be downloaded even if it already exists in
  4854. the local cache.
  4855. proxies (`dict`, *optional*):
  4856. Dictionary mapping protocol to the URL of the proxy passed to
  4857. `requests.request`.
  4858. etag_timeout (`float`, *optional*, defaults to `10`):
  4859. When fetching ETag, how many seconds to wait for the server to send
  4860. data before giving up which is passed to `requests.request`.
  4861. token (`bool` or `str`, *optional*):
  4862. A valid user access token (string). Defaults to the locally saved
  4863. token, which is the recommended method for authentication (see
  4864. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4865. To disable authentication, pass `False`.
  4866. local_files_only (`bool`, *optional*, defaults to `False`):
  4867. If `True`, avoid downloading the file and return the path to the
  4868. local cached file if it exists.
  4869. Returns:
  4870. `str`: Local path of file or if networking is off, last version of file cached on disk.
  4871. Raises:
  4872. [`~utils.RepositoryNotFoundError`]
  4873. If the repository to download from cannot be found. This may be because it doesn't exist,
  4874. or because it is set to `private` and you do not have access.
  4875. [`~utils.RevisionNotFoundError`]
  4876. If the revision to download from cannot be found.
  4877. [`~utils.EntryNotFoundError`]
  4878. If the file to download cannot be found.
  4879. [`~utils.LocalEntryNotFoundError`]
  4880. If network is disabled or unavailable and file is not found in cache.
  4881. [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
  4882. If `token=True` but the token cannot be found.
  4883. [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
  4884. If ETag cannot be determined.
  4885. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  4886. If some parameter value is invalid.
  4887. """
  4888. from .file_download import hf_hub_download
  4889. if token is None:
  4890. # Cannot do `token = token or self.token` as token can be `False`.
  4891. token = self.token
  4892. return hf_hub_download(
  4893. repo_id=repo_id,
  4894. filename=filename,
  4895. subfolder=subfolder,
  4896. repo_type=repo_type,
  4897. revision=revision,
  4898. endpoint=self.endpoint,
  4899. library_name=self.library_name,
  4900. library_version=self.library_version,
  4901. cache_dir=cache_dir,
  4902. local_dir=local_dir,
  4903. local_dir_use_symlinks=local_dir_use_symlinks,
  4904. user_agent=self.user_agent,
  4905. force_download=force_download,
  4906. force_filename=force_filename,
  4907. proxies=proxies,
  4908. etag_timeout=etag_timeout,
  4909. resume_download=resume_download,
  4910. token=token,
  4911. headers=self.headers,
  4912. local_files_only=local_files_only,
  4913. )
  4914. @validate_hf_hub_args
  4915. def snapshot_download(
  4916. self,
  4917. repo_id: str,
  4918. *,
  4919. repo_type: Optional[str] = None,
  4920. revision: Optional[str] = None,
  4921. cache_dir: Union[str, Path, None] = None,
  4922. local_dir: Union[str, Path, None] = None,
  4923. proxies: Optional[Dict] = None,
  4924. etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
  4925. force_download: bool = False,
  4926. token: Union[bool, str, None] = None,
  4927. local_files_only: bool = False,
  4928. allow_patterns: Optional[Union[List[str], str]] = None,
  4929. ignore_patterns: Optional[Union[List[str], str]] = None,
  4930. max_workers: int = 8,
  4931. tqdm_class: Optional[Type[base_tqdm]] = None,
  4932. # Deprecated args
  4933. local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto",
  4934. resume_download: Optional[bool] = None,
  4935. ) -> str:
  4936. """Download repo files.
  4937. Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from
  4938. a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order
  4939. to keep their actual filename relative to that folder. You can also filter which files to download using
  4940. `allow_patterns` and `ignore_patterns`.
  4941. If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
  4942. option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
  4943. to store some metadata related to the downloaded files.While this mechanism is not as robust as the main
  4944. cache-system, it's optimized for regularly pulling the latest version of a repository.
  4945. An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly
  4946. configured. It is also not possible to filter which files to download when cloning a repository using git.
  4947. Args:
  4948. repo_id (`str`):
  4949. A user or an organization name and a repo name separated by a `/`.
  4950. repo_type (`str`, *optional*):
  4951. Set to `"dataset"` or `"space"` if downloading from a dataset or space,
  4952. `None` or `"model"` if downloading from a model. Default is `None`.
  4953. revision (`str`, *optional*):
  4954. An optional Git revision id which can be a branch name, a tag, or a
  4955. commit hash.
  4956. cache_dir (`str`, `Path`, *optional*):
  4957. Path to the folder where cached files are stored.
  4958. local_dir (`str` or `Path`, *optional*):
  4959. If provided, the downloaded files will be placed under this directory.
  4960. proxies (`dict`, *optional*):
  4961. Dictionary mapping protocol to the URL of the proxy passed to
  4962. `requests.request`.
  4963. etag_timeout (`float`, *optional*, defaults to `10`):
  4964. When fetching ETag, how many seconds to wait for the server to send
  4965. data before giving up which is passed to `requests.request`.
  4966. force_download (`bool`, *optional*, defaults to `False`):
  4967. Whether the file should be downloaded even if it already exists in the local cache.
  4968. token (`bool` or `str`, *optional*):
  4969. A valid user access token (string). Defaults to the locally saved
  4970. token, which is the recommended method for authentication (see
  4971. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  4972. To disable authentication, pass `False`.
  4973. local_files_only (`bool`, *optional*, defaults to `False`):
  4974. If `True`, avoid downloading the file and return the path to the
  4975. local cached file if it exists.
  4976. allow_patterns (`List[str]` or `str`, *optional*):
  4977. If provided, only files matching at least one pattern are downloaded.
  4978. ignore_patterns (`List[str]` or `str`, *optional*):
  4979. If provided, files matching any of the patterns are not downloaded.
  4980. max_workers (`int`, *optional*):
  4981. Number of concurrent threads to download files (1 thread = 1 file download).
  4982. Defaults to 8.
  4983. tqdm_class (`tqdm`, *optional*):
  4984. If provided, overwrites the default behavior for the progress bar. Passed
  4985. argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
  4986. Note that the `tqdm_class` is not passed to each individual download.
  4987. Defaults to the custom HF progress bar that can be disabled by setting
  4988. `HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
  4989. Returns:
  4990. `str`: folder path of the repo snapshot.
  4991. Raises:
  4992. [`~utils.RepositoryNotFoundError`]
  4993. If the repository to download from cannot be found. This may be because it doesn't exist,
  4994. or because it is set to `private` and you do not have access.
  4995. [`~utils.RevisionNotFoundError`]
  4996. If the revision to download from cannot be found.
  4997. [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
  4998. If `token=True` and the token cannot be found.
  4999. [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if
  5000. ETag cannot be determined.
  5001. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5002. if some parameter value is invalid.
  5003. """
  5004. from ._snapshot_download import snapshot_download
  5005. if token is None:
  5006. # Cannot do `token = token or self.token` as token can be `False`.
  5007. token = self.token
  5008. return snapshot_download(
  5009. repo_id=repo_id,
  5010. repo_type=repo_type,
  5011. revision=revision,
  5012. endpoint=self.endpoint,
  5013. cache_dir=cache_dir,
  5014. local_dir=local_dir,
  5015. local_dir_use_symlinks=local_dir_use_symlinks,
  5016. library_name=self.library_name,
  5017. library_version=self.library_version,
  5018. user_agent=self.user_agent,
  5019. proxies=proxies,
  5020. etag_timeout=etag_timeout,
  5021. resume_download=resume_download,
  5022. force_download=force_download,
  5023. token=token,
  5024. local_files_only=local_files_only,
  5025. allow_patterns=allow_patterns,
  5026. ignore_patterns=ignore_patterns,
  5027. max_workers=max_workers,
  5028. tqdm_class=tqdm_class,
  5029. )
  5030. def get_safetensors_metadata(
  5031. self,
  5032. repo_id: str,
  5033. *,
  5034. repo_type: Optional[str] = None,
  5035. revision: Optional[str] = None,
  5036. token: Union[bool, str, None] = None,
  5037. ) -> SafetensorsRepoMetadata:
  5038. """
  5039. Parse metadata for a safetensors repo on the Hub.
  5040. We first check if the repo has a single safetensors file or a sharded safetensors repo. If it's a single
  5041. safetensors file, we parse the metadata from this file. If it's a sharded safetensors repo, we parse the
  5042. metadata from the index file and then parse the metadata from each shard.
  5043. To parse metadata from a single safetensors file, use [`parse_safetensors_file_metadata`].
  5044. For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
  5045. Args:
  5046. repo_id (`str`):
  5047. A user or an organization name and a repo name separated by a `/`.
  5048. repo_type (`str`, *optional*):
  5049. Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
  5050. model. Default is `None`.
  5051. revision (`str`, *optional*):
  5052. The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
  5053. head of the `"main"` branch.
  5054. token (`bool` or `str`, *optional*):
  5055. A valid user access token (string). Defaults to the locally saved
  5056. token, which is the recommended method for authentication (see
  5057. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5058. To disable authentication, pass `False`.
  5059. Returns:
  5060. [`SafetensorsRepoMetadata`]: information related to safetensors repo.
  5061. Raises:
  5062. [`NotASafetensorsRepoError`]
  5063. If the repo is not a safetensors repo i.e. doesn't have either a
  5064. `model.safetensors` or a `model.safetensors.index.json` file.
  5065. [`SafetensorsParsingError`]
  5066. If a safetensors file header couldn't be parsed correctly.
  5067. Example:
  5068. ```py
  5069. # Parse repo with single weights file
  5070. >>> metadata = get_safetensors_metadata("bigscience/bloomz-560m")
  5071. >>> metadata
  5072. SafetensorsRepoMetadata(
  5073. metadata=None,
  5074. sharded=False,
  5075. weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...},
  5076. files_metadata={'model.safetensors': SafetensorsFileMetadata(...)}
  5077. )
  5078. >>> metadata.files_metadata["model.safetensors"].metadata
  5079. {'format': 'pt'}
  5080. # Parse repo with sharded model
  5081. >>> metadata = get_safetensors_metadata("bigscience/bloom")
  5082. Parse safetensors files: 100%|██████████████████████████████████████████| 72/72 [00:12<00:00, 5.78it/s]
  5083. >>> metadata
  5084. SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...})
  5085. >>> len(metadata.files_metadata)
  5086. 72 # All safetensors files have been fetched
  5087. # Parse repo with sharded model
  5088. >>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5")
  5089. NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files.
  5090. ```
  5091. """
  5092. if self.file_exists( # Single safetensors file => non-sharded model
  5093. repo_id=repo_id,
  5094. filename=constants.SAFETENSORS_SINGLE_FILE,
  5095. repo_type=repo_type,
  5096. revision=revision,
  5097. token=token,
  5098. ):
  5099. file_metadata = self.parse_safetensors_file_metadata(
  5100. repo_id=repo_id,
  5101. filename=constants.SAFETENSORS_SINGLE_FILE,
  5102. repo_type=repo_type,
  5103. revision=revision,
  5104. token=token,
  5105. )
  5106. return SafetensorsRepoMetadata(
  5107. metadata=None,
  5108. sharded=False,
  5109. weight_map={
  5110. tensor_name: constants.SAFETENSORS_SINGLE_FILE for tensor_name in file_metadata.tensors.keys()
  5111. },
  5112. files_metadata={constants.SAFETENSORS_SINGLE_FILE: file_metadata},
  5113. )
  5114. elif self.file_exists( # Multiple safetensors files => sharded with index
  5115. repo_id=repo_id,
  5116. filename=constants.SAFETENSORS_INDEX_FILE,
  5117. repo_type=repo_type,
  5118. revision=revision,
  5119. token=token,
  5120. ):
  5121. # Fetch index
  5122. index_file = self.hf_hub_download(
  5123. repo_id=repo_id,
  5124. filename=constants.SAFETENSORS_INDEX_FILE,
  5125. repo_type=repo_type,
  5126. revision=revision,
  5127. token=token,
  5128. )
  5129. with open(index_file) as f:
  5130. index = json.load(f)
  5131. weight_map = index.get("weight_map", {})
  5132. # Fetch metadata per shard
  5133. files_metadata = {}
  5134. def _parse(filename: str) -> None:
  5135. files_metadata[filename] = self.parse_safetensors_file_metadata(
  5136. repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, token=token
  5137. )
  5138. thread_map(
  5139. _parse,
  5140. set(weight_map.values()),
  5141. desc="Parse safetensors files",
  5142. tqdm_class=hf_tqdm,
  5143. )
  5144. return SafetensorsRepoMetadata(
  5145. metadata=index.get("metadata", None),
  5146. sharded=True,
  5147. weight_map=weight_map,
  5148. files_metadata=files_metadata,
  5149. )
  5150. else:
  5151. # Not a safetensors repo
  5152. raise NotASafetensorsRepoError(
  5153. f"'{repo_id}' is not a safetensors repo. Couldn't find '{constants.SAFETENSORS_INDEX_FILE}' or '{constants.SAFETENSORS_SINGLE_FILE}' files."
  5154. )
  5155. def parse_safetensors_file_metadata(
  5156. self,
  5157. repo_id: str,
  5158. filename: str,
  5159. *,
  5160. repo_type: Optional[str] = None,
  5161. revision: Optional[str] = None,
  5162. token: Union[bool, str, None] = None,
  5163. ) -> SafetensorsFileMetadata:
  5164. """
  5165. Parse metadata from a safetensors file on the Hub.
  5166. To parse metadata from all safetensors files in a repo at once, use [`get_safetensors_metadata`].
  5167. For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
  5168. Args:
  5169. repo_id (`str`):
  5170. A user or an organization name and a repo name separated by a `/`.
  5171. filename (`str`):
  5172. The name of the file in the repo.
  5173. repo_type (`str`, *optional*):
  5174. Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
  5175. model. Default is `None`.
  5176. revision (`str`, *optional*):
  5177. The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
  5178. head of the `"main"` branch.
  5179. token (`bool` or `str`, *optional*):
  5180. A valid user access token (string). Defaults to the locally saved
  5181. token, which is the recommended method for authentication (see
  5182. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5183. To disable authentication, pass `False`.
  5184. Returns:
  5185. [`SafetensorsFileMetadata`]: information related to a safetensors file.
  5186. Raises:
  5187. [`NotASafetensorsRepoError`]:
  5188. If the repo is not a safetensors repo i.e. doesn't have either a
  5189. `model.safetensors` or a `model.safetensors.index.json` file.
  5190. [`SafetensorsParsingError`]:
  5191. If a safetensors file header couldn't be parsed correctly.
  5192. """
  5193. url = hf_hub_url(
  5194. repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, endpoint=self.endpoint
  5195. )
  5196. _headers = self._build_hf_headers(token=token)
  5197. # 1. Fetch first 100kb
  5198. # Empirically, 97% of safetensors files have a metadata size < 100kb (over the top 1000 models on the Hub).
  5199. # We assume fetching 100kb is faster than making 2 GET requests. Therefore we always fetch the first 100kb to
  5200. # avoid the 2nd GET in most cases.
  5201. # See https://github.com/huggingface/huggingface_hub/pull/1855#discussion_r1404286419.
  5202. response = get_session().get(url, headers={**_headers, "range": "bytes=0-100000"})
  5203. hf_raise_for_status(response)
  5204. # 2. Parse metadata size
  5205. metadata_size = struct.unpack("<Q", response.content[:8])[0]
  5206. if metadata_size > constants.SAFETENSORS_MAX_HEADER_LENGTH:
  5207. raise SafetensorsParsingError(
  5208. f"Failed to parse safetensors header for '{filename}' (repo '{repo_id}', revision "
  5209. f"'{revision or constants.DEFAULT_REVISION}'): safetensors header is too big. Maximum supported size is "
  5210. f"{constants.SAFETENSORS_MAX_HEADER_LENGTH} bytes (got {metadata_size})."
  5211. )
  5212. # 3.a. Get metadata from payload
  5213. if metadata_size <= 100000:
  5214. metadata_as_bytes = response.content[8 : 8 + metadata_size]
  5215. else: # 3.b. Request full metadata
  5216. response = get_session().get(url, headers={**_headers, "range": f"bytes=8-{metadata_size + 7}"})
  5217. hf_raise_for_status(response)
  5218. metadata_as_bytes = response.content
  5219. # 4. Parse json header
  5220. try:
  5221. metadata_as_dict = json.loads(metadata_as_bytes.decode(errors="ignore"))
  5222. except json.JSONDecodeError as e:
  5223. raise SafetensorsParsingError(
  5224. f"Failed to parse safetensors header for '{filename}' (repo '{repo_id}', revision "
  5225. f"'{revision or constants.DEFAULT_REVISION}'): header is not json-encoded string. Please make sure this is a "
  5226. "correctly formatted safetensors file."
  5227. ) from e
  5228. try:
  5229. return SafetensorsFileMetadata(
  5230. metadata=metadata_as_dict.get("__metadata__", {}),
  5231. tensors={
  5232. key: TensorInfo(
  5233. dtype=tensor["dtype"],
  5234. shape=tensor["shape"],
  5235. data_offsets=tuple(tensor["data_offsets"]), # type: ignore
  5236. )
  5237. for key, tensor in metadata_as_dict.items()
  5238. if key != "__metadata__"
  5239. },
  5240. )
  5241. except (KeyError, IndexError) as e:
  5242. raise SafetensorsParsingError(
  5243. f"Failed to parse safetensors header for '{filename}' (repo '{repo_id}', revision "
  5244. f"'{revision or constants.DEFAULT_REVISION}'): header format not recognized. Please make sure this is a correctly"
  5245. " formatted safetensors file."
  5246. ) from e
  5247. @validate_hf_hub_args
  5248. def create_branch(
  5249. self,
  5250. repo_id: str,
  5251. *,
  5252. branch: str,
  5253. revision: Optional[str] = None,
  5254. token: Union[bool, str, None] = None,
  5255. repo_type: Optional[str] = None,
  5256. exist_ok: bool = False,
  5257. ) -> None:
  5258. """
  5259. Create a new branch for a repo on the Hub, starting from the specified revision (defaults to `main`).
  5260. To find a revision suiting your needs, you can use [`list_repo_refs`] or [`list_repo_commits`].
  5261. Args:
  5262. repo_id (`str`):
  5263. The repository in which the branch will be created.
  5264. Example: `"user/my-cool-model"`.
  5265. branch (`str`):
  5266. The name of the branch to create.
  5267. revision (`str`, *optional*):
  5268. The git revision to create the branch from. It can be a branch name or
  5269. the OID/SHA of a commit, as a hexadecimal string. Defaults to the head
  5270. of the `"main"` branch.
  5271. token (`bool` or `str`, *optional*):
  5272. A valid user access token (string). Defaults to the locally saved
  5273. token, which is the recommended method for authentication (see
  5274. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5275. To disable authentication, pass `False`.
  5276. repo_type (`str`, *optional*):
  5277. Set to `"dataset"` or `"space"` if creating a branch on a dataset or
  5278. space, `None` or `"model"` if tagging a model. Default is `None`.
  5279. exist_ok (`bool`, *optional*, defaults to `False`):
  5280. If `True`, do not raise an error if branch already exists.
  5281. Raises:
  5282. [`~utils.RepositoryNotFoundError`]:
  5283. If repository is not found (error 404): wrong repo_id/repo_type, private
  5284. but not authenticated or repo does not exist.
  5285. [`~utils.BadRequestError`]:
  5286. If invalid reference for a branch. Ex: `refs/pr/5` or 'refs/foo/bar'.
  5287. [`~utils.HfHubHTTPError`]:
  5288. If the branch already exists on the repo (error 409) and `exist_ok` is
  5289. set to `False`.
  5290. """
  5291. if repo_type is None:
  5292. repo_type = constants.REPO_TYPE_MODEL
  5293. branch = quote(branch, safe="")
  5294. # Prepare request
  5295. branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}"
  5296. headers = self._build_hf_headers(token=token)
  5297. payload = {}
  5298. if revision is not None:
  5299. payload["startingPoint"] = revision
  5300. # Create branch
  5301. response = get_session().post(url=branch_url, headers=headers, json=payload)
  5302. try:
  5303. hf_raise_for_status(response)
  5304. except HfHubHTTPError as e:
  5305. if exist_ok and e.response.status_code == 409:
  5306. return
  5307. elif exist_ok and e.response.status_code == 403:
  5308. # No write permission on the namespace but branch might already exist
  5309. try:
  5310. refs = self.list_repo_refs(repo_id=repo_id, repo_type=repo_type, token=token)
  5311. for branch_ref in refs.branches:
  5312. if branch_ref.name == branch:
  5313. return # Branch already exists => do not raise
  5314. except HfHubHTTPError:
  5315. pass # We raise the original error if the branch does not exist
  5316. raise
  5317. @validate_hf_hub_args
  5318. def delete_branch(
  5319. self,
  5320. repo_id: str,
  5321. *,
  5322. branch: str,
  5323. token: Union[bool, str, None] = None,
  5324. repo_type: Optional[str] = None,
  5325. ) -> None:
  5326. """
  5327. Delete a branch from a repo on the Hub.
  5328. Args:
  5329. repo_id (`str`):
  5330. The repository in which a branch will be deleted.
  5331. Example: `"user/my-cool-model"`.
  5332. branch (`str`):
  5333. The name of the branch to delete.
  5334. token (`bool` or `str`, *optional*):
  5335. A valid user access token (string). Defaults to the locally saved
  5336. token, which is the recommended method for authentication (see
  5337. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5338. To disable authentication, pass `False`.
  5339. repo_type (`str`, *optional*):
  5340. Set to `"dataset"` or `"space"` if creating a branch on a dataset or
  5341. space, `None` or `"model"` if tagging a model. Default is `None`.
  5342. Raises:
  5343. [`~utils.RepositoryNotFoundError`]:
  5344. If repository is not found (error 404): wrong repo_id/repo_type, private
  5345. but not authenticated or repo does not exist.
  5346. [`~utils.HfHubHTTPError`]:
  5347. If trying to delete a protected branch. Ex: `main` cannot be deleted.
  5348. [`~utils.HfHubHTTPError`]:
  5349. If trying to delete a branch that does not exist.
  5350. """
  5351. if repo_type is None:
  5352. repo_type = constants.REPO_TYPE_MODEL
  5353. branch = quote(branch, safe="")
  5354. # Prepare request
  5355. branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}"
  5356. headers = self._build_hf_headers(token=token)
  5357. # Delete branch
  5358. response = get_session().delete(url=branch_url, headers=headers)
  5359. hf_raise_for_status(response)
  5360. @validate_hf_hub_args
  5361. def create_tag(
  5362. self,
  5363. repo_id: str,
  5364. *,
  5365. tag: str,
  5366. tag_message: Optional[str] = None,
  5367. revision: Optional[str] = None,
  5368. token: Union[bool, str, None] = None,
  5369. repo_type: Optional[str] = None,
  5370. exist_ok: bool = False,
  5371. ) -> None:
  5372. """
  5373. Tag a given commit of a repo on the Hub.
  5374. Args:
  5375. repo_id (`str`):
  5376. The repository in which a commit will be tagged.
  5377. Example: `"user/my-cool-model"`.
  5378. tag (`str`):
  5379. The name of the tag to create.
  5380. tag_message (`str`, *optional*):
  5381. The description of the tag to create.
  5382. revision (`str`, *optional*):
  5383. The git revision to tag. It can be a branch name or the OID/SHA of a
  5384. commit, as a hexadecimal string. Shorthands (7 first characters) are
  5385. also supported. Defaults to the head of the `"main"` branch.
  5386. token (`bool` or `str`, *optional*):
  5387. A valid user access token (string). Defaults to the locally saved
  5388. token, which is the recommended method for authentication (see
  5389. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5390. To disable authentication, pass `False`.
  5391. repo_type (`str`, *optional*):
  5392. Set to `"dataset"` or `"space"` if tagging a dataset or
  5393. space, `None` or `"model"` if tagging a model. Default is
  5394. `None`.
  5395. exist_ok (`bool`, *optional*, defaults to `False`):
  5396. If `True`, do not raise an error if tag already exists.
  5397. Raises:
  5398. [`~utils.RepositoryNotFoundError`]:
  5399. If repository is not found (error 404): wrong repo_id/repo_type, private
  5400. but not authenticated or repo does not exist.
  5401. [`~utils.RevisionNotFoundError`]:
  5402. If revision is not found (error 404) on the repo.
  5403. [`~utils.HfHubHTTPError`]:
  5404. If the branch already exists on the repo (error 409) and `exist_ok` is
  5405. set to `False`.
  5406. """
  5407. if repo_type is None:
  5408. repo_type = constants.REPO_TYPE_MODEL
  5409. revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION
  5410. # Prepare request
  5411. tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{revision}"
  5412. headers = self._build_hf_headers(token=token)
  5413. payload = {"tag": tag}
  5414. if tag_message is not None:
  5415. payload["message"] = tag_message
  5416. # Tag
  5417. response = get_session().post(url=tag_url, headers=headers, json=payload)
  5418. try:
  5419. hf_raise_for_status(response)
  5420. except HfHubHTTPError as e:
  5421. if not (e.response.status_code == 409 and exist_ok):
  5422. raise
  5423. @validate_hf_hub_args
  5424. def delete_tag(
  5425. self,
  5426. repo_id: str,
  5427. *,
  5428. tag: str,
  5429. token: Union[bool, str, None] = None,
  5430. repo_type: Optional[str] = None,
  5431. ) -> None:
  5432. """
  5433. Delete a tag from a repo on the Hub.
  5434. Args:
  5435. repo_id (`str`):
  5436. The repository in which a tag will be deleted.
  5437. Example: `"user/my-cool-model"`.
  5438. tag (`str`):
  5439. The name of the tag to delete.
  5440. token (`bool` or `str`, *optional*):
  5441. A valid user access token (string). Defaults to the locally saved
  5442. token, which is the recommended method for authentication (see
  5443. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5444. To disable authentication, pass `False`.
  5445. repo_type (`str`, *optional*):
  5446. Set to `"dataset"` or `"space"` if tagging a dataset or space, `None` or
  5447. `"model"` if tagging a model. Default is `None`.
  5448. Raises:
  5449. [`~utils.RepositoryNotFoundError`]:
  5450. If repository is not found (error 404): wrong repo_id/repo_type, private
  5451. but not authenticated or repo does not exist.
  5452. [`~utils.RevisionNotFoundError`]:
  5453. If tag is not found.
  5454. """
  5455. if repo_type is None:
  5456. repo_type = constants.REPO_TYPE_MODEL
  5457. tag = quote(tag, safe="")
  5458. # Prepare request
  5459. tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{tag}"
  5460. headers = self._build_hf_headers(token=token)
  5461. # Un-tag
  5462. response = get_session().delete(url=tag_url, headers=headers)
  5463. hf_raise_for_status(response)
  5464. @validate_hf_hub_args
  5465. def get_full_repo_name(
  5466. self,
  5467. model_id: str,
  5468. *,
  5469. organization: Optional[str] = None,
  5470. token: Union[bool, str, None] = None,
  5471. ):
  5472. """
  5473. Returns the repository name for a given model ID and optional
  5474. organization.
  5475. Args:
  5476. model_id (`str`):
  5477. The name of the model.
  5478. organization (`str`, *optional*):
  5479. If passed, the repository name will be in the organization
  5480. namespace instead of the user namespace.
  5481. token (`bool` or `str`, *optional*):
  5482. A valid user access token (string). Defaults to the locally saved
  5483. token, which is the recommended method for authentication (see
  5484. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5485. To disable authentication, pass `False`.
  5486. Returns:
  5487. `str`: The repository name in the user's namespace
  5488. ({username}/{model_id}) if no organization is passed, and under the
  5489. organization namespace ({organization}/{model_id}) otherwise.
  5490. """
  5491. if organization is None:
  5492. if "/" in model_id:
  5493. username = model_id.split("/")[0]
  5494. else:
  5495. username = self.whoami(token=token)["name"] # type: ignore
  5496. return f"{username}/{model_id}"
  5497. else:
  5498. return f"{organization}/{model_id}"
  5499. @validate_hf_hub_args
  5500. def get_repo_discussions(
  5501. self,
  5502. repo_id: str,
  5503. *,
  5504. author: Optional[str] = None,
  5505. discussion_type: Optional[constants.DiscussionTypeFilter] = None,
  5506. discussion_status: Optional[constants.DiscussionStatusFilter] = None,
  5507. repo_type: Optional[str] = None,
  5508. token: Union[bool, str, None] = None,
  5509. ) -> Iterator[Discussion]:
  5510. """
  5511. Fetches Discussions and Pull Requests for the given repo.
  5512. Args:
  5513. repo_id (`str`):
  5514. A namespace (user or an organization) and a repo name separated
  5515. by a `/`.
  5516. author (`str`, *optional*):
  5517. Pass a value to filter by discussion author. `None` means no filter.
  5518. Default is `None`.
  5519. discussion_type (`str`, *optional*):
  5520. Set to `"pull_request"` to fetch only pull requests, `"discussion"`
  5521. to fetch only discussions. Set to `"all"` or `None` to fetch both.
  5522. Default is `None`.
  5523. discussion_status (`str`, *optional*):
  5524. Set to `"open"` (respectively `"closed"`) to fetch only open
  5525. (respectively closed) discussions. Set to `"all"` or `None`
  5526. to fetch both.
  5527. Default is `None`.
  5528. repo_type (`str`, *optional*):
  5529. Set to `"dataset"` or `"space"` if fetching from a dataset or
  5530. space, `None` or `"model"` if fetching from a model. Default is
  5531. `None`.
  5532. token (`bool` or `str`, *optional*):
  5533. A valid user access token (string). Defaults to the locally saved
  5534. token, which is the recommended method for authentication (see
  5535. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5536. To disable authentication, pass `False`.
  5537. Returns:
  5538. `Iterator[Discussion]`: An iterator of [`Discussion`] objects.
  5539. Example:
  5540. Collecting all discussions of a repo in a list:
  5541. ```python
  5542. >>> from huggingface_hub import get_repo_discussions
  5543. >>> discussions_list = list(get_repo_discussions(repo_id="bert-base-uncased"))
  5544. ```
  5545. Iterating over discussions of a repo:
  5546. ```python
  5547. >>> from huggingface_hub import get_repo_discussions
  5548. >>> for discussion in get_repo_discussions(repo_id="bert-base-uncased"):
  5549. ... print(discussion.num, discussion.title)
  5550. ```
  5551. """
  5552. if repo_type not in constants.REPO_TYPES:
  5553. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  5554. if repo_type is None:
  5555. repo_type = constants.REPO_TYPE_MODEL
  5556. if discussion_type is not None and discussion_type not in constants.DISCUSSION_TYPES:
  5557. raise ValueError(f"Invalid discussion_type, must be one of {constants.DISCUSSION_TYPES}")
  5558. if discussion_status is not None and discussion_status not in constants.DISCUSSION_STATUS:
  5559. raise ValueError(f"Invalid discussion_status, must be one of {constants.DISCUSSION_STATUS}")
  5560. headers = self._build_hf_headers(token=token)
  5561. path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions"
  5562. params: Dict[str, Union[str, int]] = {}
  5563. if discussion_type is not None:
  5564. params["type"] = discussion_type
  5565. if discussion_status is not None:
  5566. params["status"] = discussion_status
  5567. if author is not None:
  5568. params["author"] = author
  5569. def _fetch_discussion_page(page_index: int):
  5570. params["p"] = page_index
  5571. resp = get_session().get(path, headers=headers, params=params)
  5572. hf_raise_for_status(resp)
  5573. paginated_discussions = resp.json()
  5574. total = paginated_discussions["count"]
  5575. start = paginated_discussions["start"]
  5576. discussions = paginated_discussions["discussions"]
  5577. has_next = (start + len(discussions)) < total
  5578. return discussions, has_next
  5579. has_next, page_index = True, 0
  5580. while has_next:
  5581. discussions, has_next = _fetch_discussion_page(page_index=page_index)
  5582. for discussion in discussions:
  5583. yield Discussion(
  5584. title=discussion["title"],
  5585. num=discussion["num"],
  5586. author=discussion.get("author", {}).get("name", "deleted"),
  5587. created_at=parse_datetime(discussion["createdAt"]),
  5588. status=discussion["status"],
  5589. repo_id=discussion["repo"]["name"],
  5590. repo_type=discussion["repo"]["type"],
  5591. is_pull_request=discussion["isPullRequest"],
  5592. endpoint=self.endpoint,
  5593. )
  5594. page_index = page_index + 1
  5595. @validate_hf_hub_args
  5596. def get_discussion_details(
  5597. self,
  5598. repo_id: str,
  5599. discussion_num: int,
  5600. *,
  5601. repo_type: Optional[str] = None,
  5602. token: Union[bool, str, None] = None,
  5603. ) -> DiscussionWithDetails:
  5604. """Fetches a Discussion's / Pull Request 's details from the Hub.
  5605. Args:
  5606. repo_id (`str`):
  5607. A namespace (user or an organization) and a repo name separated
  5608. by a `/`.
  5609. discussion_num (`int`):
  5610. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  5611. repo_type (`str`, *optional*):
  5612. Set to `"dataset"` or `"space"` if uploading to a dataset or
  5613. space, `None` or `"model"` if uploading to a model. Default is
  5614. `None`.
  5615. token (`bool` or `str`, *optional*):
  5616. A valid user access token (string). Defaults to the locally saved
  5617. token, which is the recommended method for authentication (see
  5618. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5619. To disable authentication, pass `False`.
  5620. Returns: [`DiscussionWithDetails`]
  5621. > [!TIP]
  5622. > Raises the following errors:
  5623. >
  5624. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  5625. > if the HuggingFace API returned an error
  5626. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5627. > if some parameter value is invalid
  5628. > - [`~utils.RepositoryNotFoundError`]
  5629. > If the repository to download from cannot be found. This may be because it doesn't exist,
  5630. > or because it is set to `private` and you do not have access.
  5631. """
  5632. if not isinstance(discussion_num, int) or discussion_num <= 0:
  5633. raise ValueError("Invalid discussion_num, must be a positive integer")
  5634. if repo_type not in constants.REPO_TYPES:
  5635. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  5636. if repo_type is None:
  5637. repo_type = constants.REPO_TYPE_MODEL
  5638. path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions/{discussion_num}"
  5639. headers = self._build_hf_headers(token=token)
  5640. resp = get_session().get(path, params={"diff": "1"}, headers=headers)
  5641. hf_raise_for_status(resp)
  5642. discussion_details = resp.json()
  5643. is_pull_request = discussion_details["isPullRequest"]
  5644. target_branch = discussion_details["changes"]["base"] if is_pull_request else None
  5645. conflicting_files = discussion_details["filesWithConflicts"] if is_pull_request else None
  5646. merge_commit_oid = discussion_details["changes"].get("mergeCommitId", None) if is_pull_request else None
  5647. return DiscussionWithDetails(
  5648. title=discussion_details["title"],
  5649. num=discussion_details["num"],
  5650. author=discussion_details.get("author", {}).get("name", "deleted"),
  5651. created_at=parse_datetime(discussion_details["createdAt"]),
  5652. status=discussion_details["status"],
  5653. repo_id=discussion_details["repo"]["name"],
  5654. repo_type=discussion_details["repo"]["type"],
  5655. is_pull_request=discussion_details["isPullRequest"],
  5656. events=[deserialize_event(evt) for evt in discussion_details["events"]],
  5657. conflicting_files=conflicting_files,
  5658. target_branch=target_branch,
  5659. merge_commit_oid=merge_commit_oid,
  5660. diff=discussion_details.get("diff"),
  5661. endpoint=self.endpoint,
  5662. )
  5663. @validate_hf_hub_args
  5664. def create_discussion(
  5665. self,
  5666. repo_id: str,
  5667. title: str,
  5668. *,
  5669. token: Union[bool, str, None] = None,
  5670. description: Optional[str] = None,
  5671. repo_type: Optional[str] = None,
  5672. pull_request: bool = False,
  5673. ) -> DiscussionWithDetails:
  5674. """Creates a Discussion or Pull Request.
  5675. Pull Requests created programmatically will be in `"draft"` status.
  5676. Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`].
  5677. Args:
  5678. repo_id (`str`):
  5679. A namespace (user or an organization) and a repo name separated
  5680. by a `/`.
  5681. title (`str`):
  5682. The title of the discussion. It can be up to 200 characters long,
  5683. and must be at least 3 characters long. Leading and trailing whitespaces
  5684. will be stripped.
  5685. token (`bool` or `str`, *optional*):
  5686. A valid user access token (string). Defaults to the locally saved
  5687. token, which is the recommended method for authentication (see
  5688. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5689. To disable authentication, pass `False`.
  5690. description (`str`, *optional*):
  5691. An optional description for the Pull Request.
  5692. Defaults to `"Discussion opened with the huggingface_hub Python library"`
  5693. pull_request (`bool`, *optional*):
  5694. Whether to create a Pull Request or discussion. If `True`, creates a Pull Request.
  5695. If `False`, creates a discussion. Defaults to `False`.
  5696. repo_type (`str`, *optional*):
  5697. Set to `"dataset"` or `"space"` if uploading to a dataset or
  5698. space, `None` or `"model"` if uploading to a model. Default is
  5699. `None`.
  5700. Returns: [`DiscussionWithDetails`]
  5701. > [!TIP]
  5702. > Raises the following errors:
  5703. >
  5704. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  5705. > if the HuggingFace API returned an error
  5706. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5707. > if some parameter value is invalid
  5708. > - [`~utils.RepositoryNotFoundError`]
  5709. > If the repository to download from cannot be found. This may be because it doesn't exist,
  5710. > or because it is set to `private` and you do not have access."""
  5711. if repo_type not in constants.REPO_TYPES:
  5712. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  5713. if repo_type is None:
  5714. repo_type = constants.REPO_TYPE_MODEL
  5715. if description is not None:
  5716. description = description.strip()
  5717. description = (
  5718. description
  5719. if description
  5720. else (
  5721. f"{'Pull Request' if pull_request else 'Discussion'} opened with the"
  5722. " [huggingface_hub Python"
  5723. " library](https://huggingface.co/docs/huggingface_hub)"
  5724. )
  5725. )
  5726. headers = self._build_hf_headers(token=token)
  5727. resp = get_session().post(
  5728. f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions",
  5729. json={
  5730. "title": title.strip(),
  5731. "description": description,
  5732. "pullRequest": pull_request,
  5733. },
  5734. headers=headers,
  5735. )
  5736. hf_raise_for_status(resp)
  5737. num = resp.json()["num"]
  5738. return self.get_discussion_details(
  5739. repo_id=repo_id,
  5740. repo_type=repo_type,
  5741. discussion_num=num,
  5742. token=token,
  5743. )
  5744. @validate_hf_hub_args
  5745. def create_pull_request(
  5746. self,
  5747. repo_id: str,
  5748. title: str,
  5749. *,
  5750. token: Union[bool, str, None] = None,
  5751. description: Optional[str] = None,
  5752. repo_type: Optional[str] = None,
  5753. ) -> DiscussionWithDetails:
  5754. """Creates a Pull Request . Pull Requests created programmatically will be in `"draft"` status.
  5755. Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`];
  5756. This is a wrapper around [`HfApi.create_discussion`].
  5757. Args:
  5758. repo_id (`str`):
  5759. A namespace (user or an organization) and a repo name separated
  5760. by a `/`.
  5761. title (`str`):
  5762. The title of the discussion. It can be up to 200 characters long,
  5763. and must be at least 3 characters long. Leading and trailing whitespaces
  5764. will be stripped.
  5765. token (`bool` or `str`, *optional*):
  5766. A valid user access token (string). Defaults to the locally saved
  5767. token, which is the recommended method for authentication (see
  5768. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5769. To disable authentication, pass `False`.
  5770. description (`str`, *optional*):
  5771. An optional description for the Pull Request.
  5772. Defaults to `"Discussion opened with the huggingface_hub Python library"`
  5773. repo_type (`str`, *optional*):
  5774. Set to `"dataset"` or `"space"` if uploading to a dataset or
  5775. space, `None` or `"model"` if uploading to a model. Default is
  5776. `None`.
  5777. Returns: [`DiscussionWithDetails`]
  5778. > [!TIP]
  5779. > Raises the following errors:
  5780. >
  5781. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  5782. > if the HuggingFace API returned an error
  5783. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5784. > if some parameter value is invalid
  5785. > - [`~utils.RepositoryNotFoundError`]
  5786. > If the repository to download from cannot be found. This may be because it doesn't exist,
  5787. > or because it is set to `private` and you do not have access."""
  5788. return self.create_discussion(
  5789. repo_id=repo_id,
  5790. title=title,
  5791. token=token,
  5792. description=description,
  5793. repo_type=repo_type,
  5794. pull_request=True,
  5795. )
  5796. def _post_discussion_changes(
  5797. self,
  5798. *,
  5799. repo_id: str,
  5800. discussion_num: int,
  5801. resource: str,
  5802. body: Optional[dict] = None,
  5803. token: Union[bool, str, None] = None,
  5804. repo_type: Optional[str] = None,
  5805. ) -> requests.Response:
  5806. """Internal utility to POST changes to a Discussion or Pull Request"""
  5807. if not isinstance(discussion_num, int) or discussion_num <= 0:
  5808. raise ValueError("Invalid discussion_num, must be a positive integer")
  5809. if repo_type not in constants.REPO_TYPES:
  5810. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  5811. if repo_type is None:
  5812. repo_type = constants.REPO_TYPE_MODEL
  5813. repo_id = f"{repo_type}s/{repo_id}"
  5814. path = f"{self.endpoint}/api/{repo_id}/discussions/{discussion_num}/{resource}"
  5815. headers = self._build_hf_headers(token=token)
  5816. resp = requests.post(path, headers=headers, json=body)
  5817. hf_raise_for_status(resp)
  5818. return resp
  5819. @validate_hf_hub_args
  5820. def comment_discussion(
  5821. self,
  5822. repo_id: str,
  5823. discussion_num: int,
  5824. comment: str,
  5825. *,
  5826. token: Union[bool, str, None] = None,
  5827. repo_type: Optional[str] = None,
  5828. ) -> DiscussionComment:
  5829. """Creates a new comment on the given Discussion.
  5830. Args:
  5831. repo_id (`str`):
  5832. A namespace (user or an organization) and a repo name separated
  5833. by a `/`.
  5834. discussion_num (`int`):
  5835. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  5836. comment (`str`):
  5837. The content of the comment to create. Comments support markdown formatting.
  5838. repo_type (`str`, *optional*):
  5839. Set to `"dataset"` or `"space"` if uploading to a dataset or
  5840. space, `None` or `"model"` if uploading to a model. Default is
  5841. `None`.
  5842. token (`bool` or `str`, *optional*):
  5843. A valid user access token (string). Defaults to the locally saved
  5844. token, which is the recommended method for authentication (see
  5845. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5846. To disable authentication, pass `False`.
  5847. Returns:
  5848. [`DiscussionComment`]: the newly created comment
  5849. Examples:
  5850. ```python
  5851. >>> comment = \"\"\"
  5852. ... Hello @otheruser!
  5853. ...
  5854. ... # This is a title
  5855. ...
  5856. ... **This is bold**, *this is italic* and ~this is strikethrough~
  5857. ... And [this](http://url) is a link
  5858. ... \"\"\"
  5859. >>> HfApi().comment_discussion(
  5860. ... repo_id="username/repo_name",
  5861. ... discussion_num=34
  5862. ... comment=comment
  5863. ... )
  5864. # DiscussionComment(id='deadbeef0000000', type='comment', ...)
  5865. ```
  5866. > [!TIP]
  5867. > Raises the following errors:
  5868. >
  5869. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  5870. > if the HuggingFace API returned an error
  5871. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5872. > if some parameter value is invalid
  5873. > - [`~utils.RepositoryNotFoundError`]
  5874. > If the repository to download from cannot be found. This may be because it doesn't exist,
  5875. > or because it is set to `private` and you do not have access.
  5876. """
  5877. resp = self._post_discussion_changes(
  5878. repo_id=repo_id,
  5879. repo_type=repo_type,
  5880. discussion_num=discussion_num,
  5881. token=token,
  5882. resource="comment",
  5883. body={"comment": comment},
  5884. )
  5885. return deserialize_event(resp.json()["newMessage"]) # type: ignore
  5886. @validate_hf_hub_args
  5887. def rename_discussion(
  5888. self,
  5889. repo_id: str,
  5890. discussion_num: int,
  5891. new_title: str,
  5892. *,
  5893. token: Union[bool, str, None] = None,
  5894. repo_type: Optional[str] = None,
  5895. ) -> DiscussionTitleChange:
  5896. """Renames a Discussion.
  5897. Args:
  5898. repo_id (`str`):
  5899. A namespace (user or an organization) and a repo name separated
  5900. by a `/`.
  5901. discussion_num (`int`):
  5902. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  5903. new_title (`str`):
  5904. The new title for the discussion
  5905. repo_type (`str`, *optional*):
  5906. Set to `"dataset"` or `"space"` if uploading to a dataset or
  5907. space, `None` or `"model"` if uploading to a model. Default is
  5908. `None`.
  5909. token (`bool` or `str`, *optional*):
  5910. A valid user access token (string). Defaults to the locally saved
  5911. token, which is the recommended method for authentication (see
  5912. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5913. To disable authentication, pass `False`.
  5914. Returns:
  5915. [`DiscussionTitleChange`]: the title change event
  5916. Examples:
  5917. ```python
  5918. >>> new_title = "New title, fixing a typo"
  5919. >>> HfApi().rename_discussion(
  5920. ... repo_id="username/repo_name",
  5921. ... discussion_num=34
  5922. ... new_title=new_title
  5923. ... )
  5924. # DiscussionTitleChange(id='deadbeef0000000', type='title-change', ...)
  5925. ```
  5926. > [!TIP]
  5927. > Raises the following errors:
  5928. >
  5929. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  5930. > if the HuggingFace API returned an error
  5931. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5932. > if some parameter value is invalid
  5933. > - [`~utils.RepositoryNotFoundError`]
  5934. > If the repository to download from cannot be found. This may be because it doesn't exist,
  5935. > or because it is set to `private` and you do not have access.
  5936. """
  5937. resp = self._post_discussion_changes(
  5938. repo_id=repo_id,
  5939. repo_type=repo_type,
  5940. discussion_num=discussion_num,
  5941. token=token,
  5942. resource="title",
  5943. body={"title": new_title},
  5944. )
  5945. return deserialize_event(resp.json()["newTitle"]) # type: ignore
  5946. @validate_hf_hub_args
  5947. def change_discussion_status(
  5948. self,
  5949. repo_id: str,
  5950. discussion_num: int,
  5951. new_status: Literal["open", "closed"],
  5952. *,
  5953. token: Union[bool, str, None] = None,
  5954. comment: Optional[str] = None,
  5955. repo_type: Optional[str] = None,
  5956. ) -> DiscussionStatusChange:
  5957. """Closes or re-opens a Discussion or Pull Request.
  5958. Args:
  5959. repo_id (`str`):
  5960. A namespace (user or an organization) and a repo name separated
  5961. by a `/`.
  5962. discussion_num (`int`):
  5963. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  5964. new_status (`str`):
  5965. The new status for the discussion, either `"open"` or `"closed"`.
  5966. comment (`str`, *optional*):
  5967. An optional comment to post with the status change.
  5968. repo_type (`str`, *optional*):
  5969. Set to `"dataset"` or `"space"` if uploading to a dataset or
  5970. space, `None` or `"model"` if uploading to a model. Default is
  5971. `None`.
  5972. token (`bool` or `str`, *optional*):
  5973. A valid user access token (string). Defaults to the locally saved
  5974. token, which is the recommended method for authentication (see
  5975. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  5976. To disable authentication, pass `False`.
  5977. Returns:
  5978. [`DiscussionStatusChange`]: the status change event
  5979. Examples:
  5980. ```python
  5981. >>> new_title = "New title, fixing a typo"
  5982. >>> HfApi().rename_discussion(
  5983. ... repo_id="username/repo_name",
  5984. ... discussion_num=34
  5985. ... new_title=new_title
  5986. ... )
  5987. # DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...)
  5988. ```
  5989. > [!TIP]
  5990. > Raises the following errors:
  5991. >
  5992. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  5993. > if the HuggingFace API returned an error
  5994. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  5995. > if some parameter value is invalid
  5996. > - [`~utils.RepositoryNotFoundError`]
  5997. > If the repository to download from cannot be found. This may be because it doesn't exist,
  5998. > or because it is set to `private` and you do not have access.
  5999. """
  6000. if new_status not in ["open", "closed"]:
  6001. raise ValueError("Invalid status, valid statuses are: 'open' and 'closed'")
  6002. body: Dict[str, str] = {"status": new_status}
  6003. if comment and comment.strip():
  6004. body["comment"] = comment.strip()
  6005. resp = self._post_discussion_changes(
  6006. repo_id=repo_id,
  6007. repo_type=repo_type,
  6008. discussion_num=discussion_num,
  6009. token=token,
  6010. resource="status",
  6011. body=body,
  6012. )
  6013. return deserialize_event(resp.json()["newStatus"]) # type: ignore
  6014. @validate_hf_hub_args
  6015. def merge_pull_request(
  6016. self,
  6017. repo_id: str,
  6018. discussion_num: int,
  6019. *,
  6020. token: Union[bool, str, None] = None,
  6021. comment: Optional[str] = None,
  6022. repo_type: Optional[str] = None,
  6023. ):
  6024. """Merges a Pull Request.
  6025. Args:
  6026. repo_id (`str`):
  6027. A namespace (user or an organization) and a repo name separated
  6028. by a `/`.
  6029. discussion_num (`int`):
  6030. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6031. comment (`str`, *optional*):
  6032. An optional comment to post with the status change.
  6033. repo_type (`str`, *optional*):
  6034. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6035. space, `None` or `"model"` if uploading to a model. Default is
  6036. `None`.
  6037. token (`bool` or `str`, *optional*):
  6038. A valid user access token (string). Defaults to the locally saved
  6039. token, which is the recommended method for authentication (see
  6040. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6041. To disable authentication, pass `False`.
  6042. Returns:
  6043. [`DiscussionStatusChange`]: the status change event
  6044. > [!TIP]
  6045. > Raises the following errors:
  6046. >
  6047. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6048. > if the HuggingFace API returned an error
  6049. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6050. > if some parameter value is invalid
  6051. > - [`~utils.RepositoryNotFoundError`]
  6052. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6053. > or because it is set to `private` and you do not have access.
  6054. """
  6055. self._post_discussion_changes(
  6056. repo_id=repo_id,
  6057. repo_type=repo_type,
  6058. discussion_num=discussion_num,
  6059. token=token,
  6060. resource="merge",
  6061. body={"comment": comment.strip()} if comment and comment.strip() else None,
  6062. )
  6063. @validate_hf_hub_args
  6064. def edit_discussion_comment(
  6065. self,
  6066. repo_id: str,
  6067. discussion_num: int,
  6068. comment_id: str,
  6069. new_content: str,
  6070. *,
  6071. token: Union[bool, str, None] = None,
  6072. repo_type: Optional[str] = None,
  6073. ) -> DiscussionComment:
  6074. """Edits a comment on a Discussion / Pull Request.
  6075. Args:
  6076. repo_id (`str`):
  6077. A namespace (user or an organization) and a repo name separated
  6078. by a `/`.
  6079. discussion_num (`int`):
  6080. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6081. comment_id (`str`):
  6082. The ID of the comment to edit.
  6083. new_content (`str`):
  6084. The new content of the comment. Comments support markdown formatting.
  6085. repo_type (`str`, *optional*):
  6086. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6087. space, `None` or `"model"` if uploading to a model. Default is
  6088. `None`.
  6089. token (`bool` or `str`, *optional*):
  6090. A valid user access token (string). Defaults to the locally saved
  6091. token, which is the recommended method for authentication (see
  6092. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6093. To disable authentication, pass `False`.
  6094. Returns:
  6095. [`DiscussionComment`]: the edited comment
  6096. > [!TIP]
  6097. > Raises the following errors:
  6098. >
  6099. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6100. > if the HuggingFace API returned an error
  6101. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6102. > if some parameter value is invalid
  6103. > - [`~utils.RepositoryNotFoundError`]
  6104. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6105. > or because it is set to `private` and you do not have access.
  6106. """
  6107. resp = self._post_discussion_changes(
  6108. repo_id=repo_id,
  6109. repo_type=repo_type,
  6110. discussion_num=discussion_num,
  6111. token=token,
  6112. resource=f"comment/{comment_id.lower()}/edit",
  6113. body={"content": new_content},
  6114. )
  6115. return deserialize_event(resp.json()["updatedComment"]) # type: ignore
  6116. @validate_hf_hub_args
  6117. def hide_discussion_comment(
  6118. self,
  6119. repo_id: str,
  6120. discussion_num: int,
  6121. comment_id: str,
  6122. *,
  6123. token: Union[bool, str, None] = None,
  6124. repo_type: Optional[str] = None,
  6125. ) -> DiscussionComment:
  6126. """Hides a comment on a Discussion / Pull Request.
  6127. > [!WARNING]
  6128. > Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.
  6129. Args:
  6130. repo_id (`str`):
  6131. A namespace (user or an organization) and a repo name separated
  6132. by a `/`.
  6133. discussion_num (`int`):
  6134. The number of the Discussion or Pull Request . Must be a strictly positive integer.
  6135. comment_id (`str`):
  6136. The ID of the comment to edit.
  6137. repo_type (`str`, *optional*):
  6138. Set to `"dataset"` or `"space"` if uploading to a dataset or
  6139. space, `None` or `"model"` if uploading to a model. Default is
  6140. `None`.
  6141. token (`bool` or `str`, *optional*):
  6142. A valid user access token (string). Defaults to the locally saved
  6143. token, which is the recommended method for authentication (see
  6144. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6145. To disable authentication, pass `False`.
  6146. Returns:
  6147. [`DiscussionComment`]: the hidden comment
  6148. > [!TIP]
  6149. > Raises the following errors:
  6150. >
  6151. > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  6152. > if the HuggingFace API returned an error
  6153. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  6154. > if some parameter value is invalid
  6155. > - [`~utils.RepositoryNotFoundError`]
  6156. > If the repository to download from cannot be found. This may be because it doesn't exist,
  6157. > or because it is set to `private` and you do not have access.
  6158. """
  6159. warnings.warn(
  6160. "Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.",
  6161. UserWarning,
  6162. )
  6163. resp = self._post_discussion_changes(
  6164. repo_id=repo_id,
  6165. repo_type=repo_type,
  6166. discussion_num=discussion_num,
  6167. token=token,
  6168. resource=f"comment/{comment_id.lower()}/hide",
  6169. )
  6170. return deserialize_event(resp.json()["updatedComment"]) # type: ignore
  6171. @validate_hf_hub_args
  6172. def add_space_secret(
  6173. self,
  6174. repo_id: str,
  6175. key: str,
  6176. value: str,
  6177. *,
  6178. description: Optional[str] = None,
  6179. token: Union[bool, str, None] = None,
  6180. ) -> None:
  6181. """Adds or updates a secret in a Space.
  6182. Secrets allow to set secret keys or tokens to a Space without hardcoding them.
  6183. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  6184. Args:
  6185. repo_id (`str`):
  6186. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6187. key (`str`):
  6188. Secret key. Example: `"GITHUB_API_KEY"`
  6189. value (`str`):
  6190. Secret value. Example: `"your_github_api_key"`.
  6191. description (`str`, *optional*):
  6192. Secret description. Example: `"Github API key to access the Github API"`.
  6193. token (`bool` or `str`, *optional*):
  6194. A valid user access token (string). Defaults to the locally saved
  6195. token, which is the recommended method for authentication (see
  6196. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6197. To disable authentication, pass `False`.
  6198. """
  6199. payload = {"key": key, "value": value}
  6200. if description is not None:
  6201. payload["description"] = description
  6202. r = get_session().post(
  6203. f"{self.endpoint}/api/spaces/{repo_id}/secrets",
  6204. headers=self._build_hf_headers(token=token),
  6205. json=payload,
  6206. )
  6207. hf_raise_for_status(r)
  6208. @validate_hf_hub_args
  6209. def delete_space_secret(self, repo_id: str, key: str, *, token: Union[bool, str, None] = None) -> None:
  6210. """Deletes a secret from a Space.
  6211. Secrets allow to set secret keys or tokens to a Space without hardcoding them.
  6212. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  6213. Args:
  6214. repo_id (`str`):
  6215. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6216. key (`str`):
  6217. Secret key. Example: `"GITHUB_API_KEY"`.
  6218. token (`bool` or `str`, *optional*):
  6219. A valid user access token (string). Defaults to the locally saved
  6220. token, which is the recommended method for authentication (see
  6221. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6222. To disable authentication, pass `False`.
  6223. """
  6224. r = get_session().delete(
  6225. f"{self.endpoint}/api/spaces/{repo_id}/secrets",
  6226. headers=self._build_hf_headers(token=token),
  6227. json={"key": key},
  6228. )
  6229. hf_raise_for_status(r)
  6230. @validate_hf_hub_args
  6231. def get_space_variables(self, repo_id: str, *, token: Union[bool, str, None] = None) -> Dict[str, SpaceVariable]:
  6232. """Gets all variables from a Space.
  6233. Variables allow to set environment variables to a Space without hardcoding them.
  6234. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
  6235. Args:
  6236. repo_id (`str`):
  6237. ID of the repo to query. Example: `"bigcode/in-the-stack"`.
  6238. token (`bool` or `str`, *optional*):
  6239. A valid user access token (string). Defaults to the locally saved
  6240. token, which is the recommended method for authentication (see
  6241. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6242. To disable authentication, pass `False`.
  6243. """
  6244. r = get_session().get(
  6245. f"{self.endpoint}/api/spaces/{repo_id}/variables",
  6246. headers=self._build_hf_headers(token=token),
  6247. )
  6248. hf_raise_for_status(r)
  6249. return {k: SpaceVariable(k, v) for k, v in r.json().items()}
  6250. @validate_hf_hub_args
  6251. def add_space_variable(
  6252. self,
  6253. repo_id: str,
  6254. key: str,
  6255. value: str,
  6256. *,
  6257. description: Optional[str] = None,
  6258. token: Union[bool, str, None] = None,
  6259. ) -> Dict[str, SpaceVariable]:
  6260. """Adds or updates a variable in a Space.
  6261. Variables allow to set environment variables to a Space without hardcoding them.
  6262. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
  6263. Args:
  6264. repo_id (`str`):
  6265. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6266. key (`str`):
  6267. Variable key. Example: `"MODEL_REPO_ID"`
  6268. value (`str`):
  6269. Variable value. Example: `"the_model_repo_id"`.
  6270. description (`str`):
  6271. Description of the variable. Example: `"Model Repo ID of the implemented model"`.
  6272. token (`bool` or `str`, *optional*):
  6273. A valid user access token (string). Defaults to the locally saved
  6274. token, which is the recommended method for authentication (see
  6275. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6276. To disable authentication, pass `False`.
  6277. """
  6278. payload = {"key": key, "value": value}
  6279. if description is not None:
  6280. payload["description"] = description
  6281. r = get_session().post(
  6282. f"{self.endpoint}/api/spaces/{repo_id}/variables",
  6283. headers=self._build_hf_headers(token=token),
  6284. json=payload,
  6285. )
  6286. hf_raise_for_status(r)
  6287. return {k: SpaceVariable(k, v) for k, v in r.json().items()}
  6288. @validate_hf_hub_args
  6289. def delete_space_variable(
  6290. self, repo_id: str, key: str, *, token: Union[bool, str, None] = None
  6291. ) -> Dict[str, SpaceVariable]:
  6292. """Deletes a variable from a Space.
  6293. Variables allow to set environment variables to a Space without hardcoding them.
  6294. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
  6295. Args:
  6296. repo_id (`str`):
  6297. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6298. key (`str`):
  6299. Variable key. Example: `"MODEL_REPO_ID"`
  6300. token (`bool` or `str`, *optional*):
  6301. A valid user access token (string). Defaults to the locally saved
  6302. token, which is the recommended method for authentication (see
  6303. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6304. To disable authentication, pass `False`.
  6305. """
  6306. r = get_session().delete(
  6307. f"{self.endpoint}/api/spaces/{repo_id}/variables",
  6308. headers=self._build_hf_headers(token=token),
  6309. json={"key": key},
  6310. )
  6311. hf_raise_for_status(r)
  6312. return {k: SpaceVariable(k, v) for k, v in r.json().items()}
  6313. @validate_hf_hub_args
  6314. def get_space_runtime(self, repo_id: str, *, token: Union[bool, str, None] = None) -> SpaceRuntime:
  6315. """Gets runtime information about a Space.
  6316. Args:
  6317. repo_id (`str`):
  6318. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6319. token (`bool` or `str`, *optional*):
  6320. A valid user access token (string). Defaults to the locally saved
  6321. token, which is the recommended method for authentication (see
  6322. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6323. To disable authentication, pass `False`.
  6324. Returns:
  6325. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  6326. """
  6327. r = get_session().get(
  6328. f"{self.endpoint}/api/spaces/{repo_id}/runtime", headers=self._build_hf_headers(token=token)
  6329. )
  6330. hf_raise_for_status(r)
  6331. return SpaceRuntime(r.json())
  6332. @validate_hf_hub_args
  6333. def request_space_hardware(
  6334. self,
  6335. repo_id: str,
  6336. hardware: SpaceHardware,
  6337. *,
  6338. token: Union[bool, str, None] = None,
  6339. sleep_time: Optional[int] = None,
  6340. ) -> SpaceRuntime:
  6341. """Request new hardware for a Space.
  6342. Args:
  6343. repo_id (`str`):
  6344. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6345. hardware (`str` or [`SpaceHardware`]):
  6346. Hardware on which to run the Space. Example: `"t4-medium"`.
  6347. token (`bool` or `str`, *optional*):
  6348. A valid user access token (string). Defaults to the locally saved
  6349. token, which is the recommended method for authentication (see
  6350. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6351. To disable authentication, pass `False`.
  6352. sleep_time (`int`, *optional*):
  6353. Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
  6354. your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
  6355. the sleep time (value is fixed to 48 hours of inactivity).
  6356. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  6357. Returns:
  6358. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  6359. > [!TIP]
  6360. > It is also possible to request hardware directly when creating the Space repo! See [`create_repo`] for details.
  6361. """
  6362. if sleep_time is not None and hardware == SpaceHardware.CPU_BASIC:
  6363. warnings.warn(
  6364. "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
  6365. " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
  6366. " you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
  6367. UserWarning,
  6368. )
  6369. payload: Dict[str, Any] = {"flavor": hardware}
  6370. if sleep_time is not None:
  6371. payload["sleepTimeSeconds"] = sleep_time
  6372. r = get_session().post(
  6373. f"{self.endpoint}/api/spaces/{repo_id}/hardware",
  6374. headers=self._build_hf_headers(token=token),
  6375. json=payload,
  6376. )
  6377. hf_raise_for_status(r)
  6378. return SpaceRuntime(r.json())
  6379. @validate_hf_hub_args
  6380. def set_space_sleep_time(
  6381. self, repo_id: str, sleep_time: int, *, token: Union[bool, str, None] = None
  6382. ) -> SpaceRuntime:
  6383. """Set a custom sleep time for a Space running on upgraded hardware..
  6384. Your Space will go to sleep after X seconds of inactivity. You are not billed when your Space is in "sleep"
  6385. mode. If a new visitor lands on your Space, it will "wake it up". Only upgraded hardware can have a
  6386. configurable sleep time. To know more about the sleep stage, please refer to
  6387. https://huggingface.co/docs/hub/spaces-gpus#sleep-time.
  6388. Args:
  6389. repo_id (`str`):
  6390. ID of the repo to update. Example: `"bigcode/in-the-stack"`.
  6391. sleep_time (`int`, *optional*):
  6392. Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
  6393. your Space to pause (default behavior for upgraded hardware). For free hardware, you can't configure
  6394. the sleep time (value is fixed to 48 hours of inactivity).
  6395. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  6396. token (`bool` or `str`, *optional*):
  6397. A valid user access token (string). Defaults to the locally saved
  6398. token, which is the recommended method for authentication (see
  6399. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6400. To disable authentication, pass `False`.
  6401. Returns:
  6402. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  6403. > [!TIP]
  6404. > It is also possible to set a custom sleep time when requesting hardware with [`request_space_hardware`].
  6405. """
  6406. r = get_session().post(
  6407. f"{self.endpoint}/api/spaces/{repo_id}/sleeptime",
  6408. headers=self._build_hf_headers(token=token),
  6409. json={"seconds": sleep_time},
  6410. )
  6411. hf_raise_for_status(r)
  6412. runtime = SpaceRuntime(r.json())
  6413. hardware = runtime.requested_hardware or runtime.hardware
  6414. if hardware == SpaceHardware.CPU_BASIC:
  6415. warnings.warn(
  6416. "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
  6417. " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
  6418. " you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
  6419. UserWarning,
  6420. )
  6421. return runtime
  6422. @validate_hf_hub_args
  6423. def pause_space(self, repo_id: str, *, token: Union[bool, str, None] = None) -> SpaceRuntime:
  6424. """Pause your Space.
  6425. A paused Space stops executing until manually restarted by its owner. This is different from the sleeping
  6426. state in which free Spaces go after 48h of inactivity. Paused time is not billed to your account, no matter the
  6427. hardware you've selected. To restart your Space, use [`restart_space`] and go to your Space settings page.
  6428. For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause).
  6429. Args:
  6430. repo_id (`str`):
  6431. ID of the Space to pause. Example: `"Salesforce/BLIP2"`.
  6432. token (`bool` or `str`, *optional*):
  6433. A valid user access token (string). Defaults to the locally saved
  6434. token, which is the recommended method for authentication (see
  6435. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6436. To disable authentication, pass `False`.
  6437. Returns:
  6438. [`SpaceRuntime`]: Runtime information about your Space including `stage=PAUSED` and requested hardware.
  6439. Raises:
  6440. [`~utils.RepositoryNotFoundError`]:
  6441. If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
  6442. are not authenticated.
  6443. [`~utils.HfHubHTTPError`]:
  6444. 403 Forbidden: only the owner of a Space can pause it. If you want to manage a Space that you don't
  6445. own, either ask the owner by opening a Discussion or duplicate the Space.
  6446. [`~utils.BadRequestError`]:
  6447. If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
  6448. a static Space, you can set it to private.
  6449. """
  6450. r = get_session().post(
  6451. f"{self.endpoint}/api/spaces/{repo_id}/pause", headers=self._build_hf_headers(token=token)
  6452. )
  6453. hf_raise_for_status(r)
  6454. return SpaceRuntime(r.json())
  6455. @validate_hf_hub_args
  6456. def restart_space(
  6457. self, repo_id: str, *, token: Union[bool, str, None] = None, factory_reboot: bool = False
  6458. ) -> SpaceRuntime:
  6459. """Restart your Space.
  6460. This is the only way to programmatically restart a Space if you've put it on Pause (see [`pause_space`]). You
  6461. must be the owner of the Space to restart it. If you are using an upgraded hardware, your account will be
  6462. billed as soon as the Space is restarted. You can trigger a restart no matter the current state of a Space.
  6463. For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause).
  6464. Args:
  6465. repo_id (`str`):
  6466. ID of the Space to restart. Example: `"Salesforce/BLIP2"`.
  6467. token (`bool` or `str`, *optional*):
  6468. A valid user access token (string). Defaults to the locally saved
  6469. token, which is the recommended method for authentication (see
  6470. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6471. To disable authentication, pass `False`.
  6472. factory_reboot (`bool`, *optional*):
  6473. If `True`, the Space will be rebuilt from scratch without caching any requirements.
  6474. Returns:
  6475. [`SpaceRuntime`]: Runtime information about your Space.
  6476. Raises:
  6477. [`~utils.RepositoryNotFoundError`]:
  6478. If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
  6479. are not authenticated.
  6480. [`~utils.HfHubHTTPError`]:
  6481. 403 Forbidden: only the owner of a Space can restart it. If you want to restart a Space that you don't
  6482. own, either ask the owner by opening a Discussion or duplicate the Space.
  6483. [`~utils.BadRequestError`]:
  6484. If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
  6485. a static Space, you can set it to private.
  6486. """
  6487. params = {}
  6488. if factory_reboot:
  6489. params["factory"] = "true"
  6490. r = get_session().post(
  6491. f"{self.endpoint}/api/spaces/{repo_id}/restart", headers=self._build_hf_headers(token=token), params=params
  6492. )
  6493. hf_raise_for_status(r)
  6494. return SpaceRuntime(r.json())
  6495. @validate_hf_hub_args
  6496. def duplicate_space(
  6497. self,
  6498. from_id: str,
  6499. to_id: Optional[str] = None,
  6500. *,
  6501. private: Optional[bool] = None,
  6502. token: Union[bool, str, None] = None,
  6503. exist_ok: bool = False,
  6504. hardware: Optional[SpaceHardware] = None,
  6505. storage: Optional[SpaceStorage] = None,
  6506. sleep_time: Optional[int] = None,
  6507. secrets: Optional[List[Dict[str, str]]] = None,
  6508. variables: Optional[List[Dict[str, str]]] = None,
  6509. ) -> RepoUrl:
  6510. """Duplicate a Space.
  6511. Programmatically duplicate a Space. The new Space will be created in your account and will be in the same state
  6512. as the original Space (running or paused). You can duplicate a Space no matter the current state of a Space.
  6513. Args:
  6514. from_id (`str`):
  6515. ID of the Space to duplicate. Example: `"pharma/CLIP-Interrogator"`.
  6516. to_id (`str`, *optional*):
  6517. ID of the new Space. Example: `"dog/CLIP-Interrogator"`. If not provided, the new Space will have the same
  6518. name as the original Space, but in your account.
  6519. private (`bool`, *optional*):
  6520. Whether the new Space should be private or not. Defaults to the same privacy as the original Space.
  6521. token (`bool` or `str`, *optional*):
  6522. A valid user access token (string). Defaults to the locally saved
  6523. token, which is the recommended method for authentication (see
  6524. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6525. To disable authentication, pass `False`.
  6526. exist_ok (`bool`, *optional*, defaults to `False`):
  6527. If `True`, do not raise an error if repo already exists.
  6528. hardware (`SpaceHardware` or `str`, *optional*):
  6529. Choice of Hardware. Example: `"t4-medium"`. See [`SpaceHardware`] for a complete list.
  6530. storage (`SpaceStorage` or `str`, *optional*):
  6531. Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
  6532. sleep_time (`int`, *optional*):
  6533. Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
  6534. your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
  6535. the sleep time (value is fixed to 48 hours of inactivity).
  6536. See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
  6537. secrets (`List[Dict[str, str]]`, *optional*):
  6538. A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
  6539. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
  6540. variables (`List[Dict[str, str]]`, *optional*):
  6541. A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
  6542. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
  6543. Returns:
  6544. [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
  6545. attributes like `endpoint`, `repo_type` and `repo_id`.
  6546. Raises:
  6547. [`~utils.RepositoryNotFoundError`]:
  6548. If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist,
  6549. or because it is set to `private` and you do not have access.
  6550. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  6551. If the HuggingFace API returned an error
  6552. Example:
  6553. ```python
  6554. >>> from huggingface_hub import duplicate_space
  6555. # Duplicate a Space to your account
  6556. >>> duplicate_space("multimodalart/dreambooth-training")
  6557. RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)
  6558. # Can set custom destination id and visibility flag.
  6559. >>> duplicate_space("multimodalart/dreambooth-training", to_id="my-dreambooth", private=True)
  6560. RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...)
  6561. ```
  6562. """
  6563. # Parse to_id if provided
  6564. parsed_to_id = RepoUrl(to_id) if to_id is not None else None
  6565. # Infer target repo_id
  6566. to_namespace = ( # set namespace manually or default to username
  6567. parsed_to_id.namespace
  6568. if parsed_to_id is not None and parsed_to_id.namespace is not None
  6569. else self.whoami(token)["name"]
  6570. )
  6571. to_repo_name = parsed_to_id.repo_name if to_id is not None else RepoUrl(from_id).repo_name # type: ignore
  6572. # repository must be a valid repo_id (namespace/repo_name).
  6573. payload: Dict[str, Any] = {"repository": f"{to_namespace}/{to_repo_name}"}
  6574. keys = ["private", "hardware", "storageTier", "sleepTimeSeconds", "secrets", "variables"]
  6575. values = [private, hardware, storage, sleep_time, secrets, variables]
  6576. payload.update({k: v for k, v in zip(keys, values) if v is not None})
  6577. if sleep_time is not None and hardware == SpaceHardware.CPU_BASIC:
  6578. warnings.warn(
  6579. "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
  6580. " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
  6581. " you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
  6582. UserWarning,
  6583. )
  6584. r = get_session().post(
  6585. f"{self.endpoint}/api/spaces/{from_id}/duplicate",
  6586. headers=self._build_hf_headers(token=token),
  6587. json=payload,
  6588. )
  6589. try:
  6590. hf_raise_for_status(r)
  6591. except HTTPError as err:
  6592. if exist_ok and err.response.status_code == 409:
  6593. # Repo already exists and `exist_ok=True`
  6594. pass
  6595. else:
  6596. raise
  6597. return RepoUrl(r.json()["url"], endpoint=self.endpoint)
  6598. @validate_hf_hub_args
  6599. def request_space_storage(
  6600. self,
  6601. repo_id: str,
  6602. storage: SpaceStorage,
  6603. *,
  6604. token: Union[bool, str, None] = None,
  6605. ) -> SpaceRuntime:
  6606. """Request persistent storage for a Space.
  6607. Args:
  6608. repo_id (`str`):
  6609. ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`.
  6610. storage (`str` or [`SpaceStorage`]):
  6611. Storage tier. Either 'small', 'medium', or 'large'.
  6612. token (`bool` or `str`, *optional*):
  6613. A valid user access token (string). Defaults to the locally saved
  6614. token, which is the recommended method for authentication (see
  6615. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6616. To disable authentication, pass `False`.
  6617. Returns:
  6618. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  6619. > [!TIP]
  6620. > It is not possible to decrease persistent storage after its granted. To do so, you must delete it
  6621. > via [`delete_space_storage`].
  6622. """
  6623. payload: Dict[str, SpaceStorage] = {"tier": storage}
  6624. r = get_session().post(
  6625. f"{self.endpoint}/api/spaces/{repo_id}/storage",
  6626. headers=self._build_hf_headers(token=token),
  6627. json=payload,
  6628. )
  6629. hf_raise_for_status(r)
  6630. return SpaceRuntime(r.json())
  6631. @validate_hf_hub_args
  6632. def delete_space_storage(
  6633. self,
  6634. repo_id: str,
  6635. *,
  6636. token: Union[bool, str, None] = None,
  6637. ) -> SpaceRuntime:
  6638. """Delete persistent storage for a Space.
  6639. Args:
  6640. repo_id (`str`):
  6641. ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`.
  6642. token (`bool` or `str`, *optional*):
  6643. A valid user access token (string). Defaults to the locally saved
  6644. token, which is the recommended method for authentication (see
  6645. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6646. To disable authentication, pass `False`.
  6647. Returns:
  6648. [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
  6649. Raises:
  6650. [`BadRequestError`]
  6651. If space has no persistent storage.
  6652. """
  6653. r = get_session().delete(
  6654. f"{self.endpoint}/api/spaces/{repo_id}/storage",
  6655. headers=self._build_hf_headers(token=token),
  6656. )
  6657. hf_raise_for_status(r)
  6658. return SpaceRuntime(r.json())
  6659. #######################
  6660. # Inference Endpoints #
  6661. #######################
  6662. def list_inference_endpoints(
  6663. self, namespace: Optional[str] = None, *, token: Union[bool, str, None] = None
  6664. ) -> List[InferenceEndpoint]:
  6665. """Lists all inference endpoints for the given namespace.
  6666. Args:
  6667. namespace (`str`, *optional*):
  6668. The namespace to list endpoints for. Defaults to the current user. Set to `"*"` to list all endpoints
  6669. from all namespaces (i.e. personal namespace and all orgs the user belongs to).
  6670. token (`bool` or `str`, *optional*):
  6671. A valid user access token (string). Defaults to the locally saved
  6672. token, which is the recommended method for authentication (see
  6673. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6674. To disable authentication, pass `False`.
  6675. Returns:
  6676. List[`InferenceEndpoint`]: A list of all inference endpoints for the given namespace.
  6677. Example:
  6678. ```python
  6679. >>> from huggingface_hub import HfApi
  6680. >>> api = HfApi()
  6681. >>> api.list_inference_endpoints()
  6682. [InferenceEndpoint(name='my-endpoint', ...), ...]
  6683. ```
  6684. """
  6685. # Special case: list all endpoints for all namespaces the user has access to
  6686. if namespace == "*":
  6687. user = self.whoami(token=token)
  6688. # List personal endpoints first
  6689. endpoints: List[InferenceEndpoint] = list_inference_endpoints(namespace=self._get_namespace(token=token))
  6690. # Then list endpoints for all orgs the user belongs to and ignore 401 errors (no billing or no access)
  6691. for org in user.get("orgs", []):
  6692. try:
  6693. endpoints += list_inference_endpoints(namespace=org["name"], token=token)
  6694. except HfHubHTTPError as error:
  6695. if error.response.status_code == 401: # Either no billing or user don't have access)
  6696. logger.debug("Cannot list Inference Endpoints for org '%s': %s", org["name"], error)
  6697. pass
  6698. return endpoints
  6699. # Normal case: list endpoints for a specific namespace
  6700. namespace = namespace or self._get_namespace(token=token)
  6701. response = get_session().get(
  6702. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}",
  6703. headers=self._build_hf_headers(token=token),
  6704. )
  6705. hf_raise_for_status(response)
  6706. return [
  6707. InferenceEndpoint.from_raw(endpoint, namespace=namespace, token=token)
  6708. for endpoint in response.json()["items"]
  6709. ]
  6710. def create_inference_endpoint(
  6711. self,
  6712. name: str,
  6713. *,
  6714. repository: str,
  6715. framework: str,
  6716. accelerator: str,
  6717. instance_size: str,
  6718. instance_type: str,
  6719. region: str,
  6720. vendor: str,
  6721. account_id: Optional[str] = None,
  6722. min_replica: int = 1,
  6723. max_replica: int = 1,
  6724. scale_to_zero_timeout: Optional[int] = None,
  6725. revision: Optional[str] = None,
  6726. task: Optional[str] = None,
  6727. custom_image: Optional[Dict] = None,
  6728. env: Optional[Dict[str, str]] = None,
  6729. secrets: Optional[Dict[str, str]] = None,
  6730. type: InferenceEndpointType = InferenceEndpointType.PROTECTED,
  6731. domain: Optional[str] = None,
  6732. path: Optional[str] = None,
  6733. cache_http_responses: Optional[bool] = None,
  6734. tags: Optional[List[str]] = None,
  6735. namespace: Optional[str] = None,
  6736. token: Union[bool, str, None] = None,
  6737. ) -> InferenceEndpoint:
  6738. """Create a new Inference Endpoint.
  6739. Args:
  6740. name (`str`):
  6741. The unique name for the new Inference Endpoint.
  6742. repository (`str`):
  6743. The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
  6744. framework (`str`):
  6745. The machine learning framework used for the model (e.g. `"custom"`).
  6746. accelerator (`str`):
  6747. The hardware accelerator to be used for inference (e.g. `"cpu"`).
  6748. instance_size (`str`):
  6749. The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
  6750. instance_type (`str`):
  6751. The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
  6752. region (`str`):
  6753. The cloud region in which the Inference Endpoint will be created (e.g. `"us-east-1"`).
  6754. vendor (`str`):
  6755. The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. `"aws"`).
  6756. account_id (`str`, *optional*):
  6757. The account ID used to link a VPC to a private Inference Endpoint (if applicable).
  6758. min_replica (`int`, *optional*):
  6759. The minimum number of replicas (instances) to keep running for the Inference Endpoint. To enable
  6760. scaling to zero, set this value to 0 and adjust `scale_to_zero_timeout` accordingly. Defaults to 1.
  6761. max_replica (`int`, *optional*):
  6762. The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to 1.
  6763. scale_to_zero_timeout (`int`, *optional*):
  6764. The duration in minutes before an inactive endpoint is scaled to zero, or no scaling to zero if
  6765. set to None and `min_replica` is not 0. Defaults to None.
  6766. revision (`str`, *optional*):
  6767. The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
  6768. task (`str`, *optional*):
  6769. The task on which to deploy the model (e.g. `"text-classification"`).
  6770. custom_image (`Dict`, *optional*):
  6771. A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
  6772. Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
  6773. env (`Dict[str, str]`, *optional*):
  6774. Non-secret environment variables to inject in the container environment.
  6775. secrets (`Dict[str, str]`, *optional*):
  6776. Secret values to inject in the container environment.
  6777. type ([`InferenceEndpointType]`, *optional*):
  6778. The type of the Inference Endpoint, which can be `"protected"` (default), `"public"` or `"private"`.
  6779. domain (`str`, *optional*):
  6780. 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"`).
  6781. path (`str`, *optional*):
  6782. The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`).
  6783. cache_http_responses (`bool`, *optional*):
  6784. Whether to cache HTTP responses from the Inference Endpoint. Defaults to `False`.
  6785. tags (`List[str]`, *optional*):
  6786. A list of tags to associate with the Inference Endpoint.
  6787. namespace (`str`, *optional*):
  6788. The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.
  6789. token (`bool` or `str`, *optional*):
  6790. A valid user access token (string). Defaults to the locally saved
  6791. token, which is the recommended method for authentication (see
  6792. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6793. To disable authentication, pass `False`.
  6794. Returns:
  6795. [`InferenceEndpoint`]: information about the updated Inference Endpoint.
  6796. Example:
  6797. ```python
  6798. >>> from huggingface_hub import HfApi
  6799. >>> api = HfApi()
  6800. >>> endpoint = api.create_inference_endpoint(
  6801. ... "my-endpoint-name",
  6802. ... repository="gpt2",
  6803. ... framework="pytorch",
  6804. ... task="text-generation",
  6805. ... accelerator="cpu",
  6806. ... vendor="aws",
  6807. ... region="us-east-1",
  6808. ... type="protected",
  6809. ... instance_size="x2",
  6810. ... instance_type="intel-icl",
  6811. ... )
  6812. >>> endpoint
  6813. InferenceEndpoint(name='my-endpoint-name', status="pending",...)
  6814. # Run inference on the endpoint
  6815. >>> endpoint.client.text_generation(...)
  6816. "..."
  6817. ```
  6818. ```python
  6819. # Start an Inference Endpoint running Zephyr-7b-beta on TGI
  6820. >>> from huggingface_hub import HfApi
  6821. >>> api = HfApi()
  6822. >>> endpoint = api.create_inference_endpoint(
  6823. ... "aws-zephyr-7b-beta-0486",
  6824. ... repository="HuggingFaceH4/zephyr-7b-beta",
  6825. ... framework="pytorch",
  6826. ... task="text-generation",
  6827. ... accelerator="gpu",
  6828. ... vendor="aws",
  6829. ... region="us-east-1",
  6830. ... type="protected",
  6831. ... instance_size="x1",
  6832. ... instance_type="nvidia-a10g",
  6833. ... env={
  6834. ... "MAX_BATCH_PREFILL_TOKENS": "2048",
  6835. ... "MAX_INPUT_LENGTH": "1024",
  6836. ... "MAX_TOTAL_TOKENS": "1512",
  6837. ... "MODEL_ID": "/repository"
  6838. ... },
  6839. ... custom_image={
  6840. ... "health_route": "/health",
  6841. ... "url": "ghcr.io/huggingface/text-generation-inference:1.1.0",
  6842. ... },
  6843. ... secrets={"MY_SECRET_KEY": "secret_value"},
  6844. ... tags=["dev", "text-generation"],
  6845. ... )
  6846. ```
  6847. ```python
  6848. # Start an Inference Endpoint running ProsusAI/finbert while scaling to zero in 15 minutes
  6849. >>> from huggingface_hub import HfApi
  6850. >>> api = HfApi()
  6851. >>> endpoint = api.create_inference_endpoint(
  6852. ... "finbert-classifier",
  6853. ... repository="ProsusAI/finbert",
  6854. ... framework="pytorch",
  6855. ... task="text-classification",
  6856. ... min_replica=0,
  6857. ... scale_to_zero_timeout=15,
  6858. ... accelerator="cpu",
  6859. ... vendor="aws",
  6860. ... region="us-east-1",
  6861. ... type="protected",
  6862. ... instance_size="x2",
  6863. ... instance_type="intel-icl",
  6864. ... )
  6865. >>> endpoint.wait(timeout=300)
  6866. # Run inference on the endpoint
  6867. >>> endpoint.client.text_generation(...)
  6868. TextClassificationOutputElement(label='positive', score=0.8983615040779114)
  6869. ```
  6870. """
  6871. namespace = namespace or self._get_namespace(token=token)
  6872. if custom_image is not None:
  6873. image = (
  6874. custom_image
  6875. if next(iter(custom_image)) in constants.INFERENCE_ENDPOINT_IMAGE_KEYS
  6876. else {"custom": custom_image}
  6877. )
  6878. else:
  6879. image = {"huggingface": {}}
  6880. payload: Dict = {
  6881. "accountId": account_id,
  6882. "compute": {
  6883. "accelerator": accelerator,
  6884. "instanceSize": instance_size,
  6885. "instanceType": instance_type,
  6886. "scaling": {
  6887. "maxReplica": max_replica,
  6888. "minReplica": min_replica,
  6889. "scaleToZeroTimeout": scale_to_zero_timeout,
  6890. },
  6891. },
  6892. "model": {
  6893. "framework": framework,
  6894. "repository": repository,
  6895. "revision": revision,
  6896. "task": task,
  6897. "image": image,
  6898. },
  6899. "name": name,
  6900. "provider": {
  6901. "region": region,
  6902. "vendor": vendor,
  6903. },
  6904. "type": type,
  6905. }
  6906. if env:
  6907. payload["model"]["env"] = env
  6908. if secrets:
  6909. payload["model"]["secrets"] = secrets
  6910. if domain is not None or path is not None:
  6911. payload["route"] = {}
  6912. if domain is not None:
  6913. payload["route"]["domain"] = domain
  6914. if path is not None:
  6915. payload["route"]["path"] = path
  6916. if cache_http_responses is not None:
  6917. payload["cacheHttpResponses"] = cache_http_responses
  6918. if tags is not None:
  6919. payload["tags"] = tags
  6920. response = get_session().post(
  6921. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}",
  6922. headers=self._build_hf_headers(token=token),
  6923. json=payload,
  6924. )
  6925. hf_raise_for_status(response)
  6926. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  6927. @experimental
  6928. @validate_hf_hub_args
  6929. def create_inference_endpoint_from_catalog(
  6930. self,
  6931. repo_id: str,
  6932. *,
  6933. name: Optional[str] = None,
  6934. token: Union[bool, str, None] = None,
  6935. namespace: Optional[str] = None,
  6936. ) -> InferenceEndpoint:
  6937. """Create a new Inference Endpoint from a model in the Hugging Face Inference Catalog.
  6938. The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference
  6939. and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list
  6940. of available models in the catalog.
  6941. Args:
  6942. repo_id (`str`):
  6943. The ID of the model in the catalog to deploy as an Inference Endpoint.
  6944. name (`str`, *optional*):
  6945. The unique name for the new Inference Endpoint. If not provided, a random name will be generated.
  6946. token (`bool` or `str`, *optional*):
  6947. A valid user access token (string). Defaults to the locally saved
  6948. token, which is the recommended method for authentication (see
  6949. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6950. namespace (`str`, *optional*):
  6951. The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.
  6952. Returns:
  6953. [`InferenceEndpoint`]: information about the new Inference Endpoint.
  6954. > [!WARNING]
  6955. > `create_inference_endpoint_from_catalog` is experimental. Its API is subject to change in the future. Please provide feedback
  6956. > if you have any suggestions or requests.
  6957. """
  6958. token = token or self.token or get_token()
  6959. payload: Dict = {
  6960. "namespace": namespace or self._get_namespace(token=token),
  6961. "repoId": repo_id,
  6962. }
  6963. if name is not None:
  6964. payload["endpointName"] = name
  6965. response = get_session().post(
  6966. f"{constants.INFERENCE_CATALOG_ENDPOINT}/deploy",
  6967. headers=self._build_hf_headers(token=token),
  6968. json=payload,
  6969. )
  6970. hf_raise_for_status(response)
  6971. data = response.json()["endpoint"]
  6972. return InferenceEndpoint.from_raw(data, namespace=data["name"], token=token)
  6973. @experimental
  6974. @validate_hf_hub_args
  6975. def list_inference_catalog(self, *, token: Union[bool, str, None] = None) -> List[str]:
  6976. """List models available in the Hugging Face Inference Catalog.
  6977. The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference
  6978. and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list
  6979. of available models in the catalog.
  6980. Use [`create_inference_endpoint_from_catalog`] to deploy a model from the catalog.
  6981. Args:
  6982. token (`bool` or `str`, *optional*):
  6983. A valid user access token (string). Defaults to the locally saved
  6984. token, which is the recommended method for authentication (see
  6985. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  6986. Returns:
  6987. List[`str`]: A list of model IDs available in the catalog.
  6988. > [!WARNING]
  6989. > `list_inference_catalog` is experimental. Its API is subject to change in the future. Please provide feedback
  6990. > if you have any suggestions or requests.
  6991. """
  6992. response = get_session().get(
  6993. f"{constants.INFERENCE_CATALOG_ENDPOINT}/repo-list",
  6994. headers=self._build_hf_headers(token=token),
  6995. )
  6996. hf_raise_for_status(response)
  6997. return response.json()["models"]
  6998. def get_inference_endpoint(
  6999. self, name: str, *, namespace: Optional[str] = None, token: Union[bool, str, None] = None
  7000. ) -> InferenceEndpoint:
  7001. """Get information about an Inference Endpoint.
  7002. Args:
  7003. name (`str`):
  7004. The name of the Inference Endpoint to retrieve information about.
  7005. namespace (`str`, *optional*):
  7006. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  7007. token (`bool` or `str`, *optional*):
  7008. A valid user access token (string). Defaults to the locally saved
  7009. token, which is the recommended method for authentication (see
  7010. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7011. To disable authentication, pass `False`.
  7012. Returns:
  7013. [`InferenceEndpoint`]: information about the requested Inference Endpoint.
  7014. Example:
  7015. ```python
  7016. >>> from huggingface_hub import HfApi
  7017. >>> api = HfApi()
  7018. >>> endpoint = api.get_inference_endpoint("my-text-to-image")
  7019. >>> endpoint
  7020. InferenceEndpoint(name='my-text-to-image', ...)
  7021. # Get status
  7022. >>> endpoint.status
  7023. 'running'
  7024. >>> endpoint.url
  7025. 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
  7026. # Run inference
  7027. >>> endpoint.client.text_to_image(...)
  7028. ```
  7029. """
  7030. namespace = namespace or self._get_namespace(token=token)
  7031. response = get_session().get(
  7032. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}",
  7033. headers=self._build_hf_headers(token=token),
  7034. )
  7035. hf_raise_for_status(response)
  7036. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  7037. def update_inference_endpoint(
  7038. self,
  7039. name: str,
  7040. *,
  7041. # Compute update
  7042. accelerator: Optional[str] = None,
  7043. instance_size: Optional[str] = None,
  7044. instance_type: Optional[str] = None,
  7045. min_replica: Optional[int] = None,
  7046. max_replica: Optional[int] = None,
  7047. scale_to_zero_timeout: Optional[int] = None,
  7048. # Model update
  7049. repository: Optional[str] = None,
  7050. framework: Optional[str] = None,
  7051. revision: Optional[str] = None,
  7052. task: Optional[str] = None,
  7053. custom_image: Optional[Dict] = None,
  7054. env: Optional[Dict[str, str]] = None,
  7055. secrets: Optional[Dict[str, str]] = None,
  7056. # Route update
  7057. domain: Optional[str] = None,
  7058. path: Optional[str] = None,
  7059. # Other
  7060. cache_http_responses: Optional[bool] = None,
  7061. tags: Optional[List[str]] = None,
  7062. namespace: Optional[str] = None,
  7063. token: Union[bool, str, None] = None,
  7064. ) -> InferenceEndpoint:
  7065. """Update an Inference Endpoint.
  7066. This method allows the update of either the compute configuration, the deployed model, the route, or any combination.
  7067. All arguments are optional but at least one must be provided.
  7068. For convenience, you can also update an Inference Endpoint using [`InferenceEndpoint.update`].
  7069. Args:
  7070. name (`str`):
  7071. The name of the Inference Endpoint to update.
  7072. accelerator (`str`, *optional*):
  7073. The hardware accelerator to be used for inference (e.g. `"cpu"`).
  7074. instance_size (`str`, *optional*):
  7075. The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
  7076. instance_type (`str`, *optional*):
  7077. The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
  7078. min_replica (`int`, *optional*):
  7079. The minimum number of replicas (instances) to keep running for the Inference Endpoint.
  7080. max_replica (`int`, *optional*):
  7081. The maximum number of replicas (instances) to scale to for the Inference Endpoint.
  7082. scale_to_zero_timeout (`int`, *optional*):
  7083. The duration in minutes before an inactive endpoint is scaled to zero.
  7084. repository (`str`, *optional*):
  7085. The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
  7086. framework (`str`, *optional*):
  7087. The machine learning framework used for the model (e.g. `"custom"`).
  7088. revision (`str`, *optional*):
  7089. The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
  7090. task (`str`, *optional*):
  7091. The task on which to deploy the model (e.g. `"text-classification"`).
  7092. custom_image (`Dict`, *optional*):
  7093. A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
  7094. Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
  7095. env (`Dict[str, str]`, *optional*):
  7096. Non-secret environment variables to inject in the container environment
  7097. secrets (`Dict[str, str]`, *optional*):
  7098. Secret values to inject in the container environment.
  7099. domain (`str`, *optional*):
  7100. 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"`).
  7101. path (`str`, *optional*):
  7102. The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`).
  7103. cache_http_responses (`bool`, *optional*):
  7104. Whether to cache HTTP responses from the Inference Endpoint.
  7105. tags (`List[str]`, *optional*):
  7106. A list of tags to associate with the Inference Endpoint.
  7107. namespace (`str`, *optional*):
  7108. The namespace where the Inference Endpoint will be updated. Defaults to the current user's namespace.
  7109. token (`bool` or `str`, *optional*):
  7110. A valid user access token (string). Defaults to the locally saved
  7111. token, which is the recommended method for authentication (see
  7112. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7113. To disable authentication, pass `False`.
  7114. Returns:
  7115. [`InferenceEndpoint`]: information about the updated Inference Endpoint.
  7116. """
  7117. namespace = namespace or self._get_namespace(token=token)
  7118. # Populate only the fields that are not None
  7119. payload: Dict = defaultdict(lambda: defaultdict(dict))
  7120. if accelerator is not None:
  7121. payload["compute"]["accelerator"] = accelerator
  7122. if instance_size is not None:
  7123. payload["compute"]["instanceSize"] = instance_size
  7124. if instance_type is not None:
  7125. payload["compute"]["instanceType"] = instance_type
  7126. if max_replica is not None:
  7127. payload["compute"]["scaling"]["maxReplica"] = max_replica
  7128. if min_replica is not None:
  7129. payload["compute"]["scaling"]["minReplica"] = min_replica
  7130. if scale_to_zero_timeout is not None:
  7131. payload["compute"]["scaling"]["scaleToZeroTimeout"] = scale_to_zero_timeout
  7132. if repository is not None:
  7133. payload["model"]["repository"] = repository
  7134. if framework is not None:
  7135. payload["model"]["framework"] = framework
  7136. if revision is not None:
  7137. payload["model"]["revision"] = revision
  7138. if task is not None:
  7139. payload["model"]["task"] = task
  7140. if custom_image is not None:
  7141. payload["model"]["image"] = {"custom": custom_image}
  7142. if env is not None:
  7143. payload["model"]["env"] = env
  7144. if secrets is not None:
  7145. payload["model"]["secrets"] = secrets
  7146. if domain is not None:
  7147. payload["route"]["domain"] = domain
  7148. if path is not None:
  7149. payload["route"]["path"] = path
  7150. if cache_http_responses is not None:
  7151. payload["cacheHttpResponses"] = cache_http_responses
  7152. if tags is not None:
  7153. payload["tags"] = tags
  7154. response = get_session().put(
  7155. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}",
  7156. headers=self._build_hf_headers(token=token),
  7157. json=payload,
  7158. )
  7159. hf_raise_for_status(response)
  7160. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  7161. def delete_inference_endpoint(
  7162. self, name: str, *, namespace: Optional[str] = None, token: Union[bool, str, None] = None
  7163. ) -> None:
  7164. """Delete an Inference Endpoint.
  7165. This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
  7166. to pause it with [`pause_inference_endpoint`] or scale it to zero with [`scale_to_zero_inference_endpoint`].
  7167. For convenience, you can also delete an Inference Endpoint using [`InferenceEndpoint.delete`].
  7168. Args:
  7169. name (`str`):
  7170. The name of the Inference Endpoint to delete.
  7171. namespace (`str`, *optional*):
  7172. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  7173. token (`bool` or `str`, *optional*):
  7174. A valid user access token (string). Defaults to the locally saved
  7175. token, which is the recommended method for authentication (see
  7176. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7177. To disable authentication, pass `False`.
  7178. """
  7179. namespace = namespace or self._get_namespace(token=token)
  7180. response = get_session().delete(
  7181. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}",
  7182. headers=self._build_hf_headers(token=token),
  7183. )
  7184. hf_raise_for_status(response)
  7185. def pause_inference_endpoint(
  7186. self, name: str, *, namespace: Optional[str] = None, token: Union[bool, str, None] = None
  7187. ) -> InferenceEndpoint:
  7188. """Pause an Inference Endpoint.
  7189. A paused Inference Endpoint will not be charged. It can be resumed at any time using [`resume_inference_endpoint`].
  7190. This is different than scaling the Inference Endpoint to zero with [`scale_to_zero_inference_endpoint`], which
  7191. would be automatically restarted when a request is made to it.
  7192. For convenience, you can also pause an Inference Endpoint using [`pause_inference_endpoint`].
  7193. Args:
  7194. name (`str`):
  7195. The name of the Inference Endpoint to pause.
  7196. namespace (`str`, *optional*):
  7197. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  7198. token (`bool` or `str`, *optional*):
  7199. A valid user access token (string). Defaults to the locally saved
  7200. token, which is the recommended method for authentication (see
  7201. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7202. To disable authentication, pass `False`.
  7203. Returns:
  7204. [`InferenceEndpoint`]: information about the paused Inference Endpoint.
  7205. """
  7206. namespace = namespace or self._get_namespace(token=token)
  7207. response = get_session().post(
  7208. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/pause",
  7209. headers=self._build_hf_headers(token=token),
  7210. )
  7211. hf_raise_for_status(response)
  7212. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  7213. def resume_inference_endpoint(
  7214. self,
  7215. name: str,
  7216. *,
  7217. namespace: Optional[str] = None,
  7218. running_ok: bool = True,
  7219. token: Union[bool, str, None] = None,
  7220. ) -> InferenceEndpoint:
  7221. """Resume an Inference Endpoint.
  7222. For convenience, you can also resume an Inference Endpoint using [`InferenceEndpoint.resume`].
  7223. Args:
  7224. name (`str`):
  7225. The name of the Inference Endpoint to resume.
  7226. namespace (`str`, *optional*):
  7227. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  7228. running_ok (`bool`, *optional*):
  7229. If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to
  7230. `True`.
  7231. token (`bool` or `str`, *optional*):
  7232. A valid user access token (string). Defaults to the locally saved
  7233. token, which is the recommended method for authentication (see
  7234. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7235. To disable authentication, pass `False`.
  7236. Returns:
  7237. [`InferenceEndpoint`]: information about the resumed Inference Endpoint.
  7238. """
  7239. namespace = namespace or self._get_namespace(token=token)
  7240. response = get_session().post(
  7241. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/resume",
  7242. headers=self._build_hf_headers(token=token),
  7243. )
  7244. try:
  7245. hf_raise_for_status(response)
  7246. except HfHubHTTPError as error:
  7247. # If already running (and it's ok), then fetch current status and return
  7248. if running_ok and error.response.status_code == 400 and "already running" in error.response.text:
  7249. return self.get_inference_endpoint(name, namespace=namespace, token=token)
  7250. # Otherwise, raise the error
  7251. raise
  7252. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  7253. def scale_to_zero_inference_endpoint(
  7254. self, name: str, *, namespace: Optional[str] = None, token: Union[bool, str, None] = None
  7255. ) -> InferenceEndpoint:
  7256. """Scale Inference Endpoint to zero.
  7257. An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a
  7258. cold start delay. This is different than pausing the Inference Endpoint with [`pause_inference_endpoint`], which
  7259. would require a manual resume with [`resume_inference_endpoint`].
  7260. For convenience, you can also scale an Inference Endpoint to zero using [`InferenceEndpoint.scale_to_zero`].
  7261. Args:
  7262. name (`str`):
  7263. The name of the Inference Endpoint to scale to zero.
  7264. namespace (`str`, *optional*):
  7265. The namespace in which the Inference Endpoint is located. Defaults to the current user.
  7266. token (`bool` or `str`, *optional*):
  7267. A valid user access token (string). Defaults to the locally saved
  7268. token, which is the recommended method for authentication (see
  7269. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7270. To disable authentication, pass `False`.
  7271. Returns:
  7272. [`InferenceEndpoint`]: information about the scaled-to-zero Inference Endpoint.
  7273. """
  7274. namespace = namespace or self._get_namespace(token=token)
  7275. response = get_session().post(
  7276. f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/scale-to-zero",
  7277. headers=self._build_hf_headers(token=token),
  7278. )
  7279. hf_raise_for_status(response)
  7280. return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
  7281. def _get_namespace(self, token: Union[bool, str, None] = None) -> str:
  7282. """Get the default namespace for the current user."""
  7283. me = self.whoami(token=token)
  7284. if me["type"] == "user":
  7285. return me["name"]
  7286. else:
  7287. raise ValueError(
  7288. "Cannot determine default namespace. You must provide a 'namespace' as input or be logged in as a"
  7289. " user."
  7290. )
  7291. ########################
  7292. # Collection Endpoints #
  7293. ########################
  7294. @validate_hf_hub_args
  7295. def list_collections(
  7296. self,
  7297. *,
  7298. owner: Union[List[str], str, None] = None,
  7299. item: Union[List[str], str, None] = None,
  7300. sort: Optional[Literal["lastModified", "trending", "upvotes"]] = None,
  7301. limit: Optional[int] = None,
  7302. token: Union[bool, str, None] = None,
  7303. ) -> Iterable[Collection]:
  7304. """List collections on the Huggingface Hub, given some filters.
  7305. > [!WARNING]
  7306. > When listing collections, the item list per collection is truncated to 4 items maximum. To retrieve all items
  7307. > from a collection, you must use [`get_collection`].
  7308. Args:
  7309. owner (`List[str]` or `str`, *optional*):
  7310. Filter by owner's username.
  7311. item (`List[str]` or `str`, *optional*):
  7312. Filter collections containing a particular items. Example: `"models/teknium/OpenHermes-2.5-Mistral-7B"`, `"datasets/squad"` or `"papers/2311.12983"`.
  7313. sort (`Literal["lastModified", "trending", "upvotes"]`, *optional*):
  7314. Sort collections by last modified, trending or upvotes.
  7315. limit (`int`, *optional*):
  7316. Maximum number of collections to be returned.
  7317. token (`bool` or `str`, *optional*):
  7318. A valid user access token (string). Defaults to the locally saved
  7319. token, which is the recommended method for authentication (see
  7320. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7321. To disable authentication, pass `False`.
  7322. Returns:
  7323. `Iterable[Collection]`: an iterable of [`Collection`] objects.
  7324. """
  7325. # Construct the API endpoint
  7326. path = f"{self.endpoint}/api/collections"
  7327. headers = self._build_hf_headers(token=token)
  7328. params: Dict = {}
  7329. if owner is not None:
  7330. params.update({"owner": owner})
  7331. if item is not None:
  7332. params.update({"item": item})
  7333. if sort is not None:
  7334. params.update({"sort": sort})
  7335. if limit is not None:
  7336. params.update({"limit": limit})
  7337. # Paginate over the results until limit is reached
  7338. items = paginate(path, headers=headers, params=params)
  7339. if limit is not None:
  7340. items = islice(items, limit) # Do not iterate over all pages
  7341. # Parse as Collection and return
  7342. for position, collection_data in enumerate(items):
  7343. yield Collection(position=position, **collection_data)
  7344. def get_collection(self, collection_slug: str, *, token: Union[bool, str, None] = None) -> Collection:
  7345. """Gets information about a Collection on the Hub.
  7346. Args:
  7347. collection_slug (`str`):
  7348. Slug of the collection of the Hub. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  7349. token (`bool` or `str`, *optional*):
  7350. A valid user access token (string). Defaults to the locally saved
  7351. token, which is the recommended method for authentication (see
  7352. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7353. To disable authentication, pass `False`.
  7354. Returns: [`Collection`]
  7355. Example:
  7356. ```py
  7357. >>> from huggingface_hub import get_collection
  7358. >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
  7359. >>> collection.title
  7360. 'Recent models'
  7361. >>> len(collection.items)
  7362. 37
  7363. >>> collection.items[0]
  7364. CollectionItem(
  7365. item_object_id='651446103cd773a050bf64c2',
  7366. item_id='TheBloke/U-Amethyst-20B-AWQ',
  7367. item_type='model',
  7368. position=88,
  7369. note=None
  7370. )
  7371. ```
  7372. """
  7373. r = get_session().get(
  7374. f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token)
  7375. )
  7376. hf_raise_for_status(r)
  7377. return Collection(**{**r.json(), "endpoint": self.endpoint})
  7378. def create_collection(
  7379. self,
  7380. title: str,
  7381. *,
  7382. namespace: Optional[str] = None,
  7383. description: Optional[str] = None,
  7384. private: bool = False,
  7385. exists_ok: bool = False,
  7386. token: Union[bool, str, None] = None,
  7387. ) -> Collection:
  7388. """Create a new Collection on the Hub.
  7389. Args:
  7390. title (`str`):
  7391. Title of the collection to create. Example: `"Recent models"`.
  7392. namespace (`str`, *optional*):
  7393. Namespace of the collection to create (username or org). Will default to the owner name.
  7394. description (`str`, *optional*):
  7395. Description of the collection to create.
  7396. private (`bool`, *optional*):
  7397. Whether the collection should be private or not. Defaults to `False` (i.e. public collection).
  7398. exists_ok (`bool`, *optional*):
  7399. If `True`, do not raise an error if collection already exists.
  7400. token (`bool` or `str`, *optional*):
  7401. A valid user access token (string). Defaults to the locally saved
  7402. token, which is the recommended method for authentication (see
  7403. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7404. To disable authentication, pass `False`.
  7405. Returns: [`Collection`]
  7406. Example:
  7407. ```py
  7408. >>> from huggingface_hub import create_collection
  7409. >>> collection = create_collection(
  7410. ... title="ICCV 2023",
  7411. ... description="Portfolio of models, papers and demos I presented at ICCV 2023",
  7412. ... )
  7413. >>> collection.slug
  7414. "username/iccv-2023-64f9a55bb3115b4f513ec026"
  7415. ```
  7416. """
  7417. if namespace is None:
  7418. namespace = self.whoami(token)["name"]
  7419. payload = {
  7420. "title": title,
  7421. "namespace": namespace,
  7422. "private": private,
  7423. }
  7424. if description is not None:
  7425. payload["description"] = description
  7426. r = get_session().post(
  7427. f"{self.endpoint}/api/collections", headers=self._build_hf_headers(token=token), json=payload
  7428. )
  7429. try:
  7430. hf_raise_for_status(r)
  7431. except HTTPError as err:
  7432. if exists_ok and err.response.status_code == 409:
  7433. # Collection already exists and `exists_ok=True`
  7434. slug = r.json()["slug"]
  7435. return self.get_collection(slug, token=token)
  7436. else:
  7437. raise
  7438. return Collection(**{**r.json(), "endpoint": self.endpoint})
  7439. def update_collection_metadata(
  7440. self,
  7441. collection_slug: str,
  7442. *,
  7443. title: Optional[str] = None,
  7444. description: Optional[str] = None,
  7445. position: Optional[int] = None,
  7446. private: Optional[bool] = None,
  7447. theme: Optional[str] = None,
  7448. token: Union[bool, str, None] = None,
  7449. ) -> Collection:
  7450. """Update metadata of a collection on the Hub.
  7451. All arguments are optional. Only provided metadata will be updated.
  7452. Args:
  7453. collection_slug (`str`):
  7454. Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  7455. title (`str`):
  7456. Title of the collection to update.
  7457. description (`str`, *optional*):
  7458. Description of the collection to update.
  7459. position (`int`, *optional*):
  7460. New position of the collection in the list of collections of the user.
  7461. private (`bool`, *optional*):
  7462. Whether the collection should be private or not.
  7463. theme (`str`, *optional*):
  7464. Theme of the collection on the Hub.
  7465. token (`bool` or `str`, *optional*):
  7466. A valid user access token (string). Defaults to the locally saved
  7467. token, which is the recommended method for authentication (see
  7468. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7469. To disable authentication, pass `False`.
  7470. Returns: [`Collection`]
  7471. Example:
  7472. ```py
  7473. >>> from huggingface_hub import update_collection_metadata
  7474. >>> collection = update_collection_metadata(
  7475. ... collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026",
  7476. ... title="ICCV Oct. 2023"
  7477. ... description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023",
  7478. ... private=False,
  7479. ... theme="pink",
  7480. ... )
  7481. >>> collection.slug
  7482. "username/iccv-oct-2023-64f9a55bb3115b4f513ec026"
  7483. # ^collection slug got updated but not the trailing ID
  7484. ```
  7485. """
  7486. payload = {
  7487. "position": position,
  7488. "private": private,
  7489. "theme": theme,
  7490. "title": title,
  7491. "description": description,
  7492. }
  7493. r = get_session().patch(
  7494. f"{self.endpoint}/api/collections/{collection_slug}",
  7495. headers=self._build_hf_headers(token=token),
  7496. # Only send not-none values to the API
  7497. json={key: value for key, value in payload.items() if value is not None},
  7498. )
  7499. hf_raise_for_status(r)
  7500. return Collection(**{**r.json()["data"], "endpoint": self.endpoint})
  7501. def delete_collection(
  7502. self, collection_slug: str, *, missing_ok: bool = False, token: Union[bool, str, None] = None
  7503. ) -> None:
  7504. """Delete a collection on the Hub.
  7505. Args:
  7506. collection_slug (`str`):
  7507. Slug of the collection to delete. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  7508. missing_ok (`bool`, *optional*):
  7509. If `True`, do not raise an error if collection doesn't exists.
  7510. token (`bool` or `str`, *optional*):
  7511. A valid user access token (string). Defaults to the locally saved
  7512. token, which is the recommended method for authentication (see
  7513. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7514. To disable authentication, pass `False`.
  7515. Example:
  7516. ```py
  7517. >>> from huggingface_hub import delete_collection
  7518. >>> collection = delete_collection("username/useless-collection-64f9a55bb3115b4f513ec026", missing_ok=True)
  7519. ```
  7520. > [!WARNING]
  7521. > This is a non-revertible action. A deleted collection cannot be restored.
  7522. """
  7523. r = get_session().delete(
  7524. f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token)
  7525. )
  7526. try:
  7527. hf_raise_for_status(r)
  7528. except HTTPError as err:
  7529. if missing_ok and err.response.status_code == 404:
  7530. # Collection doesn't exists and `missing_ok=True`
  7531. return
  7532. else:
  7533. raise
  7534. def add_collection_item(
  7535. self,
  7536. collection_slug: str,
  7537. item_id: str,
  7538. item_type: CollectionItemType_T,
  7539. *,
  7540. note: Optional[str] = None,
  7541. exists_ok: bool = False,
  7542. token: Union[bool, str, None] = None,
  7543. ) -> Collection:
  7544. """Add an item to a collection on the Hub.
  7545. Args:
  7546. collection_slug (`str`):
  7547. Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  7548. item_id (`str`):
  7549. ID of the item to add to the collection. It can be the ID of a repo on the Hub (e.g. `"facebook/bart-large-mnli"`)
  7550. or a paper id (e.g. `"2307.09288"`).
  7551. item_type (`str`):
  7552. Type of the item to add. Can be one of `"model"`, `"dataset"`, `"space"` or `"paper"`.
  7553. note (`str`, *optional*):
  7554. A note to attach to the item in the collection. The maximum size for a note is 500 characters.
  7555. exists_ok (`bool`, *optional*):
  7556. If `True`, do not raise an error if item already exists.
  7557. token (`bool` or `str`, *optional*):
  7558. A valid user access token (string). Defaults to the locally saved
  7559. token, which is the recommended method for authentication (see
  7560. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7561. To disable authentication, pass `False`.
  7562. Returns: [`Collection`]
  7563. Raises:
  7564. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7565. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  7566. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  7567. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7568. HTTP 404 if the item you try to add to the collection does not exist on the Hub.
  7569. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7570. HTTP 409 if the item you try to add to the collection is already in the collection (and exists_ok=False)
  7571. Example:
  7572. ```py
  7573. >>> from huggingface_hub import add_collection_item
  7574. >>> collection = add_collection_item(
  7575. ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
  7576. ... item_id="pierre-loic/climate-news-articles",
  7577. ... item_type="dataset"
  7578. ... )
  7579. >>> collection.items[-1].item_id
  7580. "pierre-loic/climate-news-articles"
  7581. # ^item got added to the collection on last position
  7582. # Add item with a note
  7583. >>> add_collection_item(
  7584. ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
  7585. ... item_id="datasets/climate_fever",
  7586. ... item_type="dataset"
  7587. ... note="This dataset adopts the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet."
  7588. ... )
  7589. (...)
  7590. ```
  7591. """
  7592. payload: Dict[str, Any] = {"item": {"id": item_id, "type": item_type}}
  7593. if note is not None:
  7594. payload["note"] = note
  7595. r = get_session().post(
  7596. f"{self.endpoint}/api/collections/{collection_slug}/items",
  7597. headers=self._build_hf_headers(token=token),
  7598. json=payload,
  7599. )
  7600. try:
  7601. hf_raise_for_status(r)
  7602. except HTTPError as err:
  7603. if exists_ok and err.response.status_code == 409:
  7604. # Item already exists and `exists_ok=True`
  7605. return self.get_collection(collection_slug, token=token)
  7606. else:
  7607. raise
  7608. return Collection(**{**r.json(), "endpoint": self.endpoint})
  7609. def update_collection_item(
  7610. self,
  7611. collection_slug: str,
  7612. item_object_id: str,
  7613. *,
  7614. note: Optional[str] = None,
  7615. position: Optional[int] = None,
  7616. token: Union[bool, str, None] = None,
  7617. ) -> None:
  7618. """Update an item in a collection.
  7619. Args:
  7620. collection_slug (`str`):
  7621. Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  7622. item_object_id (`str`):
  7623. ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
  7624. It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`.
  7625. note (`str`, *optional*):
  7626. A note to attach to the item in the collection. The maximum size for a note is 500 characters.
  7627. position (`int`, *optional*):
  7628. New position of the item in the collection.
  7629. token (`bool` or `str`, *optional*):
  7630. A valid user access token (string). Defaults to the locally saved
  7631. token, which is the recommended method for authentication (see
  7632. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7633. To disable authentication, pass `False`.
  7634. Example:
  7635. ```py
  7636. >>> from huggingface_hub import get_collection, update_collection_item
  7637. # Get collection first
  7638. >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
  7639. # Update item based on its ID (add note + update position)
  7640. >>> update_collection_item(
  7641. ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
  7642. ... item_object_id=collection.items[-1].item_object_id,
  7643. ... note="Newly updated model!"
  7644. ... position=0,
  7645. ... )
  7646. ```
  7647. """
  7648. payload = {"position": position, "note": note}
  7649. r = get_session().patch(
  7650. f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}",
  7651. headers=self._build_hf_headers(token=token),
  7652. # Only send not-none values to the API
  7653. json={key: value for key, value in payload.items() if value is not None},
  7654. )
  7655. hf_raise_for_status(r)
  7656. def delete_collection_item(
  7657. self,
  7658. collection_slug: str,
  7659. item_object_id: str,
  7660. *,
  7661. missing_ok: bool = False,
  7662. token: Union[bool, str, None] = None,
  7663. ) -> None:
  7664. """Delete an item from a collection.
  7665. Args:
  7666. collection_slug (`str`):
  7667. Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
  7668. item_object_id (`str`):
  7669. ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
  7670. It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`.
  7671. missing_ok (`bool`, *optional*):
  7672. If `True`, do not raise an error if item doesn't exists.
  7673. token (`bool` or `str`, *optional*):
  7674. A valid user access token (string). Defaults to the locally saved
  7675. token, which is the recommended method for authentication (see
  7676. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7677. To disable authentication, pass `False`.
  7678. Example:
  7679. ```py
  7680. >>> from huggingface_hub import get_collection, delete_collection_item
  7681. # Get collection first
  7682. >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
  7683. # Delete item based on its ID
  7684. >>> delete_collection_item(
  7685. ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
  7686. ... item_object_id=collection.items[-1].item_object_id,
  7687. ... )
  7688. ```
  7689. """
  7690. r = get_session().delete(
  7691. f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}",
  7692. headers=self._build_hf_headers(token=token),
  7693. )
  7694. try:
  7695. hf_raise_for_status(r)
  7696. except HTTPError as err:
  7697. if missing_ok and err.response.status_code == 404:
  7698. # Item already deleted and `missing_ok=True`
  7699. return
  7700. else:
  7701. raise
  7702. ##########################
  7703. # Manage access requests #
  7704. ##########################
  7705. @validate_hf_hub_args
  7706. def list_pending_access_requests(
  7707. self, repo_id: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  7708. ) -> List[AccessRequest]:
  7709. """
  7710. Get pending access requests for a given gated repo.
  7711. A pending request means the user has requested access to the repo but the request has not been processed yet.
  7712. If the approval mode is automatic, this list should be empty. Pending requests can be accepted or rejected
  7713. using [`accept_access_request`] and [`reject_access_request`].
  7714. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  7715. Args:
  7716. repo_id (`str`):
  7717. The id of the repo to get access requests for.
  7718. repo_type (`str`, *optional*):
  7719. The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
  7720. Defaults to `model`.
  7721. token (`bool` or `str`, *optional*):
  7722. A valid user access token (string). Defaults to the locally saved
  7723. token, which is the recommended method for authentication (see
  7724. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7725. To disable authentication, pass `False`.
  7726. Returns:
  7727. `List[AccessRequest]`: A list of [`AccessRequest`] objects. Each time contains a `username`, `email`,
  7728. `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
  7729. be populated with user's answers.
  7730. Raises:
  7731. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7732. HTTP 400 if the repo is not gated.
  7733. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7734. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  7735. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  7736. Example:
  7737. ```py
  7738. >>> from huggingface_hub import list_pending_access_requests, accept_access_request
  7739. # List pending requests
  7740. >>> requests = list_pending_access_requests("meta-llama/Llama-2-7b")
  7741. >>> len(requests)
  7742. 411
  7743. >>> requests[0]
  7744. [
  7745. AccessRequest(
  7746. username='clem',
  7747. fullname='Clem 🤗',
  7748. email='***',
  7749. timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
  7750. status='pending',
  7751. fields=None,
  7752. ),
  7753. ...
  7754. ]
  7755. # Accept Clem's request
  7756. >>> accept_access_request("meta-llama/Llama-2-7b", "clem")
  7757. ```
  7758. """
  7759. return self._list_access_requests(repo_id, "pending", repo_type=repo_type, token=token)
  7760. @validate_hf_hub_args
  7761. def list_accepted_access_requests(
  7762. self, repo_id: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  7763. ) -> List[AccessRequest]:
  7764. """
  7765. Get accepted access requests for a given gated repo.
  7766. An accepted request means the user has requested access to the repo and the request has been accepted. The user
  7767. can download any file of the repo. If the approval mode is automatic, this list should contains by default all
  7768. requests. Accepted requests can be cancelled or rejected at any time using [`cancel_access_request`] and
  7769. [`reject_access_request`]. A cancelled request will go back to the pending list while a rejected request will
  7770. go to the rejected list. In both cases, the user will lose access to the repo.
  7771. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  7772. Args:
  7773. repo_id (`str`):
  7774. The id of the repo to get access requests for.
  7775. repo_type (`str`, *optional*):
  7776. The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
  7777. Defaults to `model`.
  7778. token (`bool` or `str`, *optional*):
  7779. A valid user access token (string). Defaults to the locally saved
  7780. token, which is the recommended method for authentication (see
  7781. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7782. To disable authentication, pass `False`.
  7783. Returns:
  7784. `List[AccessRequest]`: A list of [`AccessRequest`] objects. Each time contains a `username`, `email`,
  7785. `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
  7786. be populated with user's answers.
  7787. Raises:
  7788. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7789. HTTP 400 if the repo is not gated.
  7790. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7791. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  7792. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  7793. Example:
  7794. ```py
  7795. >>> from huggingface_hub import list_accepted_access_requests
  7796. >>> requests = list_accepted_access_requests("meta-llama/Llama-2-7b")
  7797. >>> len(requests)
  7798. 411
  7799. >>> requests[0]
  7800. [
  7801. AccessRequest(
  7802. username='clem',
  7803. fullname='Clem 🤗',
  7804. email='***',
  7805. timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
  7806. status='accepted',
  7807. fields=None,
  7808. ),
  7809. ...
  7810. ]
  7811. ```
  7812. """
  7813. return self._list_access_requests(repo_id, "accepted", repo_type=repo_type, token=token)
  7814. @validate_hf_hub_args
  7815. def list_rejected_access_requests(
  7816. self, repo_id: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  7817. ) -> List[AccessRequest]:
  7818. """
  7819. Get rejected access requests for a given gated repo.
  7820. A rejected request means the user has requested access to the repo and the request has been explicitly rejected
  7821. by a repo owner (either you or another user from your organization). The user cannot download any file of the
  7822. repo. Rejected requests can be accepted or cancelled at any time using [`accept_access_request`] and
  7823. [`cancel_access_request`]. A cancelled request will go back to the pending list while an accepted request will
  7824. go to the accepted list.
  7825. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  7826. Args:
  7827. repo_id (`str`):
  7828. The id of the repo to get access requests for.
  7829. repo_type (`str`, *optional*):
  7830. The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
  7831. Defaults to `model`.
  7832. token (`bool` or `str`, *optional*):
  7833. A valid user access token (string). Defaults to the locally saved
  7834. token, which is the recommended method for authentication (see
  7835. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7836. To disable authentication, pass `False`.
  7837. Returns:
  7838. `List[AccessRequest]`: A list of [`AccessRequest`] objects. Each time contains a `username`, `email`,
  7839. `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
  7840. be populated with user's answers.
  7841. Raises:
  7842. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7843. HTTP 400 if the repo is not gated.
  7844. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7845. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  7846. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  7847. Example:
  7848. ```py
  7849. >>> from huggingface_hub import list_rejected_access_requests
  7850. >>> requests = list_rejected_access_requests("meta-llama/Llama-2-7b")
  7851. >>> len(requests)
  7852. 411
  7853. >>> requests[0]
  7854. [
  7855. AccessRequest(
  7856. username='clem',
  7857. fullname='Clem 🤗',
  7858. email='***',
  7859. timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
  7860. status='rejected',
  7861. fields=None,
  7862. ),
  7863. ...
  7864. ]
  7865. ```
  7866. """
  7867. return self._list_access_requests(repo_id, "rejected", repo_type=repo_type, token=token)
  7868. def _list_access_requests(
  7869. self,
  7870. repo_id: str,
  7871. status: Literal["accepted", "rejected", "pending"],
  7872. repo_type: Optional[str] = None,
  7873. token: Union[bool, str, None] = None,
  7874. ) -> List[AccessRequest]:
  7875. if repo_type not in constants.REPO_TYPES:
  7876. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  7877. if repo_type is None:
  7878. repo_type = constants.REPO_TYPE_MODEL
  7879. response = get_session().get(
  7880. f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/{status}",
  7881. headers=self._build_hf_headers(token=token),
  7882. )
  7883. hf_raise_for_status(response)
  7884. return [
  7885. AccessRequest(
  7886. username=request["user"]["user"],
  7887. fullname=request["user"]["fullname"],
  7888. email=request["user"].get("email"),
  7889. status=request["status"],
  7890. timestamp=parse_datetime(request["timestamp"]),
  7891. fields=request.get("fields"), # only if custom fields in form
  7892. )
  7893. for request in response.json()
  7894. ]
  7895. @validate_hf_hub_args
  7896. def cancel_access_request(
  7897. self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  7898. ) -> None:
  7899. """
  7900. Cancel an access request from a user for a given gated repo.
  7901. A cancelled request will go back to the pending list and the user will lose access to the repo.
  7902. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  7903. Args:
  7904. repo_id (`str`):
  7905. The id of the repo to cancel access request for.
  7906. user (`str`):
  7907. The username of the user which access request should be cancelled.
  7908. repo_type (`str`, *optional*):
  7909. The type of the repo to cancel access request for. Must be one of `model`, `dataset` or `space`.
  7910. Defaults to `model`.
  7911. token (`bool` or `str`, *optional*):
  7912. A valid user access token (string). Defaults to the locally saved
  7913. token, which is the recommended method for authentication (see
  7914. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7915. To disable authentication, pass `False`.
  7916. Raises:
  7917. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7918. HTTP 400 if the repo is not gated.
  7919. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7920. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  7921. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  7922. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7923. HTTP 404 if the user does not exist on the Hub.
  7924. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7925. HTTP 404 if the user access request cannot be found.
  7926. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7927. HTTP 404 if the user access request is already in the pending list.
  7928. """
  7929. self._handle_access_request(repo_id, user, "pending", repo_type=repo_type, token=token)
  7930. @validate_hf_hub_args
  7931. def accept_access_request(
  7932. self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  7933. ) -> None:
  7934. """
  7935. Accept an access request from a user for a given gated repo.
  7936. Once the request is accepted, the user will be able to download any file of the repo and access the community
  7937. tab. If the approval mode is automatic, you don't have to accept requests manually. An accepted request can be
  7938. cancelled or rejected at any time using [`cancel_access_request`] and [`reject_access_request`].
  7939. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  7940. Args:
  7941. repo_id (`str`):
  7942. The id of the repo to accept access request for.
  7943. user (`str`):
  7944. The username of the user which access request should be accepted.
  7945. repo_type (`str`, *optional*):
  7946. The type of the repo to accept access request for. Must be one of `model`, `dataset` or `space`.
  7947. Defaults to `model`.
  7948. token (`bool` or `str`, *optional*):
  7949. A valid user access token (string). Defaults to the locally saved
  7950. token, which is the recommended method for authentication (see
  7951. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7952. To disable authentication, pass `False`.
  7953. Raises:
  7954. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7955. HTTP 400 if the repo is not gated.
  7956. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7957. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  7958. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  7959. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7960. HTTP 404 if the user does not exist on the Hub.
  7961. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7962. HTTP 404 if the user access request cannot be found.
  7963. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  7964. HTTP 404 if the user access request is already in the accepted list.
  7965. """
  7966. self._handle_access_request(repo_id, user, "accepted", repo_type=repo_type, token=token)
  7967. @validate_hf_hub_args
  7968. def reject_access_request(
  7969. self,
  7970. repo_id: str,
  7971. user: str,
  7972. *,
  7973. repo_type: Optional[str] = None,
  7974. rejection_reason: Optional[str],
  7975. token: Union[bool, str, None] = None,
  7976. ) -> None:
  7977. """
  7978. Reject an access request from a user for a given gated repo.
  7979. A rejected request will go to the rejected list. The user cannot download any file of the repo. Rejected
  7980. requests can be accepted or cancelled at any time using [`accept_access_request`] and [`cancel_access_request`].
  7981. A cancelled request will go back to the pending list while an accepted request will go to the accepted list.
  7982. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  7983. Args:
  7984. repo_id (`str`):
  7985. The id of the repo to reject access request for.
  7986. user (`str`):
  7987. The username of the user which access request should be rejected.
  7988. repo_type (`str`, *optional*):
  7989. The type of the repo to reject access request for. Must be one of `model`, `dataset` or `space`.
  7990. Defaults to `model`.
  7991. rejection_reason (`str`, *optional*):
  7992. Optional rejection reason that will be visible to the user (max 200 characters).
  7993. token (`bool` or `str`, *optional*):
  7994. A valid user access token (string). Defaults to the locally saved
  7995. token, which is the recommended method for authentication (see
  7996. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  7997. To disable authentication, pass `False`.
  7998. Raises:
  7999. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8000. HTTP 400 if the repo is not gated.
  8001. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8002. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  8003. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  8004. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8005. HTTP 404 if the user does not exist on the Hub.
  8006. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8007. HTTP 404 if the user access request cannot be found.
  8008. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8009. HTTP 404 if the user access request is already in the rejected list.
  8010. """
  8011. self._handle_access_request(
  8012. repo_id, user, "rejected", repo_type=repo_type, rejection_reason=rejection_reason, token=token
  8013. )
  8014. @validate_hf_hub_args
  8015. def _handle_access_request(
  8016. self,
  8017. repo_id: str,
  8018. user: str,
  8019. status: Literal["accepted", "rejected", "pending"],
  8020. repo_type: Optional[str] = None,
  8021. rejection_reason: Optional[str] = None,
  8022. token: Union[bool, str, None] = None,
  8023. ) -> None:
  8024. if repo_type not in constants.REPO_TYPES:
  8025. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  8026. if repo_type is None:
  8027. repo_type = constants.REPO_TYPE_MODEL
  8028. payload = {"user": user, "status": status}
  8029. if rejection_reason is not None:
  8030. if status != "rejected":
  8031. raise ValueError("`rejection_reason` can only be passed when rejecting an access request.")
  8032. payload["rejectionReason"] = rejection_reason
  8033. response = get_session().post(
  8034. f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/handle",
  8035. headers=self._build_hf_headers(token=token),
  8036. json=payload,
  8037. )
  8038. hf_raise_for_status(response)
  8039. @validate_hf_hub_args
  8040. def grant_access(
  8041. self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  8042. ) -> None:
  8043. """
  8044. Grant access to a user for a given gated repo.
  8045. Granting access don't require for the user to send an access request by themselves. The user is automatically
  8046. added to the accepted list meaning they can download the files You can revoke the granted access at any time
  8047. using [`cancel_access_request`] or [`reject_access_request`].
  8048. For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
  8049. Args:
  8050. repo_id (`str`):
  8051. The id of the repo to grant access to.
  8052. user (`str`):
  8053. The username of the user to grant access.
  8054. repo_type (`str`, *optional*):
  8055. The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`.
  8056. Defaults to `model`.
  8057. token (`bool` or `str`, *optional*):
  8058. A valid user access token (string). Defaults to the locally saved
  8059. token, which is the recommended method for authentication (see
  8060. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8061. To disable authentication, pass `False`.
  8062. Raises:
  8063. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8064. HTTP 400 if the repo is not gated.
  8065. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8066. HTTP 400 if the user already has access to the repo.
  8067. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8068. HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
  8069. or `admin` role in the organization the repo belongs to or if you passed a `read` token.
  8070. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8071. HTTP 404 if the user does not exist on the Hub.
  8072. """
  8073. if repo_type not in constants.REPO_TYPES:
  8074. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  8075. if repo_type is None:
  8076. repo_type = constants.REPO_TYPE_MODEL
  8077. response = get_session().post(
  8078. f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/grant",
  8079. headers=self._build_hf_headers(token=token),
  8080. json={"user": user},
  8081. )
  8082. hf_raise_for_status(response)
  8083. return response.json()
  8084. ###################
  8085. # Manage webhooks #
  8086. ###################
  8087. @validate_hf_hub_args
  8088. def get_webhook(self, webhook_id: str, *, token: Union[bool, str, None] = None) -> WebhookInfo:
  8089. """Get a webhook by its id.
  8090. Args:
  8091. webhook_id (`str`):
  8092. The unique identifier of the webhook to get.
  8093. token (`bool` or `str`, *optional*):
  8094. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8095. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8096. To disable authentication, pass `False`.
  8097. Returns:
  8098. [`WebhookInfo`]:
  8099. Info about the webhook.
  8100. Example:
  8101. ```python
  8102. >>> from huggingface_hub import get_webhook
  8103. >>> webhook = get_webhook("654bbbc16f2ec14d77f109cc")
  8104. >>> print(webhook)
  8105. WebhookInfo(
  8106. id="654bbbc16f2ec14d77f109cc",
  8107. job=None,
  8108. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8109. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8110. secret="my-secret",
  8111. domains=["repo", "discussion"],
  8112. disabled=False,
  8113. )
  8114. ```
  8115. """
  8116. response = get_session().get(
  8117. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}",
  8118. headers=self._build_hf_headers(token=token),
  8119. )
  8120. hf_raise_for_status(response)
  8121. webhook_data = response.json()["webhook"]
  8122. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  8123. webhook = WebhookInfo(
  8124. id=webhook_data["id"],
  8125. url=webhook_data.get("url"),
  8126. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  8127. watched=watched_items,
  8128. domains=webhook_data["domains"],
  8129. secret=webhook_data.get("secret"),
  8130. disabled=webhook_data["disabled"],
  8131. )
  8132. return webhook
  8133. @validate_hf_hub_args
  8134. def list_webhooks(self, *, token: Union[bool, str, None] = None) -> List[WebhookInfo]:
  8135. """List all configured webhooks.
  8136. Args:
  8137. token (`bool` or `str`, *optional*):
  8138. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8139. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8140. To disable authentication, pass `False`.
  8141. Returns:
  8142. `List[WebhookInfo]`:
  8143. List of webhook info objects.
  8144. Example:
  8145. ```python
  8146. >>> from huggingface_hub import list_webhooks
  8147. >>> webhooks = list_webhooks()
  8148. >>> len(webhooks)
  8149. 2
  8150. >>> webhooks[0]
  8151. WebhookInfo(
  8152. id="654bbbc16f2ec14d77f109cc",
  8153. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8154. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8155. secret="my-secret",
  8156. domains=["repo", "discussion"],
  8157. disabled=False,
  8158. )
  8159. ```
  8160. """
  8161. response = get_session().get(
  8162. f"{constants.ENDPOINT}/api/settings/webhooks",
  8163. headers=self._build_hf_headers(token=token),
  8164. )
  8165. hf_raise_for_status(response)
  8166. webhooks_data = response.json()
  8167. return [
  8168. WebhookInfo(
  8169. id=webhook["id"],
  8170. url=webhook.get("url"),
  8171. job=JobSpec(**webhook["job"]) if webhook.get("job") else None,
  8172. watched=[WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook["watched"]],
  8173. domains=webhook["domains"],
  8174. secret=webhook.get("secret"),
  8175. disabled=webhook["disabled"],
  8176. )
  8177. for webhook in webhooks_data
  8178. ]
  8179. @validate_hf_hub_args
  8180. def create_webhook(
  8181. self,
  8182. *,
  8183. url: Optional[str] = None,
  8184. job_id: Optional[str] = None,
  8185. watched: List[Union[Dict, WebhookWatchedItem]],
  8186. domains: Optional[List[constants.WEBHOOK_DOMAIN_T]] = None,
  8187. secret: Optional[str] = None,
  8188. token: Union[bool, str, None] = None,
  8189. ) -> WebhookInfo:
  8190. """Create a new webhook.
  8191. The webhook can either send a payload to a URL, or trigger a Job to run on Hugging Face infrastructure.
  8192. This function should be called with one of `url` or `job_id`, but not both.
  8193. Args:
  8194. url (`str`):
  8195. URL to send the payload to.
  8196. job_id (`str`):
  8197. ID of the source Job to trigger with the webhook payload in the environment variable WEBHOOK_PAYLOAD.
  8198. Additional environment variables are available for convenience: WEBHOOK_REPO_ID, WEBHOOK_REPO_TYPE and WEBHOOK_SECRET.
  8199. watched (`List[WebhookWatchedItem]`):
  8200. List of [`WebhookWatchedItem`] to be watched by the webhook. It can be users, orgs, models, datasets or spaces.
  8201. Watched items can also be provided as plain dictionaries.
  8202. domains (`List[Literal["repo", "discussion"]]`, optional):
  8203. List of domains to watch. It can be "repo", "discussion" or both.
  8204. secret (`str`, optional):
  8205. A secret to sign the payload with.
  8206. token (`bool` or `str`, *optional*):
  8207. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8208. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8209. To disable authentication, pass `False`.
  8210. Returns:
  8211. [`WebhookInfo`]:
  8212. Info about the newly created webhook.
  8213. Example:
  8214. Create a webhook that sends a payload to a URL
  8215. ```python
  8216. >>> from huggingface_hub import create_webhook
  8217. >>> payload = create_webhook(
  8218. ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
  8219. ... url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8220. ... domains=["repo", "discussion"],
  8221. ... secret="my-secret",
  8222. ... )
  8223. >>> print(payload)
  8224. WebhookInfo(
  8225. id="654bbbc16f2ec14d77f109cc",
  8226. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8227. job=None,
  8228. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8229. domains=["repo", "discussion"],
  8230. secret="my-secret",
  8231. disabled=False,
  8232. )
  8233. ```
  8234. Run a Job and then create a webhook that triggers this Job
  8235. ```python
  8236. >>> from huggingface_hub import create_webhook, run_job
  8237. >>> job = run_job(
  8238. ... image="ubuntu",
  8239. ... command=["bash", "-c", r"echo An event occured in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD"],
  8240. ... )
  8241. >>> payload = create_webhook(
  8242. ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
  8243. ... job_id=job.id,
  8244. ... domains=["repo", "discussion"],
  8245. ... secret="my-secret",
  8246. ... )
  8247. >>> print(payload)
  8248. WebhookInfo(
  8249. id="654bbbc16f2ec14d77f109cc",
  8250. url=None,
  8251. job=JobSpec(
  8252. docker_image='ubuntu',
  8253. space_id=None,
  8254. command=['bash', '-c', 'echo An event occured in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD'],
  8255. arguments=[],
  8256. environment={},
  8257. secrets=[],
  8258. flavor='cpu-basic',
  8259. timeout=None,
  8260. tags=None,
  8261. arch=None
  8262. ),
  8263. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8264. domains=["repo", "discussion"],
  8265. secret="my-secret",
  8266. disabled=False,
  8267. )
  8268. ```
  8269. """
  8270. watched_dicts = [asdict(item) if isinstance(item, WebhookWatchedItem) else item for item in watched]
  8271. post_webhooks_json = {"watched": watched_dicts, "domains": domains, "secret": secret}
  8272. if url is not None and job_id is not None:
  8273. raise ValueError("Set `url` or `job_id` but not both.")
  8274. elif url is not None:
  8275. post_webhooks_json["url"] = url
  8276. elif job_id is not None:
  8277. post_webhooks_json["jobSourceId"] = job_id
  8278. else:
  8279. raise ValueError("Missing argument for webhook: `url` or `job_id`.")
  8280. response = get_session().post(
  8281. f"{constants.ENDPOINT}/api/settings/webhooks",
  8282. json=post_webhooks_json,
  8283. headers=self._build_hf_headers(token=token),
  8284. )
  8285. hf_raise_for_status(response)
  8286. webhook_data = response.json()["webhook"]
  8287. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  8288. webhook = WebhookInfo(
  8289. id=webhook_data["id"],
  8290. url=webhook_data.get("url"),
  8291. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  8292. watched=watched_items,
  8293. domains=webhook_data["domains"],
  8294. secret=webhook_data.get("secret"),
  8295. disabled=webhook_data["disabled"],
  8296. )
  8297. return webhook
  8298. @validate_hf_hub_args
  8299. def update_webhook(
  8300. self,
  8301. webhook_id: str,
  8302. *,
  8303. url: Optional[str] = None,
  8304. watched: Optional[List[Union[Dict, WebhookWatchedItem]]] = None,
  8305. domains: Optional[List[constants.WEBHOOK_DOMAIN_T]] = None,
  8306. secret: Optional[str] = None,
  8307. token: Union[bool, str, None] = None,
  8308. ) -> WebhookInfo:
  8309. """Update an existing webhook.
  8310. Args:
  8311. webhook_id (`str`):
  8312. The unique identifier of the webhook to be updated.
  8313. url (`str`, optional):
  8314. The URL to which the payload will be sent.
  8315. watched (`List[WebhookWatchedItem]`, optional):
  8316. List of items to watch. It can be users, orgs, models, datasets, or spaces.
  8317. Refer to [`WebhookWatchedItem`] for more details. Watched items can also be provided as plain dictionaries.
  8318. domains (`List[Literal["repo", "discussion"]]`, optional):
  8319. The domains to watch. This can include "repo", "discussion", or both.
  8320. secret (`str`, optional):
  8321. A secret to sign the payload with, providing an additional layer of security.
  8322. token (`bool` or `str`, *optional*):
  8323. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8324. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8325. To disable authentication, pass `False`.
  8326. Returns:
  8327. [`WebhookInfo`]:
  8328. Info about the updated webhook.
  8329. Example:
  8330. ```python
  8331. >>> from huggingface_hub import update_webhook
  8332. >>> updated_payload = update_webhook(
  8333. ... webhook_id="654bbbc16f2ec14d77f109cc",
  8334. ... url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8335. ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
  8336. ... domains=["repo"],
  8337. ... secret="my-secret",
  8338. ... )
  8339. >>> print(updated_payload)
  8340. WebhookInfo(
  8341. id="654bbbc16f2ec14d77f109cc",
  8342. job=None,
  8343. url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8344. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8345. domains=["repo"],
  8346. secret="my-secret",
  8347. disabled=False,
  8348. ```
  8349. """
  8350. if watched is None:
  8351. watched = []
  8352. watched_dicts = [asdict(item) if isinstance(item, WebhookWatchedItem) else item for item in watched]
  8353. response = get_session().post(
  8354. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}",
  8355. json={"watched": watched_dicts, "url": url, "domains": domains, "secret": secret},
  8356. headers=self._build_hf_headers(token=token),
  8357. )
  8358. hf_raise_for_status(response)
  8359. webhook_data = response.json()["webhook"]
  8360. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  8361. webhook = WebhookInfo(
  8362. id=webhook_data["id"],
  8363. url=webhook_data.get("url"),
  8364. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  8365. watched=watched_items,
  8366. domains=webhook_data["domains"],
  8367. secret=webhook_data.get("secret"),
  8368. disabled=webhook_data["disabled"],
  8369. )
  8370. return webhook
  8371. @validate_hf_hub_args
  8372. def enable_webhook(self, webhook_id: str, *, token: Union[bool, str, None] = None) -> WebhookInfo:
  8373. """Enable a webhook (makes it "active").
  8374. Args:
  8375. webhook_id (`str`):
  8376. The unique identifier of the webhook to enable.
  8377. token (`bool` or `str`, *optional*):
  8378. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8379. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8380. To disable authentication, pass `False`.
  8381. Returns:
  8382. [`WebhookInfo`]:
  8383. Info about the enabled webhook.
  8384. Example:
  8385. ```python
  8386. >>> from huggingface_hub import enable_webhook
  8387. >>> enabled_webhook = enable_webhook("654bbbc16f2ec14d77f109cc")
  8388. >>> enabled_webhook
  8389. WebhookInfo(
  8390. id="654bbbc16f2ec14d77f109cc",
  8391. job=None,
  8392. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8393. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8394. domains=["repo", "discussion"],
  8395. secret="my-secret",
  8396. disabled=False,
  8397. )
  8398. ```
  8399. """
  8400. response = get_session().post(
  8401. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}/enable",
  8402. headers=self._build_hf_headers(token=token),
  8403. )
  8404. hf_raise_for_status(response)
  8405. webhook_data = response.json()["webhook"]
  8406. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  8407. webhook = WebhookInfo(
  8408. id=webhook_data["id"],
  8409. url=webhook_data.get("url"),
  8410. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  8411. watched=watched_items,
  8412. domains=webhook_data["domains"],
  8413. secret=webhook_data.get("secret"),
  8414. disabled=webhook_data["disabled"],
  8415. )
  8416. return webhook
  8417. @validate_hf_hub_args
  8418. def disable_webhook(self, webhook_id: str, *, token: Union[bool, str, None] = None) -> WebhookInfo:
  8419. """Disable a webhook (makes it "disabled").
  8420. Args:
  8421. webhook_id (`str`):
  8422. The unique identifier of the webhook to disable.
  8423. token (`bool` or `str`, *optional*):
  8424. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8425. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8426. To disable authentication, pass `False`.
  8427. Returns:
  8428. [`WebhookInfo`]:
  8429. Info about the disabled webhook.
  8430. Example:
  8431. ```python
  8432. >>> from huggingface_hub import disable_webhook
  8433. >>> disabled_webhook = disable_webhook("654bbbc16f2ec14d77f109cc")
  8434. >>> disabled_webhook
  8435. WebhookInfo(
  8436. id="654bbbc16f2ec14d77f109cc",
  8437. url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
  8438. jon=None,
  8439. watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
  8440. domains=["repo", "discussion"],
  8441. secret="my-secret",
  8442. disabled=True,
  8443. )
  8444. ```
  8445. """
  8446. response = get_session().post(
  8447. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}/disable",
  8448. headers=self._build_hf_headers(token=token),
  8449. )
  8450. hf_raise_for_status(response)
  8451. webhook_data = response.json()["webhook"]
  8452. watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]]
  8453. webhook = WebhookInfo(
  8454. id=webhook_data["id"],
  8455. url=webhook_data.get("url"),
  8456. job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None,
  8457. watched=watched_items,
  8458. domains=webhook_data["domains"],
  8459. secret=webhook_data.get("secret"),
  8460. disabled=webhook_data["disabled"],
  8461. )
  8462. return webhook
  8463. @validate_hf_hub_args
  8464. def delete_webhook(self, webhook_id: str, *, token: Union[bool, str, None] = None) -> None:
  8465. """Delete a webhook.
  8466. Args:
  8467. webhook_id (`str`):
  8468. The unique identifier of the webhook to delete.
  8469. token (`bool` or `str`, *optional*):
  8470. A valid user access token (string). Defaults to the locally saved token, which is the recommended
  8471. method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8472. To disable authentication, pass `False`.
  8473. Returns:
  8474. `None`
  8475. Example:
  8476. ```python
  8477. >>> from huggingface_hub import delete_webhook
  8478. >>> delete_webhook("654bbbc16f2ec14d77f109cc")
  8479. ```
  8480. """
  8481. response = get_session().delete(
  8482. f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}",
  8483. headers=self._build_hf_headers(token=token),
  8484. )
  8485. hf_raise_for_status(response)
  8486. #############
  8487. # Internals #
  8488. #############
  8489. def _build_hf_headers(
  8490. self,
  8491. token: Union[bool, str, None] = None,
  8492. library_name: Optional[str] = None,
  8493. library_version: Optional[str] = None,
  8494. user_agent: Union[Dict, str, None] = None,
  8495. ) -> Dict[str, str]:
  8496. """
  8497. Alias for [`build_hf_headers`] that uses the token from [`HfApi`] client
  8498. when `token` is not provided.
  8499. """
  8500. if token is None:
  8501. # Cannot do `token = token or self.token` as token can be `False`.
  8502. token = self.token
  8503. return build_hf_headers(
  8504. token=token,
  8505. library_name=library_name or self.library_name,
  8506. library_version=library_version or self.library_version,
  8507. user_agent=user_agent or self.user_agent,
  8508. headers=self.headers,
  8509. )
  8510. def _prepare_folder_deletions(
  8511. self,
  8512. repo_id: str,
  8513. repo_type: Optional[str],
  8514. revision: Optional[str],
  8515. path_in_repo: str,
  8516. delete_patterns: Optional[Union[List[str], str]],
  8517. token: Union[bool, str, None] = None,
  8518. ) -> List[CommitOperationDelete]:
  8519. """Generate the list of Delete operations for a commit to delete files from a repo.
  8520. List remote files and match them against the `delete_patterns` constraints. Returns a list of [`CommitOperationDelete`]
  8521. with the matching items.
  8522. Note: `.gitattributes` file is essential to make a repo work properly on the Hub. This file will always be
  8523. kept even if it matches the `delete_patterns` constraints.
  8524. """
  8525. if delete_patterns is None:
  8526. # If no delete patterns, no need to list and filter remote files
  8527. return []
  8528. # List remote files
  8529. filenames = self.list_repo_files(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token)
  8530. # Compute relative path in repo
  8531. if path_in_repo and path_in_repo not in (".", "./"):
  8532. path_in_repo = path_in_repo.strip("/") + "/" # harmonize
  8533. relpath_to_abspath = {
  8534. file[len(path_in_repo) :]: file for file in filenames if file.startswith(path_in_repo)
  8535. }
  8536. else:
  8537. relpath_to_abspath = {file: file for file in filenames}
  8538. # Apply filter on relative paths and return
  8539. return [
  8540. CommitOperationDelete(path_in_repo=relpath_to_abspath[relpath], is_folder=False)
  8541. for relpath in filter_repo_objects(relpath_to_abspath.keys(), allow_patterns=delete_patterns)
  8542. if relpath_to_abspath[relpath] != ".gitattributes"
  8543. ]
  8544. def _prepare_upload_folder_additions(
  8545. self,
  8546. folder_path: Union[str, Path],
  8547. path_in_repo: str,
  8548. allow_patterns: Optional[Union[List[str], str]] = None,
  8549. ignore_patterns: Optional[Union[List[str], str]] = None,
  8550. repo_type: Optional[str] = None,
  8551. token: Union[bool, str, None] = None,
  8552. ) -> List[CommitOperationAdd]:
  8553. """Generate the list of Add operations for a commit to upload a folder.
  8554. Files not matching the `allow_patterns` (allowlist) and `ignore_patterns` (denylist)
  8555. constraints are discarded.
  8556. """
  8557. folder_path = Path(folder_path).expanduser().resolve()
  8558. if not folder_path.is_dir():
  8559. raise ValueError(f"Provided path: '{folder_path}' is not a directory")
  8560. # List files from folder
  8561. relpath_to_abspath = {
  8562. path.relative_to(folder_path).as_posix(): path
  8563. for path in sorted(folder_path.glob("**/*")) # sorted to be deterministic
  8564. if path.is_file()
  8565. }
  8566. # Filter files
  8567. # Patterns are applied on the path relative to `folder_path`. `path_in_repo` is prefixed after the filtering.
  8568. filtered_repo_objects = list(
  8569. filter_repo_objects(
  8570. relpath_to_abspath.keys(), allow_patterns=allow_patterns, ignore_patterns=ignore_patterns
  8571. )
  8572. )
  8573. prefix = f"{path_in_repo.strip('/')}/" if path_in_repo else ""
  8574. # If updating a README.md file, make sure the metadata format is valid
  8575. # It's better to fail early than to fail after all the files have been hashed.
  8576. if "README.md" in filtered_repo_objects:
  8577. self._validate_yaml(
  8578. content=relpath_to_abspath["README.md"].read_text(encoding="utf8"),
  8579. repo_type=repo_type,
  8580. token=token,
  8581. )
  8582. if len(filtered_repo_objects) > 30:
  8583. log = logger.warning if len(filtered_repo_objects) > 200 else logger.info
  8584. log(
  8585. "It seems you are trying to upload a large folder at once. This might take some time and then fail if "
  8586. "the folder is too large. For such cases, it is recommended to upload in smaller batches or to use "
  8587. "`HfApi().upload_large_folder(...)`/`hf upload-large-folder` instead. For more details, "
  8588. "check out https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#upload-a-large-folder."
  8589. )
  8590. logger.info(f"Start hashing {len(filtered_repo_objects)} files.")
  8591. operations = [
  8592. CommitOperationAdd(
  8593. path_or_fileobj=relpath_to_abspath[relpath], # absolute path on disk
  8594. path_in_repo=prefix + relpath, # "absolute" path in repo
  8595. )
  8596. for relpath in filtered_repo_objects
  8597. ]
  8598. logger.info(f"Finished hashing {len(filtered_repo_objects)} files.")
  8599. return operations
  8600. def _validate_yaml(self, content: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None):
  8601. """
  8602. Validate YAML from `README.md`, used before file hashing and upload.
  8603. Args:
  8604. content (`str`):
  8605. Content of `README.md` to validate.
  8606. repo_type (`str`, *optional*):
  8607. The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`.
  8608. Defaults to `model`.
  8609. token (`bool` or `str`, *optional*):
  8610. A valid user access token (string). Defaults to the locally saved
  8611. token, which is the recommended method for authentication (see
  8612. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8613. To disable authentication, pass `False`.
  8614. Raises:
  8615. - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  8616. if YAML is invalid
  8617. """
  8618. repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL
  8619. headers = self._build_hf_headers(token=token)
  8620. response = get_session().post(
  8621. f"{self.endpoint}/api/validate-yaml",
  8622. json={"content": content, "repoType": repo_type},
  8623. headers=headers,
  8624. )
  8625. # Handle warnings (example: empty metadata)
  8626. response_content = response.json()
  8627. message = "\n".join([f"- {warning.get('message')}" for warning in response_content.get("warnings", [])])
  8628. if message:
  8629. warnings.warn(f"Warnings while validating metadata in README.md:\n{message}")
  8630. # Raise on errors
  8631. try:
  8632. hf_raise_for_status(response)
  8633. except BadRequestError as e:
  8634. errors = response_content.get("errors", [])
  8635. message = "\n".join([f"- {error.get('message')}" for error in errors])
  8636. raise ValueError(f"Invalid metadata in README.md.\n{message}") from e
  8637. def get_user_overview(self, username: str, token: Union[bool, str, None] = None) -> User:
  8638. """
  8639. Get an overview of a user on the Hub.
  8640. Args:
  8641. username (`str`):
  8642. Username of the user to get an overview of.
  8643. token (`bool` or `str`, *optional*):
  8644. A valid user access token (string). Defaults to the locally saved
  8645. token, which is the recommended method for authentication (see
  8646. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8647. To disable authentication, pass `False`.
  8648. Returns:
  8649. `User`: A [`User`] object with the user's overview.
  8650. Raises:
  8651. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8652. HTTP 404 If the user does not exist on the Hub.
  8653. """
  8654. r = get_session().get(
  8655. f"{constants.ENDPOINT}/api/users/{username}/overview", headers=self._build_hf_headers(token=token)
  8656. )
  8657. hf_raise_for_status(r)
  8658. return User(**r.json())
  8659. @validate_hf_hub_args
  8660. def get_organization_overview(self, organization: str, token: Union[bool, str, None] = None) -> Organization:
  8661. """
  8662. Get an overview of an organization on the Hub.
  8663. Args:
  8664. organization (`str`):
  8665. Name of the organization to get an overview of.
  8666. token (`bool` or `str`, *optional*):
  8667. A valid user access token (string). Defaults to the locally saved token, which is the recommended method
  8668. for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8669. To disable authentication, pass `False`.
  8670. Returns:
  8671. `Organization`: An [`Organization`] object with the organization's overview.
  8672. Raises:
  8673. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8674. HTTP 404 If the organization does not exist on the Hub.
  8675. """
  8676. r = get_session().get(
  8677. f"{constants.ENDPOINT}/api/organizations/{organization}/overview",
  8678. headers=self._build_hf_headers(token=token),
  8679. )
  8680. hf_raise_for_status(r)
  8681. return Organization(**r.json())
  8682. def list_organization_members(self, organization: str, token: Union[bool, str, None] = None) -> Iterable[User]:
  8683. """
  8684. List of members of an organization on the Hub.
  8685. Args:
  8686. organization (`str`):
  8687. Name of the organization to get the members of.
  8688. token (`bool` or `str`, *optional*):
  8689. A valid user access token (string). Defaults to the locally saved
  8690. token, which is the recommended method for authentication (see
  8691. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8692. To disable authentication, pass `False`.
  8693. Returns:
  8694. `Iterable[User]`: A list of [`User`] objects with the members of the organization.
  8695. Raises:
  8696. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8697. HTTP 404 If the organization does not exist on the Hub.
  8698. """
  8699. for member in paginate(
  8700. path=f"{constants.ENDPOINT}/api/organizations/{organization}/members",
  8701. params={},
  8702. headers=self._build_hf_headers(token=token),
  8703. ):
  8704. yield User(**member)
  8705. def list_user_followers(self, username: str, token: Union[bool, str, None] = None) -> Iterable[User]:
  8706. """
  8707. Get the list of followers of a user on the Hub.
  8708. Args:
  8709. username (`str`):
  8710. Username of the user to get the followers of.
  8711. token (`bool` or `str`, *optional*):
  8712. A valid user access token (string). Defaults to the locally saved
  8713. token, which is the recommended method for authentication (see
  8714. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8715. To disable authentication, pass `False`.
  8716. Returns:
  8717. `Iterable[User]`: A list of [`User`] objects with the followers of the user.
  8718. Raises:
  8719. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8720. HTTP 404 If the user does not exist on the Hub.
  8721. """
  8722. for follower in paginate(
  8723. path=f"{constants.ENDPOINT}/api/users/{username}/followers",
  8724. params={},
  8725. headers=self._build_hf_headers(token=token),
  8726. ):
  8727. yield User(**follower)
  8728. def list_user_following(self, username: str, token: Union[bool, str, None] = None) -> Iterable[User]:
  8729. """
  8730. Get the list of users followed by a user on the Hub.
  8731. Args:
  8732. username (`str`):
  8733. Username of the user to get the users followed by.
  8734. token (`bool` or `str`, *optional*):
  8735. A valid user access token (string). Defaults to the locally saved
  8736. token, which is the recommended method for authentication (see
  8737. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8738. To disable authentication, pass `False`.
  8739. Returns:
  8740. `Iterable[User]`: A list of [`User`] objects with the users followed by the user.
  8741. Raises:
  8742. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8743. HTTP 404 If the user does not exist on the Hub.
  8744. """
  8745. for followed_user in paginate(
  8746. path=f"{constants.ENDPOINT}/api/users/{username}/following",
  8747. params={},
  8748. headers=self._build_hf_headers(token=token),
  8749. ):
  8750. yield User(**followed_user)
  8751. def list_papers(
  8752. self,
  8753. *,
  8754. query: Optional[str] = None,
  8755. token: Union[bool, str, None] = None,
  8756. ) -> Iterable[PaperInfo]:
  8757. """
  8758. List daily papers on the Hugging Face Hub given a search query.
  8759. Args:
  8760. query (`str`, *optional*):
  8761. A search query string to find papers.
  8762. If provided, returns papers that match the query.
  8763. token (Union[bool, str, None], *optional*):
  8764. A valid user access token (string). Defaults to the locally saved
  8765. token, which is the recommended method for authentication (see
  8766. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  8767. To disable authentication, pass `False`.
  8768. Returns:
  8769. `Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects.
  8770. Example:
  8771. ```python
  8772. >>> from huggingface_hub import HfApi
  8773. >>> api = HfApi()
  8774. # List all papers with "attention" in their title
  8775. >>> api.list_papers(query="attention")
  8776. ```
  8777. """
  8778. path = f"{self.endpoint}/api/papers/search"
  8779. params = {}
  8780. if query:
  8781. params["q"] = query
  8782. r = get_session().get(
  8783. path,
  8784. params=params,
  8785. headers=self._build_hf_headers(token=token),
  8786. )
  8787. hf_raise_for_status(r)
  8788. for paper in r.json():
  8789. yield PaperInfo(**paper)
  8790. def paper_info(self, id: str) -> PaperInfo:
  8791. """
  8792. Get information for a paper on the Hub.
  8793. Args:
  8794. id (`str`, **optional**):
  8795. ArXiv id of the paper.
  8796. Returns:
  8797. `PaperInfo`: A `PaperInfo` object.
  8798. Raises:
  8799. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
  8800. HTTP 404 If the paper does not exist on the Hub.
  8801. """
  8802. path = f"{self.endpoint}/api/papers/{id}"
  8803. r = get_session().get(path)
  8804. hf_raise_for_status(r)
  8805. return PaperInfo(**r.json())
  8806. def auth_check(
  8807. self, repo_id: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
  8808. ) -> None:
  8809. """
  8810. Check if the provided user token has access to a specific repository on the Hugging Face Hub.
  8811. This method verifies whether the user, authenticated via the provided token, has access to the specified
  8812. repository. If the repository is not found or if the user lacks the required permissions to access it,
  8813. the method raises an appropriate exception.
  8814. Args:
  8815. repo_id (`str`):
  8816. The repository to check for access. Format should be `"user/repo_name"`.
  8817. Example: `"user/my-cool-model"`.
  8818. repo_type (`str`, *optional*):
  8819. The type of the repository. Should be one of `"model"`, `"dataset"`, or `"space"`.
  8820. If not specified, the default is `"model"`.
  8821. token `(Union[bool, str, None]`, *optional*):
  8822. A valid user access token. If not provided, the locally saved token will be used, which is the
  8823. recommended authentication method. Set to `False` to disable authentication.
  8824. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  8825. Raises:
  8826. [`~utils.RepositoryNotFoundError`]:
  8827. Raised if the repository does not exist, is private, or the user does not have access. This can
  8828. occur if the `repo_id` or `repo_type` is incorrect or if the repository is private but the user
  8829. is not authenticated.
  8830. [`~utils.GatedRepoError`]:
  8831. Raised if the repository exists but is gated and the user is not authorized to access it.
  8832. Example:
  8833. Check if the user has access to a repository:
  8834. ```python
  8835. >>> from huggingface_hub import auth_check
  8836. >>> from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
  8837. try:
  8838. auth_check("user/my-cool-model")
  8839. except GatedRepoError:
  8840. # Handle gated repository error
  8841. print("You do not have permission to access this gated repository.")
  8842. except RepositoryNotFoundError:
  8843. # Handle repository not found error
  8844. print("The repository was not found or you do not have access.")
  8845. ```
  8846. In this example:
  8847. - If the user has access, the method completes successfully.
  8848. - If the repository is gated or does not exist, appropriate exceptions are raised, allowing the user
  8849. to handle them accordingly.
  8850. """
  8851. headers = self._build_hf_headers(token=token)
  8852. if repo_type is None:
  8853. repo_type = constants.REPO_TYPE_MODEL
  8854. if repo_type not in constants.REPO_TYPES:
  8855. raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}")
  8856. path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/auth-check"
  8857. r = get_session().get(path, headers=headers)
  8858. hf_raise_for_status(r)
  8859. def run_job(
  8860. self,
  8861. *,
  8862. image: str,
  8863. command: List[str],
  8864. env: Optional[Dict[str, Any]] = None,
  8865. secrets: Optional[Dict[str, Any]] = None,
  8866. flavor: Optional[SpaceHardware] = None,
  8867. timeout: Optional[Union[int, float, str]] = None,
  8868. namespace: Optional[str] = None,
  8869. token: Union[bool, str, None] = None,
  8870. ) -> JobInfo:
  8871. """
  8872. Run compute Jobs on Hugging Face infrastructure.
  8873. Args:
  8874. image (`str`):
  8875. The Docker image to use.
  8876. Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`.
  8877. Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`.
  8878. command (`List[str]`):
  8879. The command to run. Example: `["echo", "hello"]`.
  8880. env (`Dict[str, Any]`, *optional*):
  8881. Defines the environment variables for the Job.
  8882. secrets (`Dict[str, Any]`, *optional*):
  8883. Defines the secret environment variables for the Job.
  8884. flavor (`str`, *optional*):
  8885. Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
  8886. Defaults to `"cpu-basic"`.
  8887. timeout (`Union[int, float, str]`, *optional*):
  8888. Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days).
  8889. Example: `300` or `"5m"` for 5 minutes.
  8890. namespace (`str`, *optional*):
  8891. The namespace where the Job will be created. Defaults to the current user's namespace.
  8892. token `(Union[bool, str, None]`, *optional*):
  8893. A valid user access token. If not provided, the locally saved token will be used, which is the
  8894. recommended authentication method. Set to `False` to disable authentication.
  8895. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  8896. Example:
  8897. Run your first Job:
  8898. ```python
  8899. >>> from huggingface_hub import run_job
  8900. >>> run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
  8901. ```
  8902. Run a GPU Job:
  8903. ```python
  8904. >>> from huggingface_hub import run_job
  8905. >>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
  8906. >>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
  8907. >>> run_job(image=image, command=command, flavor="a10g-small")
  8908. ```
  8909. """
  8910. if namespace is None:
  8911. namespace = self.whoami(token=token)["name"]
  8912. job_spec = _create_job_spec(
  8913. image=image,
  8914. command=command,
  8915. env=env,
  8916. secrets=secrets,
  8917. flavor=flavor,
  8918. timeout=timeout,
  8919. )
  8920. response = get_session().post(
  8921. f"https://huggingface.co/api/jobs/{namespace}",
  8922. json=job_spec,
  8923. headers=self._build_hf_headers(token=token),
  8924. )
  8925. hf_raise_for_status(response)
  8926. job_info = response.json()
  8927. return JobInfo(**job_info, endpoint=self.endpoint)
  8928. def fetch_job_logs(
  8929. self,
  8930. *,
  8931. job_id: str,
  8932. namespace: Optional[str] = None,
  8933. token: Union[bool, str, None] = None,
  8934. ) -> Iterable[str]:
  8935. """
  8936. Fetch all the logs from a compute Job on Hugging Face infrastructure.
  8937. Args:
  8938. job_id (`str`):
  8939. ID of the Job.
  8940. namespace (`str`, *optional*):
  8941. The namespace where the Job is running. Defaults to the current user's namespace.
  8942. token `(Union[bool, str, None]`, *optional*):
  8943. A valid user access token. If not provided, the locally saved token will be used, which is the
  8944. recommended authentication method. Set to `False` to disable authentication.
  8945. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  8946. Example:
  8947. ```python
  8948. >>> from huggingface_hub import fetch_job_logs, run_job
  8949. >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
  8950. >>> for log in fetch_job_logs(job.id):
  8951. ... print(log)
  8952. Hello from HF compute!
  8953. ```
  8954. """
  8955. if namespace is None:
  8956. namespace = self.whoami(token=token)["name"]
  8957. logging_finished = logging_started = False
  8958. job_finished = False
  8959. # - We need to retry because sometimes the /logs doesn't return logs when the job just started.
  8960. # (for example it can return only two lines: one for "Job started" and one empty line)
  8961. # - Timeouts can happen in case of build errors
  8962. # - ChunkedEncodingError can happen in case of stopped logging in the middle of streaming
  8963. # - Infinite empty log stream can happen in case of build error
  8964. # (the logs stream is infinite and empty except for the Job started message)
  8965. # - there is a ": keep-alive" every 30 seconds
  8966. # We don't use http_backoff since we need to check ourselves if ConnectionError.__context__ is a TimeoutError
  8967. max_retries = 5
  8968. min_wait_time = 1
  8969. max_wait_time = 10
  8970. sleep_time = 0
  8971. for _ in range(max_retries):
  8972. time.sleep(sleep_time)
  8973. sleep_time = min(max_wait_time, max(min_wait_time, sleep_time * 2))
  8974. try:
  8975. resp = get_session().get(
  8976. f"https://huggingface.co/api/jobs/{namespace}/{job_id}/logs",
  8977. headers=self._build_hf_headers(token=token),
  8978. stream=True,
  8979. timeout=120,
  8980. )
  8981. log = None
  8982. for line in resp.iter_lines(chunk_size=1):
  8983. line = line.decode("utf-8")
  8984. if line and line.startswith("data: {"):
  8985. data = json.loads(line[len("data: ") :])
  8986. # timestamp = data["timestamp"]
  8987. if not data["data"].startswith("===== Job started"):
  8988. logging_started = True
  8989. log = data["data"]
  8990. yield log
  8991. logging_finished = logging_started
  8992. except requests.exceptions.ChunkedEncodingError:
  8993. # Response ended prematurely
  8994. break
  8995. except KeyboardInterrupt:
  8996. break
  8997. except requests.exceptions.ConnectionError as err:
  8998. is_timeout = err.__context__ and isinstance(getattr(err.__context__, "__cause__", None), TimeoutError)
  8999. if logging_started or not is_timeout:
  9000. raise
  9001. if logging_finished or job_finished:
  9002. break
  9003. job_status = (
  9004. get_session()
  9005. .get(
  9006. f"https://huggingface.co/api/jobs/{namespace}/{job_id}",
  9007. headers=self._build_hf_headers(token=token),
  9008. )
  9009. .json()
  9010. )
  9011. if "status" in job_status and job_status["status"]["stage"] not in ("RUNNING", "UPDATING"):
  9012. job_finished = True
  9013. def list_jobs(
  9014. self,
  9015. *,
  9016. timeout: Optional[int] = None,
  9017. namespace: Optional[str] = None,
  9018. token: Union[bool, str, None] = None,
  9019. ) -> List[JobInfo]:
  9020. """
  9021. List compute Jobs on Hugging Face infrastructure.
  9022. Args:
  9023. timeout (`float`, *optional*):
  9024. Whether to set a timeout for the request to the Hub.
  9025. namespace (`str`, *optional*):
  9026. The namespace from where it lists the jobs. Defaults to the current user's namespace.
  9027. token `(Union[bool, str, None]`, *optional*):
  9028. A valid user access token. If not provided, the locally saved token will be used, which is the
  9029. recommended authentication method. Set to `False` to disable authentication.
  9030. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9031. """
  9032. if namespace is None:
  9033. namespace = whoami(token=token)["name"]
  9034. response = get_session().get(
  9035. f"{self.endpoint}/api/jobs/{namespace}",
  9036. headers=self._build_hf_headers(token=token),
  9037. timeout=timeout,
  9038. )
  9039. response.raise_for_status()
  9040. return [JobInfo(**job_info, endpoint=self.endpoint) for job_info in response.json()]
  9041. def inspect_job(
  9042. self,
  9043. *,
  9044. job_id: str,
  9045. namespace: Optional[str] = None,
  9046. token: Union[bool, str, None] = None,
  9047. ) -> JobInfo:
  9048. """
  9049. Inspect a compute Job on Hugging Face infrastructure.
  9050. Args:
  9051. job_id (`str`):
  9052. ID of the Job.
  9053. namespace (`str`, *optional*):
  9054. The namespace where the Job is running. Defaults to the current user's namespace.
  9055. token `(Union[bool, str, None]`, *optional*):
  9056. A valid user access token. If not provided, the locally saved token will be used, which is the
  9057. recommended authentication method. Set to `False` to disable authentication.
  9058. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9059. Example:
  9060. ```python
  9061. >>> from huggingface_hub import inspect_job, run_job
  9062. >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
  9063. >>> inspect_job(job.id)
  9064. JobInfo(
  9065. id='68780d00bbe36d38803f645f',
  9066. created_at=datetime.datetime(2025, 7, 16, 20, 35, 12, 808000, tzinfo=datetime.timezone.utc),
  9067. docker_image='python:3.12',
  9068. space_id=None,
  9069. command=['python', '-c', "print('Hello from HF compute!')"],
  9070. arguments=[],
  9071. environment={},
  9072. secrets={},
  9073. flavor='cpu-basic',
  9074. status=JobStatus(stage='RUNNING', message=None)
  9075. )
  9076. ```
  9077. """
  9078. if namespace is None:
  9079. namespace = self.whoami(token=token)["name"]
  9080. response = get_session().get(
  9081. f"{self.endpoint}/api/jobs/{namespace}/{job_id}",
  9082. headers=self._build_hf_headers(token=token),
  9083. )
  9084. response.raise_for_status()
  9085. return JobInfo(**response.json(), endpoint=self.endpoint)
  9086. def cancel_job(
  9087. self,
  9088. *,
  9089. job_id: str,
  9090. namespace: Optional[str] = None,
  9091. token: Union[bool, str, None] = None,
  9092. ) -> None:
  9093. """
  9094. Cancel a compute Job on Hugging Face infrastructure.
  9095. Args:
  9096. job_id (`str`):
  9097. ID of the Job.
  9098. namespace (`str`, *optional*):
  9099. The namespace where the Job is running. Defaults to the current user's namespace.
  9100. token `(Union[bool, str, None]`, *optional*):
  9101. A valid user access token. If not provided, the locally saved token will be used, which is the
  9102. recommended authentication method. Set to `False` to disable authentication.
  9103. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9104. """
  9105. if namespace is None:
  9106. namespace = self.whoami(token=token)["name"]
  9107. get_session().post(
  9108. f"{self.endpoint}/api/jobs/{namespace}/{job_id}/cancel",
  9109. headers=self._build_hf_headers(token=token),
  9110. ).raise_for_status()
  9111. @experimental
  9112. def run_uv_job(
  9113. self,
  9114. script: str,
  9115. *,
  9116. script_args: Optional[List[str]] = None,
  9117. dependencies: Optional[List[str]] = None,
  9118. python: Optional[str] = None,
  9119. image: Optional[str] = None,
  9120. env: Optional[Dict[str, Any]] = None,
  9121. secrets: Optional[Dict[str, Any]] = None,
  9122. flavor: Optional[SpaceHardware] = None,
  9123. timeout: Optional[Union[int, float, str]] = None,
  9124. namespace: Optional[str] = None,
  9125. token: Union[bool, str, None] = None,
  9126. _repo: Optional[str] = None,
  9127. ) -> JobInfo:
  9128. """
  9129. Run a UV script Job on Hugging Face infrastructure.
  9130. Args:
  9131. script (`str`):
  9132. Path or URL of the UV script, or a command.
  9133. script_args (`List[str]`, *optional*)
  9134. Arguments to pass to the script or command.
  9135. dependencies (`List[str]`, *optional*)
  9136. Dependencies to use to run the UV script.
  9137. python (`str`, *optional*)
  9138. Use a specific Python version. Default is 3.12.
  9139. image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"):
  9140. Use a custom Docker image with `uv` installed.
  9141. env (`Dict[str, Any]`, *optional*):
  9142. Defines the environment variables for the Job.
  9143. secrets (`Dict[str, Any]`, *optional*):
  9144. Defines the secret environment variables for the Job.
  9145. flavor (`str`, *optional*):
  9146. Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
  9147. Defaults to `"cpu-basic"`.
  9148. timeout (`Union[int, float, str]`, *optional*):
  9149. Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days).
  9150. Example: `300` or `"5m"` for 5 minutes.
  9151. namespace (`str`, *optional*):
  9152. The namespace where the Job will be created. Defaults to the current user's namespace.
  9153. token `(Union[bool, str, None]`, *optional*):
  9154. A valid user access token. If not provided, the locally saved token will be used, which is the
  9155. recommended authentication method. Set to `False` to disable authentication.
  9156. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9157. Example:
  9158. Run a script from a URL:
  9159. ```python
  9160. >>> from huggingface_hub import run_uv_job
  9161. >>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
  9162. >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
  9163. >>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")
  9164. ```
  9165. Run a local script:
  9166. ```python
  9167. >>> from huggingface_hub import run_uv_job
  9168. >>> script = "my_sft.py"
  9169. >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
  9170. >>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")
  9171. ```
  9172. Run a command:
  9173. ```python
  9174. >>> from huggingface_hub import run_uv_job
  9175. >>> script = "lighteval"
  9176. >>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
  9177. >>> run_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small")
  9178. ```
  9179. """
  9180. image = image or "ghcr.io/astral-sh/uv:python3.12-bookworm"
  9181. env = env or {}
  9182. secrets = secrets or {}
  9183. # Build command
  9184. command, env, secrets = self._create_uv_command_env_and_secrets(
  9185. script=script,
  9186. script_args=script_args,
  9187. dependencies=dependencies,
  9188. python=python,
  9189. env=env,
  9190. secrets=secrets,
  9191. namespace=namespace,
  9192. token=token,
  9193. _repo=_repo,
  9194. )
  9195. # Create RunCommand args
  9196. return self.run_job(
  9197. image=image,
  9198. command=command,
  9199. env=env,
  9200. secrets=secrets,
  9201. flavor=flavor,
  9202. timeout=timeout,
  9203. namespace=namespace,
  9204. token=token,
  9205. )
  9206. def create_scheduled_job(
  9207. self,
  9208. *,
  9209. image: str,
  9210. command: List[str],
  9211. schedule: str,
  9212. suspend: Optional[bool] = None,
  9213. concurrency: Optional[bool] = None,
  9214. env: Optional[Dict[str, Any]] = None,
  9215. secrets: Optional[Dict[str, Any]] = None,
  9216. flavor: Optional[SpaceHardware] = None,
  9217. timeout: Optional[Union[int, float, str]] = None,
  9218. namespace: Optional[str] = None,
  9219. token: Union[bool, str, None] = None,
  9220. ) -> ScheduledJobInfo:
  9221. """
  9222. Create scheduled compute Jobs on Hugging Face infrastructure.
  9223. Args:
  9224. image (`str`):
  9225. The Docker image to use.
  9226. Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`.
  9227. Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`.
  9228. command (`List[str]`):
  9229. The command to run. Example: `["echo", "hello"]`.
  9230. schedule (`str`):
  9231. One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
  9232. CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
  9233. suspend (`bool`, *optional*):
  9234. If True, the scheduled Job is suspended (paused). Defaults to False.
  9235. concurrency (`bool`, *optional*):
  9236. If True, multiple instances of this Job can run concurrently. Defaults to False.
  9237. env (`Dict[str, Any]`, *optional*):
  9238. Defines the environment variables for the Job.
  9239. secrets (`Dict[str, Any]`, *optional*):
  9240. Defines the secret environment variables for the Job.
  9241. flavor (`str`, *optional*):
  9242. Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
  9243. Defaults to `"cpu-basic"`.
  9244. timeout (`Union[int, float, str]`, *optional*):
  9245. Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days).
  9246. Example: `300` or `"5m"` for 5 minutes.
  9247. namespace (`str`, *optional*):
  9248. The namespace where the Job will be created. Defaults to the current user's namespace.
  9249. token `(Union[bool, str, None]`, *optional*):
  9250. A valid user access token. If not provided, the locally saved token will be used, which is the
  9251. recommended authentication method. Set to `False` to disable authentication.
  9252. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9253. Example:
  9254. Create your first scheduled Job:
  9255. ```python
  9256. >>> from huggingface_hub import create_scheduled_job
  9257. >>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")
  9258. ```
  9259. Use a CRON schedule expression:
  9260. ```python
  9261. >>> from huggingface_hub import create_scheduled_job
  9262. >>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('this runs every 5min')"], schedule="*/5 * * * *")
  9263. ```
  9264. Create a scheduled GPU Job:
  9265. ```python
  9266. >>> from huggingface_hub import create_scheduled_job
  9267. >>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
  9268. >>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
  9269. >>> create_scheduled_job(image, command, flavor="a10g-small", schedule="@hourly")
  9270. ```
  9271. """
  9272. if namespace is None:
  9273. namespace = self.whoami(token=token)["name"]
  9274. # prepare payload to send to HF Jobs API
  9275. job_spec = _create_job_spec(
  9276. image=image,
  9277. command=command,
  9278. env=env,
  9279. secrets=secrets,
  9280. flavor=flavor,
  9281. timeout=timeout,
  9282. )
  9283. input_json: Dict[str, Any] = {
  9284. "jobSpec": job_spec,
  9285. "schedule": schedule,
  9286. }
  9287. if concurrency is not None:
  9288. input_json["concurrency"] = concurrency
  9289. if suspend is not None:
  9290. input_json["suspend"] = suspend
  9291. response = get_session().post(
  9292. f"https://huggingface.co/api/scheduled-jobs/{namespace}",
  9293. json=input_json,
  9294. headers=self._build_hf_headers(token=token),
  9295. )
  9296. hf_raise_for_status(response)
  9297. scheduled_job_info = response.json()
  9298. return ScheduledJobInfo(**scheduled_job_info)
  9299. def list_scheduled_jobs(
  9300. self,
  9301. *,
  9302. timeout: Optional[int] = None,
  9303. namespace: Optional[str] = None,
  9304. token: Union[bool, str, None] = None,
  9305. ) -> List[ScheduledJobInfo]:
  9306. """
  9307. List scheduled compute Jobs on Hugging Face infrastructure.
  9308. Args:
  9309. timeout (`float`, *optional*):
  9310. Whether to set a timeout for the request to the Hub.
  9311. namespace (`str`, *optional*):
  9312. The namespace from where it lists the jobs. Defaults to the current user's namespace.
  9313. token `(Union[bool, str, None]`, *optional*):
  9314. A valid user access token. If not provided, the locally saved token will be used, which is the
  9315. recommended authentication method. Set to `False` to disable authentication.
  9316. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9317. """
  9318. if namespace is None:
  9319. namespace = self.whoami(token=token)["name"]
  9320. response = get_session().get(
  9321. f"{self.endpoint}/api/scheduled-jobs/{namespace}",
  9322. headers=self._build_hf_headers(token=token),
  9323. timeout=timeout,
  9324. )
  9325. hf_raise_for_status(response)
  9326. return [ScheduledJobInfo(**scheduled_job_info) for scheduled_job_info in response.json()]
  9327. def inspect_scheduled_job(
  9328. self,
  9329. *,
  9330. scheduled_job_id: str,
  9331. namespace: Optional[str] = None,
  9332. token: Union[bool, str, None] = None,
  9333. ) -> ScheduledJobInfo:
  9334. """
  9335. Inspect a scheduled compute Job on Hugging Face infrastructure.
  9336. Args:
  9337. scheduled_job_id (`str`):
  9338. ID of the scheduled Job.
  9339. namespace (`str`, *optional*):
  9340. The namespace where the scheduled Job is. Defaults to the current user's namespace.
  9341. token `(Union[bool, str, None]`, *optional*):
  9342. A valid user access token. If not provided, the locally saved token will be used, which is the
  9343. recommended authentication method. Set to `False` to disable authentication.
  9344. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9345. Example:
  9346. ```python
  9347. >>> from huggingface_hub import inspect_job, create_scheduled_job
  9348. >>> scheduled_job = create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")
  9349. >>> inspect_scheduled_job(scheduled_job.id)
  9350. ```
  9351. """
  9352. if namespace is None:
  9353. namespace = self.whoami(token=token)["name"]
  9354. response = get_session().get(
  9355. f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}",
  9356. headers=self._build_hf_headers(token=token),
  9357. )
  9358. hf_raise_for_status(response)
  9359. return ScheduledJobInfo(**response.json())
  9360. def delete_scheduled_job(
  9361. self,
  9362. *,
  9363. scheduled_job_id: str,
  9364. namespace: Optional[str] = None,
  9365. token: Union[bool, str, None] = None,
  9366. ) -> None:
  9367. """
  9368. Delete a scheduled compute Job on Hugging Face infrastructure.
  9369. Args:
  9370. scheduled_job_id (`str`):
  9371. ID of the scheduled Job.
  9372. namespace (`str`, *optional*):
  9373. The namespace where the scheduled Job is. Defaults to the current user's namespace.
  9374. token `(Union[bool, str, None]`, *optional*):
  9375. A valid user access token. If not provided, the locally saved token will be used, which is the
  9376. recommended authentication method. Set to `False` to disable authentication.
  9377. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9378. """
  9379. if namespace is None:
  9380. namespace = self.whoami(token=token)["name"]
  9381. response = get_session().delete(
  9382. f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}",
  9383. headers=self._build_hf_headers(token=token),
  9384. )
  9385. hf_raise_for_status(response)
  9386. def suspend_scheduled_job(
  9387. self,
  9388. *,
  9389. scheduled_job_id: str,
  9390. namespace: Optional[str] = None,
  9391. token: Union[bool, str, None] = None,
  9392. ) -> None:
  9393. """
  9394. Suspend (pause) a scheduled compute Job on Hugging Face infrastructure.
  9395. Args:
  9396. scheduled_job_id (`str`):
  9397. ID of the scheduled Job.
  9398. namespace (`str`, *optional*):
  9399. The namespace where the scheduled Job is. Defaults to the current user's namespace.
  9400. token `(Union[bool, str, None]`, *optional*):
  9401. A valid user access token. If not provided, the locally saved token will be used, which is the
  9402. recommended authentication method. Set to `False` to disable authentication.
  9403. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9404. """
  9405. if namespace is None:
  9406. namespace = self.whoami(token=token)["name"]
  9407. get_session().post(
  9408. f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}/suspend",
  9409. headers=self._build_hf_headers(token=token),
  9410. ).raise_for_status()
  9411. def resume_scheduled_job(
  9412. self,
  9413. *,
  9414. scheduled_job_id: str,
  9415. namespace: Optional[str] = None,
  9416. token: Union[bool, str, None] = None,
  9417. ) -> None:
  9418. """
  9419. Resume (unpause) a scheduled compute Job on Hugging Face infrastructure.
  9420. Args:
  9421. scheduled_job_id (`str`):
  9422. ID of the scheduled Job.
  9423. namespace (`str`, *optional*):
  9424. The namespace where the scheduled Job is. Defaults to the current user's namespace.
  9425. token `(Union[bool, str, None]`, *optional*):
  9426. A valid user access token. If not provided, the locally saved token will be used, which is the
  9427. recommended authentication method. Set to `False` to disable authentication.
  9428. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9429. """
  9430. if namespace is None:
  9431. namespace = self.whoami(token=token)["name"]
  9432. get_session().post(
  9433. f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}/resume",
  9434. headers=self._build_hf_headers(token=token),
  9435. ).raise_for_status()
  9436. @experimental
  9437. def create_scheduled_uv_job(
  9438. self,
  9439. script: str,
  9440. *,
  9441. script_args: Optional[List[str]] = None,
  9442. schedule: str,
  9443. suspend: Optional[bool] = None,
  9444. concurrency: Optional[bool] = None,
  9445. dependencies: Optional[List[str]] = None,
  9446. python: Optional[str] = None,
  9447. image: Optional[str] = None,
  9448. env: Optional[Dict[str, Any]] = None,
  9449. secrets: Optional[Dict[str, Any]] = None,
  9450. flavor: Optional[SpaceHardware] = None,
  9451. timeout: Optional[Union[int, float, str]] = None,
  9452. namespace: Optional[str] = None,
  9453. token: Union[bool, str, None] = None,
  9454. _repo: Optional[str] = None,
  9455. ) -> ScheduledJobInfo:
  9456. """
  9457. Run a UV script Job on Hugging Face infrastructure.
  9458. Args:
  9459. script (`str`):
  9460. Path or URL of the UV script, or a command.
  9461. script_args (`List[str]`, *optional*)
  9462. Arguments to pass to the script, or a command.
  9463. schedule (`str`):
  9464. One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
  9465. CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
  9466. suspend (`bool`, *optional*):
  9467. If True, the scheduled Job is suspended (paused). Defaults to False.
  9468. concurrency (`bool`, *optional*):
  9469. If True, multiple instances of this Job can run concurrently. Defaults to False.
  9470. dependencies (`List[str]`, *optional*)
  9471. Dependencies to use to run the UV script.
  9472. python (`str`, *optional*)
  9473. Use a specific Python version. Default is 3.12.
  9474. image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"):
  9475. Use a custom Docker image with `uv` installed.
  9476. env (`Dict[str, Any]`, *optional*):
  9477. Defines the environment variables for the Job.
  9478. secrets (`Dict[str, Any]`, *optional*):
  9479. Defines the secret environment variables for the Job.
  9480. flavor (`str`, *optional*):
  9481. Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
  9482. Defaults to `"cpu-basic"`.
  9483. timeout (`Union[int, float, str]`, *optional*):
  9484. Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days).
  9485. Example: `300` or `"5m"` for 5 minutes.
  9486. namespace (`str`, *optional*):
  9487. The namespace where the Job will be created. Defaults to the current user's namespace.
  9488. token `(Union[bool, str, None]`, *optional*):
  9489. A valid user access token. If not provided, the locally saved token will be used, which is the
  9490. recommended authentication method. Set to `False` to disable authentication.
  9491. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
  9492. Example:
  9493. Schedule a script from a URL:
  9494. ```python
  9495. >>> from huggingface_hub import create_scheduled_uv_job
  9496. >>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
  9497. >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
  9498. >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")
  9499. ```
  9500. Schedule a local script:
  9501. ```python
  9502. >>> from huggingface_hub import create_scheduled_uv_job
  9503. >>> script = "my_sft.py"
  9504. >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
  9505. >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")
  9506. ```
  9507. Schedule a command:
  9508. ```python
  9509. >>> from huggingface_hub import create_scheduled_uv_job
  9510. >>> script = "lighteval"
  9511. >>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
  9512. >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small", schedule="@weekly")
  9513. ```
  9514. """
  9515. image = image or "ghcr.io/astral-sh/uv:python3.12-bookworm"
  9516. # Build command
  9517. command, env, secrets = self._create_uv_command_env_and_secrets(
  9518. script=script,
  9519. script_args=script_args,
  9520. dependencies=dependencies,
  9521. python=python,
  9522. env=env,
  9523. secrets=secrets,
  9524. namespace=namespace,
  9525. token=token,
  9526. _repo=_repo,
  9527. )
  9528. # Create RunCommand args
  9529. return self.create_scheduled_job(
  9530. image=image,
  9531. command=command,
  9532. schedule=schedule,
  9533. suspend=suspend,
  9534. concurrency=concurrency,
  9535. env=env,
  9536. secrets=secrets,
  9537. flavor=flavor,
  9538. timeout=timeout,
  9539. namespace=namespace,
  9540. token=token,
  9541. )
  9542. def _create_uv_command_env_and_secrets(
  9543. self,
  9544. *,
  9545. script: str,
  9546. script_args: Optional[List[str]],
  9547. dependencies: Optional[List[str]],
  9548. python: Optional[str],
  9549. env: Optional[Dict[str, Any]],
  9550. secrets: Optional[Dict[str, Any]],
  9551. namespace: Optional[str],
  9552. token: Union[bool, str, None],
  9553. _repo: Optional[str],
  9554. ) -> Tuple[List[str], Dict[str, Any], Dict[str, Any]]:
  9555. env = env or {}
  9556. secrets = secrets or {}
  9557. # Build command
  9558. uv_args = []
  9559. if dependencies:
  9560. for dependency in dependencies:
  9561. uv_args += ["--with", dependency]
  9562. if python:
  9563. uv_args += ["--python", python]
  9564. script_args = script_args or []
  9565. if namespace is None:
  9566. namespace = self.whoami(token=token)["name"]
  9567. is_url = script.startswith("http://") or script.startswith("https://")
  9568. if is_url or not Path(script).is_file():
  9569. # Direct URL execution or command - no upload needed
  9570. command = ["uv", "run"] + uv_args + [script] + script_args
  9571. else:
  9572. # Local file - upload to HF
  9573. script_path = Path(script)
  9574. filename = script_path.name
  9575. # Parse repo
  9576. if _repo:
  9577. repo_id = _repo
  9578. if "/" not in repo_id:
  9579. repo_id = f"{namespace}/{repo_id}"
  9580. else:
  9581. repo_id = f"{namespace}/hf-cli-jobs-uv-run-scripts"
  9582. # Create repo if needed
  9583. try:
  9584. self.repo_info(repo_id, repo_type="dataset")
  9585. logger.debug(f"Using existing repository: {repo_id}")
  9586. except RepositoryNotFoundError:
  9587. logger.info(f"Creating repository: {repo_id}")
  9588. create_repo(repo_id, repo_type="dataset", private=True, exist_ok=True)
  9589. # Upload script
  9590. logger.info(f"Uploading {script_path.name} to {repo_id}...")
  9591. with open(script_path, "r") as f:
  9592. script_content = f.read()
  9593. commit_hash = self.upload_file(
  9594. path_or_fileobj=script_content.encode(),
  9595. path_in_repo=filename,
  9596. repo_id=repo_id,
  9597. repo_type="dataset",
  9598. ).oid
  9599. script_url = f"{self.endpoint}/datasets/{repo_id}/resolve/{commit_hash}/{filename}"
  9600. repo_url = f"{self.endpoint}/datasets/{repo_id}"
  9601. logger.debug(f"✓ Script uploaded to: {repo_url}/blob/main/{filename}")
  9602. # Create and upload minimal README
  9603. timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S UTC")
  9604. readme_content = dedent(
  9605. f"""
  9606. ---
  9607. tags:
  9608. - hf-cli-jobs-uv-script
  9609. - ephemeral
  9610. viewer: false
  9611. ---
  9612. # UV Script: {filename}
  9613. Executed via `hf jobs uv run` on {timestamp}
  9614. ## Run this script
  9615. ```bash
  9616. hf jobs uv run {filename}
  9617. ```
  9618. ---
  9619. *Created with [hf jobs](https://huggingface.co/docs/huggingface_hub/main/en/guides/jobs)*
  9620. """
  9621. )
  9622. self.upload_file(
  9623. path_or_fileobj=readme_content.encode(),
  9624. path_in_repo="README.md",
  9625. repo_id=repo_id,
  9626. repo_type="dataset",
  9627. )
  9628. secrets["UV_SCRIPT_HF_TOKEN"] = token or self.token or get_token()
  9629. env["UV_SCRIPT_URL"] = script_url
  9630. pre_command = (
  9631. dedent(
  9632. """
  9633. import urllib.request
  9634. import os
  9635. from pathlib import Path
  9636. o = urllib.request.build_opener()
  9637. o.addheaders = [("Authorization", "Bearer " + os.environ["UV_SCRIPT_HF_TOKEN"])]
  9638. Path("/tmp/script.py").write_bytes(o.open(os.environ["UV_SCRIPT_URL"]).read())
  9639. """
  9640. )
  9641. .strip()
  9642. .replace('"', r"\"")
  9643. .split("\n")
  9644. )
  9645. pre_command = ["python", "-c", '"' + "; ".join(pre_command) + '"']
  9646. command = ["uv", "run"] + uv_args + ["/tmp/script.py"] + script_args
  9647. command = ["bash", "-c", " ".join(pre_command) + " && " + " ".join(command)]
  9648. return command, env, secrets
  9649. def _parse_revision_from_pr_url(pr_url: str) -> str:
  9650. """Safely parse revision number from a PR url.
  9651. Example:
  9652. ```py
  9653. >>> _parse_revision_from_pr_url("https://huggingface.co/bigscience/bloom/discussions/2")
  9654. "refs/pr/2"
  9655. ```
  9656. """
  9657. re_match = re.match(_REGEX_DISCUSSION_URL, pr_url)
  9658. if re_match is None:
  9659. raise RuntimeError(f"Unexpected response from the hub, expected a Pull Request URL but got: '{pr_url}'")
  9660. return f"refs/pr/{re_match[1]}"
  9661. api = HfApi()
  9662. whoami = api.whoami
  9663. auth_check = api.auth_check
  9664. get_token_permission = api.get_token_permission
  9665. list_models = api.list_models
  9666. model_info = api.model_info
  9667. list_datasets = api.list_datasets
  9668. dataset_info = api.dataset_info
  9669. list_spaces = api.list_spaces
  9670. space_info = api.space_info
  9671. list_papers = api.list_papers
  9672. paper_info = api.paper_info
  9673. repo_exists = api.repo_exists
  9674. revision_exists = api.revision_exists
  9675. file_exists = api.file_exists
  9676. repo_info = api.repo_info
  9677. list_repo_files = api.list_repo_files
  9678. list_repo_refs = api.list_repo_refs
  9679. list_repo_commits = api.list_repo_commits
  9680. list_repo_tree = api.list_repo_tree
  9681. get_paths_info = api.get_paths_info
  9682. get_model_tags = api.get_model_tags
  9683. get_dataset_tags = api.get_dataset_tags
  9684. create_commit = api.create_commit
  9685. create_repo = api.create_repo
  9686. delete_repo = api.delete_repo
  9687. update_repo_visibility = api.update_repo_visibility
  9688. update_repo_settings = api.update_repo_settings
  9689. move_repo = api.move_repo
  9690. upload_file = api.upload_file
  9691. upload_folder = api.upload_folder
  9692. delete_file = api.delete_file
  9693. delete_folder = api.delete_folder
  9694. delete_files = api.delete_files
  9695. upload_large_folder = api.upload_large_folder
  9696. preupload_lfs_files = api.preupload_lfs_files
  9697. create_branch = api.create_branch
  9698. delete_branch = api.delete_branch
  9699. create_tag = api.create_tag
  9700. delete_tag = api.delete_tag
  9701. get_full_repo_name = api.get_full_repo_name
  9702. # Danger-zone API
  9703. super_squash_history = api.super_squash_history
  9704. list_lfs_files = api.list_lfs_files
  9705. permanently_delete_lfs_files = api.permanently_delete_lfs_files
  9706. # Safetensors helpers
  9707. get_safetensors_metadata = api.get_safetensors_metadata
  9708. parse_safetensors_file_metadata = api.parse_safetensors_file_metadata
  9709. # Background jobs
  9710. run_as_future = api.run_as_future
  9711. # Activity API
  9712. list_liked_repos = api.list_liked_repos
  9713. list_repo_likers = api.list_repo_likers
  9714. unlike = api.unlike
  9715. # Community API
  9716. get_discussion_details = api.get_discussion_details
  9717. get_repo_discussions = api.get_repo_discussions
  9718. create_discussion = api.create_discussion
  9719. create_pull_request = api.create_pull_request
  9720. change_discussion_status = api.change_discussion_status
  9721. comment_discussion = api.comment_discussion
  9722. edit_discussion_comment = api.edit_discussion_comment
  9723. rename_discussion = api.rename_discussion
  9724. merge_pull_request = api.merge_pull_request
  9725. # Space API
  9726. add_space_secret = api.add_space_secret
  9727. delete_space_secret = api.delete_space_secret
  9728. get_space_variables = api.get_space_variables
  9729. add_space_variable = api.add_space_variable
  9730. delete_space_variable = api.delete_space_variable
  9731. get_space_runtime = api.get_space_runtime
  9732. request_space_hardware = api.request_space_hardware
  9733. set_space_sleep_time = api.set_space_sleep_time
  9734. pause_space = api.pause_space
  9735. restart_space = api.restart_space
  9736. duplicate_space = api.duplicate_space
  9737. request_space_storage = api.request_space_storage
  9738. delete_space_storage = api.delete_space_storage
  9739. # Inference Endpoint API
  9740. list_inference_endpoints = api.list_inference_endpoints
  9741. create_inference_endpoint = api.create_inference_endpoint
  9742. get_inference_endpoint = api.get_inference_endpoint
  9743. update_inference_endpoint = api.update_inference_endpoint
  9744. delete_inference_endpoint = api.delete_inference_endpoint
  9745. pause_inference_endpoint = api.pause_inference_endpoint
  9746. resume_inference_endpoint = api.resume_inference_endpoint
  9747. scale_to_zero_inference_endpoint = api.scale_to_zero_inference_endpoint
  9748. create_inference_endpoint_from_catalog = api.create_inference_endpoint_from_catalog
  9749. list_inference_catalog = api.list_inference_catalog
  9750. # Collections API
  9751. get_collection = api.get_collection
  9752. list_collections = api.list_collections
  9753. create_collection = api.create_collection
  9754. update_collection_metadata = api.update_collection_metadata
  9755. delete_collection = api.delete_collection
  9756. add_collection_item = api.add_collection_item
  9757. update_collection_item = api.update_collection_item
  9758. delete_collection_item = api.delete_collection_item
  9759. delete_collection_item = api.delete_collection_item
  9760. # Access requests API
  9761. list_pending_access_requests = api.list_pending_access_requests
  9762. list_accepted_access_requests = api.list_accepted_access_requests
  9763. list_rejected_access_requests = api.list_rejected_access_requests
  9764. cancel_access_request = api.cancel_access_request
  9765. accept_access_request = api.accept_access_request
  9766. reject_access_request = api.reject_access_request
  9767. grant_access = api.grant_access
  9768. # Webhooks API
  9769. create_webhook = api.create_webhook
  9770. disable_webhook = api.disable_webhook
  9771. delete_webhook = api.delete_webhook
  9772. enable_webhook = api.enable_webhook
  9773. get_webhook = api.get_webhook
  9774. list_webhooks = api.list_webhooks
  9775. update_webhook = api.update_webhook
  9776. # User API
  9777. get_user_overview = api.get_user_overview
  9778. get_organization_overview = api.get_organization_overview
  9779. list_organization_members = api.list_organization_members
  9780. list_user_followers = api.list_user_followers
  9781. list_user_following = api.list_user_following
  9782. # Jobs API
  9783. run_job = api.run_job
  9784. fetch_job_logs = api.fetch_job_logs
  9785. list_jobs = api.list_jobs
  9786. inspect_job = api.inspect_job
  9787. cancel_job = api.cancel_job
  9788. run_uv_job = api.run_uv_job
  9789. create_scheduled_job = api.create_scheduled_job
  9790. list_scheduled_jobs = api.list_scheduled_jobs
  9791. inspect_scheduled_job = api.inspect_scheduled_job
  9792. delete_scheduled_job = api.delete_scheduled_job
  9793. suspend_scheduled_job = api.suspend_scheduled_job
  9794. resume_scheduled_job = api.resume_scheduled_job
  9795. create_scheduled_uv_job = api.create_scheduled_uv_job