Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
0.5.15: fix maintainer public publishing and mark editorial featured Spaces
Browse filesFiles changed (25)
- CHANGELOG.md+7
- PUBLIC_CACHE.md+5-1
- README.md+9-1
- VALIDATION.md+15-1
- assets/calendar.css+2
- assets/day-details.js+12-3
- assets/locales.json+3
- assets/theme.css+2
- contrib/aggregation.py+3
- contrib/collection.py+7-3
- contrib/collectors/featured.pyAdded+72
- contrib/collectors/repositories.py+27-2
- contrib/config.py+1-1
- contrib/domain.py+2
- contrib/public_cache.py+34-8
- contrib/ui/events.py+2-1
- releases/HF-Contrib-v2-0.5.15.zipAdded+3
- tests/check_featured.cjsAdded+39
- tests/conftest.pyAdded+9
- tests/preview_featured.pyAdded+40
- tests/test_checkpointing.py+2-2
- tests/test_featured.pyAdded+93
- tests/test_interactions.cjs+7
- tests/test_owner_access.py+3
- tests/test_public_cache.py+39-3
12345# Changelog## 0.5.14 — automatic updates counted separately in the headline- Show the exact non-classified count as the main number, with recognized automatic updates and the raw total on a secondary line. Follow activity/repository filters and visible private data; omit the line when no automatic updates are visible.123456789101112# Changelog## 0.5.15 — reliable maintainer publication and featured Spaces- Publish maintainer scans through their verified, active OAuth session; isolate this capability from other users and keep public collection anonymous for other profiles. Diagnose refused service credentials safely, retry only transient publication errors and preserve independent personal backups.- Read the Hub directory’s editorial featured flag, with anonymous, bounded, cached requests and a strict contract. Ignore README pins and self-assigned tags. Update metadata on unchanged repository heads and completed historical years without rescanning history.- Show a localized, understated star badge in public Space activity details. Restore metadata from personal checkpoints; invalidate cached rows when flags change. Keep counts, intensity, animation and the aggregate-only public schema unchanged.- No dependency, OAuth-scope or source-version changes.## 0.5.14 — automatic updates counted separately in the headline- Show the exact non-classified count as the main number, with recognized automatic updates and the raw total on a secondary line. Follow activity/repository filters and visible private data; omit the line when no automatic updates are visible.
47 unmodified lines4849505152535447 unmodified linesCreate the dedicated bucket with `private=False` and verify anonymous reads and denied anonymous writes. The Space never changes a bucket's visibility or publishes into the private checkpoint bucket.Set the server-only Space secret `HF_CONTRIB_PUBLIC_WRITE_TOKEN` to a token authorized to write this bucket; use a fine-grained token restricted to this bucket when provisioning credentials. It is never sent to the browser or used to collect user activity. Users' OAuth tokens remain explicitly scoped to their own repository access and personal backups. Without this server secret the public mirror is disabled; personal collection still works. No additional OAuth scope is requested.`scripts/backfill_public_cache.py` migrates only the maintainer's actual public checkpoint prefixes. It does not project or read private snapshots. It runs dry by default; `--apply` writes validated aggregates, and optional `--profile USERNAME` limits the selection. Repository visibility is checked anonymously once per profile across its saved years. Never copy personal checkpoint objects directly to this bucket.47 unmodified lines484950515253545556575847 unmodified linesCreate the dedicated bucket with `private=False` and verify anonymous reads and denied anonymous writes. The Space never changes a bucket's visibility or publishes into the private checkpoint bucket.For other users, set the server-only Space secret `HF_CONTRIB_PUBLIC_WRITE_TOKEN` to a durable personal access token authorized to write this bucket; prefer a fine-grained token restricted to this bucket. Never persist a short-lived OAuth access token as this service secret. It is never sent to the browser or used to collect activity. Since 0.5.15, the verified maintainer (OAuth username **and** immutable subject check) uses their active session directly to publish their scans, including other public profiles. Other users' OAuth tokens are never used for central publishing. Without the service secret, only the verified maintainer can publish; personal collection remains available. No additional OAuth scope is requested.Publication retries only transport errors and HTTP 429/500/502/503/504, at most three attempts. A server-requested delay longer than ten seconds is surfaced without retrying early. Refused credentials receive a distinct safe notice. Startup diagnostics and publication failures log only HTTP status/exception class, without credentials, private identities or response bodies. An identical existing aggregate needs no rewrite.Editorial featured Space identities live only in personal checkpoint repository metadata and the owner-authorized UI snapshot. They are intentionally excluded from this public aggregate format.`scripts/backfill_public_cache.py` migrates only the maintainer's actual public checkpoint prefixes. It does not project or read private snapshots. It runs dry by default; `--apply` writes validated aggregates, and optional `--profile USERNAME` limits the selection. Repository visibility is checked anonymously once per profile across its saved years. Never copy personal checkpoint objects directly to this bucket.
14 unmodified lines151617181920215 unmodified lines27282930313214 unmodified linesshort_description: Your Hugging Face activity, by day and contribution type.---# HF Contrib · 0.5.14A contribution explorer for your own Hugging Face account. Signed-out visitors have one sign-in button in the welcome screen; the header account action appears only after authentication, for signing out. The server selects the signed-in account. The Space maintainer can also inspect the public activity of another profile. One annual calendar changes with the selected activity family. The annual calendar shows incoming activity as it is collected. Repository stars lead, followed by timeline stars. Repository batches reveal dates in calendar order; live timeline batches interlace two chronological halves of the dates already received. Choose English or French and a light, dark or system theme. Select a day for its contribution breakdown, timestamps, titles and direct Hub links. Completed results can be exported as an overview PNG with all twelve activity categories.5 unmodified linesThe Publications view includes Daily Papers submissions, authored research papers, published blog articles and social posts. Posts and blog articles share the publication family’s cyan palette and triangular pending marker. Post replies appear in Community with turquoise diamonds; emoji reactions appear in Reactions with coral circles. Export height follows the twelve categories: 2800 × 4032 px, or 4076 px high with the automation explanation.## Separate automatic updates in the headline (0.5.14)The large headline counts visible contributions **excluding recognized automatic updates**. When any are present, a secondary line shows their exact count and the raw total: for the saved julien-c/2026 public scan, **884 contributions + 39,283 automatic updates = 40,167 total**. This does not label the remaining activity as human-authored; ambiguous automation remains unclassified.14 unmodified lines151617181920215 unmodified lines272829303132333435363738394014 unmodified linesshort_description: Your Hugging Face activity, by day and contribution type.---# HF Contrib · 0.5.15A contribution explorer for your own Hugging Face account. Signed-out visitors have one sign-in button in the welcome screen; the header account action appears only after authentication, for signing out. The server selects the signed-in account. The Space maintainer can also inspect the public activity of another profile. One annual calendar changes with the selected activity family. The annual calendar shows incoming activity as it is collected. Repository stars lead, followed by timeline stars. Repository batches reveal dates in calendar order; live timeline batches interlace two chronological halves of the dates already received. Choose English or French and a light, dark or system theme. Select a day for its contribution breakdown, timestamps, titles and direct Hub links. Completed results can be exported as an overview PNG with all twelve activity categories.5 unmodified linesThe Publications view includes Daily Papers submissions, authored research papers, published blog articles and social posts. Posts and blog articles share the publication family’s cyan palette and triangular pending marker. Post replies appear in Community with turquoise diamonds; emoji reactions appear in Reactions with coral circles. Export height follows the twelve categories: 2800 × 4032 px, or 4076 px high with the automation explanation.## Public publishing and editorial Space badges (0.5.15)The verified maintainer's active OAuth session now publishes their public scans, including other profiles, without depending on a stale service credential. This uses the already granted bucket write permission; other users never provide credentials for the central public bucket. Transient publication failures receive at most three attempts, with bounded waits that respect Retry-After. A refused credential is not repeatedly retried. Startup and failure diagnostics log only a status code/exception class, never tokens, response bodies or repository names.Public Space activities carry a small **Featured** star badge when the Hub directory explicitly reports its editorial `featured: true` flag. README `pinned` and user tags are ignored. An explicit Refresh collects current editorial metadata, even on a fully covered historical year, without rescanning that year's history. The normal SHA shortcut also updates the flag. Saved metadata restores locally; filters, day selection, language changes, replay and exports make no additional requests. The badge describes an observed editorial distinction, not a selection date or an extra contribution. It is excluded from private events and from the aggregate-only public mirror.The anonymous `/spaces-json` directory endpoint is not a versioned SDK API: strict contract tests, exact author matching, a one-hour bounded cache, pagination limits and a 30-second overall budget contain this dependency. Unavailable metadata never blocks the available scan or invents a badge. See [PUBLIC_CACHE.md](PUBLIC_CACHE.md) for service credential provisioning and [VALIDATION.md](VALIDATION.md) for tested boundaries.## Separate automatic updates in the headline (0.5.14)The large headline counts visible contributions **excluding recognized automatic updates**. When any are present, a secondary line shows their exact count and the raw total: for the saved julien-c/2026 public scan, **884 contributions + 39,283 automatic updates = 40,167 total**. This does not label the remaining activity as human-authored; ambiguous automation remains unclassified.
1234# Release validation · 0.5.14## v0.5.14 — separate automatic updates from the headline123456789101112131415161718# Release validation · 0.5.15## v0.5.15 — public publisher authentication and editorial Space badgesValidation date: 2026-11-28 (Europe/Paris). Base: `3750d5e6ba4e8e6b3af4e2c9e095fcd422e34e12` (0.5.14).- **Cause verified in the running Space:** the server public publisher credential receives HTTP 401 from the Hub. Diagnostic revision `74330aafcad3634643fc7a9106cb382f32f13998` logs only this status; prior code swallowed the cause. The same stored public data publishes successfully with the authorized owner's current OAuth access. The refused service secret has not been replaced with another short-lived OAuth token: other users still require a valid durable server credential. The maintainer now publishes through the verified active Space session.- **312 Python tests and all five Node suites pass.** Cases include verified subject/username capability gating, anonymous collection of other profiles, refused service credential versus maintainer session, bounded transient retries/Retry-After, public/private separation, exact raw projections, strict featured contract, author mismatch, self-pinned/tagged false positives, optional endpoint failure, cancellation/cache/pagination, unchanged-head enrichment, historical metadata refresh and saved restoration without a commit rescan. Updated DOM rows reflect added/removed badges without count changes.- **Live public repair:** the existing public-checkpoint scopes were projected again with current anonymous repository visibility, without reading private checkpoints, querying history or rewriting personal backups. Forty public calendars were checked anonymously against their saved projections; the subsequent abidlabs/2026 scope was published through the new maintainer-session path with a deliberately invalid service credential, then compared exactly through anonymous reading. These checks cover the saved scopes present during verification, not scans arriving afterwards. Newer existing public snapshots remain protected.- **Live editorial contract:** the anonymous `/spaces-json` directory returned 246 exact-author fffiloni Spaces and 56 editorial flags at verification; expression-editor is true, HF-Contrib-v2 false. This is observed editorial metadata, not a new history scan or an inferred selection date.- **Actual Gradio 6.31.0 in Chromium, simulated OAuth/activity:** 1200px/light/EN, 390px/dark/FR and 320px/light/FR pass badge rendering, localization, scope changes, private/type exclusion and overflow checks, with no browser errors. Desktop/mobile screenshots inspected. Filters do not request new data; changing locale retains the existing Gradio preference notification. The fixture does not log into a real account or scan private activity.- **Automation regression in the production controller:** 1200px/light/EN and 390px/dark/FR pass exact 167 ordinary + 432 automatic = 599 raw, private composition, preserved dense ordinary activity, replay, matching PNG text/colours and classification changes without extra stars; no requests or browser errors.- No dependency, OAuth scope, intensity policy, raw count, event schema or animation changes. Source archive integrity/manifest and the deployed revision/config/assets are checked during publication. No physical Safari, new real Space OAuth login or full private scan was performed.Reproduce the new layout check: `python tests/preview_featured.py`, then `node tests/check_featured.cjs http://127.0.0.1:7860` with Playwright available. The preview is never imported by the application.## v0.5.14 — separate automatic updates from the headline
142 unmodified lines143144145146147148142 unmodified lines.hc-app .entry-aside time { font-size:11px;font-variant-numeric:tabular-nums; }.hc-app .entry-aside svg { width:16px;height:16px; }.hc-app .private-badge { color:var(--hc-warning);background:var(--hc-warning-bg);border-radius:4px;padding:1px 5px;font-size:10px;white-space:nowrap; }.hc-app .day-footer { display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 0; }.hc-app .day-excerpt,.hc-app .day-pending,.hc-app .no-day-entries { font-size:11px;color:var(--muted);line-height:1.6; }.hc-app .day-excerpt { margin:0;max-width:470px; }142 unmodified lines143144145146147148149150142 unmodified lines.hc-app .entry-aside time { font-size:11px;font-variant-numeric:tabular-nums; }.hc-app .entry-aside svg { width:16px;height:16px; }.hc-app .private-badge { color:var(--hc-warning);background:var(--hc-warning-bg);border-radius:4px;padding:1px 5px;font-size:10px;white-space:nowrap; }.hc-app .featured-badge { display:inline-flex;align-items:center;flex:none;gap:4px;color:var(--hc-featured-ink);background:var(--hc-featured-bg);border:1px solid var(--hc-featured-line);border-radius:5px;padding:1px 5px;font-size:10px;line-height:1.4;white-space:nowrap; }.hc-app .featured-badge svg { width:11px;height:11px;flex:none; }.hc-app .day-footer { display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 0; }.hc-app .day-excerpt,.hc-app .day-pending,.hc-app .no-day-entries { font-size:11px;color:var(--muted);line-height:1.6; }.hc-app .day-excerpt { margin:0;max-width:470px; }
47 unmodified lines4849505152535446 unmodified lines10110210310410510610710810911011111 unmodified lines12312412512612712847 unmodified lines'post.published':'M4 3h16v14H9l-5 4Zm4 5h8M8 12h5','post.comment':'M21 11a8 8 0 0 1-8 8H7l-4 3V11a9 9 0 0 1 18 0ZM7 10h10M7 14h6','post.reaction':'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM8 9h.01M16 9h.01M8 14a4 4 0 0 0 8 0',external:'M7 17 17 7M7 7h10v10'};const svg=document.createElementNS('http://www.w3.org/2000/svg','svg'),path=document.createElementNS('http://www.w3.org/2000/svg','path');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('fill','none');svg.setAttribute('stroke','currentColor');svg.setAttribute('stroke-width','1.6');svg.setAttribute('stroke-linecap','round');svg.setAttribute('stroke-linejoin','round');svg.setAttribute('aria-hidden','true');46 unmodified linesconst filterLabel=dayFilter==='all'?'All activities':definitions.find(([id])=>id===dayFilter)?.[1];q('.day-list-heading').textContent=t(filterLabel)+' · '+fmt.format(records.length)+' '+t(records.length===1?'available event':'available events');const list=q('.day-entries');const rowScope=[language,data.run_id,data.username,data.year,selectedDay,showPrivate()].join('|');if(rowScope!==dayRowsScope){dayRowsScope=rowScope;dayRows=new WeakMap();}// Preserve focused links and scroll position when an unrelated source updates.const scope=data.username+'|'+data.year+'|'+selectedDay+'|'+showPrivate()+'|'+keys.join(',')+'|'+dayFilter;const signature=language+'|'+scope+'|'+ready+'|'+JSON.stringify(records);if(list.dataset.signature!==signature){const focused=list.contains(document.activeElement)?document.activeElement.dataset.entryId:null;const scroll=list.dataset.scope===scope?list.scrollTop:0;11 unmodified linesif(href){link.href=href;link.target='_blank';link.rel='noopener noreferrer';link.dataset.entryId=record.key+record.id;}context.appendChild(label);if(record.private){const badge=document.createElement('span');badge.className='private-badge';badge.textContent=t('Private');context.appendChild(badge);}const repo=record.repo&&record.repo!==record.title?record.repo:'';const actor=record.actor&&record.actor.toLowerCase()!==data.username.toLowerCase()?t('by {actor}',{actor:record.actor}):'';if(repo||actor){const detail=document.createElement('span');detail.className='entry-repo';detail.textContent=[repo,actor].filter(Boolean).join(' · ');detail.title=detail.textContent;context.appendChild(detail);}47 unmodified lines484950515253545546 unmodified lines10210310410510610710810911011111211311411 unmodified lines12612712812913013113213313413513613747 unmodified lines'post.published':'M4 3h16v14H9l-5 4Zm4 5h8M8 12h5','post.comment':'M21 11a8 8 0 0 1-8 8H7l-4 3V11a9 9 0 0 1 18 0ZM7 10h10M7 14h6','post.reaction':'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM8 9h.01M16 9h.01M8 14a4 4 0 0 0 8 0',external:'M7 17 17 7M7 7h10v10',featured:'m12 3 2.8 5.7 6.2.9-4.5 4.4 1.1 6.2-5.6-3-5.6 3 1.1-6.2L3 9.6l6.2-.9Z'};const svg=document.createElementNS('http://www.w3.org/2000/svg','svg'),path=document.createElementNS('http://www.w3.org/2000/svg','path');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('fill','none');svg.setAttribute('stroke','currentColor');svg.setAttribute('stroke-width','1.6');svg.setAttribute('stroke-linecap','round');svg.setAttribute('stroke-linejoin','round');svg.setAttribute('aria-hidden','true');46 unmodified linesconst filterLabel=dayFilter==='all'?'All activities':definitions.find(([id])=>id===dayFilter)?.[1];q('.day-list-heading').textContent=t(filterLabel)+' · '+fmt.format(records.length)+' '+t(records.length===1?'available event':'available events');const list=q('.day-entries');const featured=new Set(Array.isArray(data.featured_spaces)?data.featured_spaces:[]);const featuredSignature=JSON.stringify([...featured].sort());const rowScope=[language,data.run_id,data.username,data.year,selectedDay,showPrivate(),featuredSignature].join('|');if(rowScope!==dayRowsScope){dayRowsScope=rowScope;dayRows=new WeakMap();}// Preserve focused links and scroll position when an unrelated source updates.const scope=data.username+'|'+data.year+'|'+selectedDay+'|'+showPrivate()+'|'+keys.join(',')+'|'+dayFilter;const signature=language+'|'+scope+'|'+ready+'|'+JSON.stringify(records)+'|'+featuredSignature;if(list.dataset.signature!==signature){const focused=list.contains(document.activeElement)?document.activeElement.dataset.entryId:null;const scroll=list.dataset.scope===scope?list.scrollTop:0;11 unmodified linesif(href){link.href=href;link.target='_blank';link.rel='noopener noreferrer';link.dataset.entryId=record.key+record.id;}context.appendChild(label);if(record.private){const badge=document.createElement('span');badge.className='private-badge';badge.textContent=t('Private');context.appendChild(badge);}if(!record.private&&record.key.startsWith('space.')&&featured.has(record.repo)){const badge=document.createElement('span'),label=document.createElement('span');badge.className='featured-badge';label.textContent=t('Featured');badge.title=t('Featured by Hugging Face. This badge does not indicate the selection date.');badge.append(entryIcon('featured'),label);context.appendChild(badge);}const repo=record.repo&&record.repo!==record.title?record.repo:'';const actor=record.actor&&record.actor.toLowerCase()!==data.username.toLowerCase()?t('by {actor}',{actor:record.actor}):'';if(repo||actor){const detail=document.createElement('span');detail.className='entry-repo';detail.textContent=[repo,actor].filter(Boolean).join(' · ');detail.title=detail.textContent;context.appendChild(detail);}
12345{"fr": {"Automatic updates attenuated": "Mises à jour automatiques atténuées","Username or organization": "Profil ou organisation","e.g. fffiloni": "ex. fffiloni",12345678{"fr": {"Featured": "À la une","Featured by Hugging Face. This badge does not indicate the selection date.": "Space mis à la une par Hugging Face. Ce badge n’indique pas la date de sélection.","Public publishing access is unavailable. Your personal backup is separate.": "L’accès à la publication publique est indisponible. Votre sauvegarde personnelle est indépendante.","Automatic updates attenuated": "Mises à jour automatiques atténuées","Username or organization": "Profil ou organisation","e.g. fffiloni": "ex. fffiloni",
5 unmodified lines6789101116 unmodified lines2829303132335 unmodified lines--hc-selected:#fff0b9; --hc-selected-line:#d9b654; --hc-ok-bg:#e1efdb; --hc-ok:#326223;--hc-spark-core:#fff6c9; --hc-spark-edge:#996000; --hc-spark-dot:#197c99; --hc-spark-glow:rgba(225,157,10,.5);--hc-finish-light:rgba(248,173,32,.82); --hc-warning-bg:#fff2d6; --hc-warning:#715019;box-sizing:border-box!important; width:100%!important; max-width:1160px!important; margin:0 auto!important; padding:clamp(16px, calc(4vw - 16px), 22px) clamp(16px, calc(4vw - 20px), 24px)!important;color:var(--hc-ink)!important; background:var(--hc-bg)!important; color-scheme:light;--body-background-fill:var(--hc-bg); --background-fill-primary:var(--hc-surface); --background-fill-secondary:var(--hc-bg);16 unmodified lines--hc-selected:#423a20; --hc-selected-line:#907d38; --hc-ok-bg:#263c2b; --hc-ok:#95d99d;--hc-spark-core:#fffef0; --hc-spark-edge:#ffce59; --hc-spark-dot:#b8efff; --hc-spark-glow:rgba(255,210,102,.65);--hc-finish-light:rgba(255,208,100,.78); --hc-warning-bg:#3a3020; --hc-warning:#efd293; color-scheme:dark;}body { background:#fafaf8; }#brand-row { align-items:center; padding:0 0 16px; margin:0; gap:16px; border-bottom:0; }5 unmodified lines678910111216 unmodified lines293031323334355 unmodified lines--hc-selected:#fff0b9; --hc-selected-line:#d9b654; --hc-ok-bg:#e1efdb; --hc-ok:#326223;--hc-spark-core:#fff6c9; --hc-spark-edge:#996000; --hc-spark-dot:#197c99; --hc-spark-glow:rgba(225,157,10,.5);--hc-finish-light:rgba(248,173,32,.82); --hc-warning-bg:#fff2d6; --hc-warning:#715019;--hc-featured-ink:#845007; --hc-featured-bg:#fff4cf; --hc-featured-line:#e9d490;box-sizing:border-box!important; width:100%!important; max-width:1160px!important; margin:0 auto!important; padding:clamp(16px, calc(4vw - 16px), 22px) clamp(16px, calc(4vw - 20px), 24px)!important;color:var(--hc-ink)!important; background:var(--hc-bg)!important; color-scheme:light;--body-background-fill:var(--hc-bg); --background-fill-primary:var(--hc-surface); --background-fill-secondary:var(--hc-bg);16 unmodified lines--hc-selected:#423a20; --hc-selected-line:#907d38; --hc-ok-bg:#263c2b; --hc-ok:#95d99d;--hc-spark-core:#fffef0; --hc-spark-edge:#ffce59; --hc-spark-dot:#b8efff; --hc-spark-glow:rgba(255,210,102,.65);--hc-finish-light:rgba(255,208,100,.78); --hc-warning-bg:#3a3020; --hc-warning:#efd293; color-scheme:dark;--hc-featured-ink:#f7d88d; --hc-featured-bg:#332b1b; --hc-featured-line:#61502b;}body { background:#fafaf8; }#brand-row { align-items:center; padding:0 0 16px; margin:0; gap:16px; border-bottom:0; }
175 unmodified lines176177178179175 unmodified linesdef copy(self):self.snapshot['automation'] = self.automation.snapshot()return deepcopy(self.snapshot)175 unmodified lines176177178179180181182175 unmodified linesdef copy(self):self.snapshot['automation'] = self.automation.snapshot()repos = self.sync.get('repositories', {}).get('repos', {})self.snapshot['featured_spaces'] = sorted(key[6:] for key, row in repos.items()if key.startswith('space:') and row.get('private') is False and row.get('featured') is True)return deepcopy(self.snapshot)
172 unmodified lines17317417517617717817918022 unmodified lines203204205206207208209210172 unmodified linesdirty, last_yield = False, time.monotonic()for future in workers:future.result()accumulator.finish(cancel.is_set())publish_public = public_cache.enabled() and accumulator.snapshot['phase'] in {'complete','partial'}checkpoint = accumulator.bundle(started_at, sources) if store or publish_public else Noneresult = accumulator.copy()if store:22 unmodified lines# service credentials, private names or raw upload errors.public_cache.log.warning('Public publication failed: %s HTTP %s',type(error).__name__, getattr(getattr(error, 'response', None), 'status_code', None))result.update(public_storage_status='error',public_storage_notice='The public copy could not be saved. You can retry with Refresh.')result['revision'] += 1if not store:cache.put(request, result)172 unmodified lines17317417517617717817918018118218318418522 unmodified lines208209210211212213214172 unmodified linesdirty, last_yield = False, time.monotonic()for future in workers:future.result()if refresh and saved and 'repositories' not in sources:# Historical coverage may already be complete. Refresh editorial# metadata only, without reopening any commit history or timeline.from .collectors.repositories import refresh_featured_metadatarefresh_featured_metadata(request, cancel, accumulator.sync)accumulator.finish(cancel.is_set())publish_public = public_cache.enabled(request) and accumulator.snapshot['phase'] in {'complete','partial'}checkpoint = accumulator.bundle(started_at, sources) if store or publish_public else Noneresult = accumulator.copy()if store:22 unmodified lines# service credentials, private names or raw upload errors.public_cache.log.warning('Public publication failed: %s HTTP %s',type(error).__name__, getattr(getattr(error, 'response', None), 'status_code', None))result.update(public_storage_status='error',public_storage_notice=public_cache.failure_notice(error))result['revision'] += 1if not store:cache.put(request, result)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Editorial Space flags from the Hub directory, never README pins or user tags.
The directory endpoint is not a versioned Hub SDK API. Keep its contract strict,requests anonymous and optional: an outage must not invalidate activity counts."""from collections import OrderedDictfrom threading import Lockfrom time import monotonicimport loggingimport httpxfrom ..hub import Cancelled, validate_username
_cache = OrderedDict()_lock = Lock()TTL = 3600MAX_PAGES = 100
def parse_page(value, page, username): if not isinstance(value, dict) or value.get('pageIndex') != page: raise ValueError('Invalid featured directory page') rows, size = value.get('spaces'), value.get('numItemsPerPage') if not isinstance(rows, list) or type(size) is not int or not 1 <= size <= 100 or len(rows) > size: raise ValueError('Invalid featured directory rows') flags = {} for row in rows: if not isinstance(row, dict) or not isinstance(row.get('id'), str) or type(row.get('featured')) is not bool or type(row.get('private')) is not bool: raise ValueError('Invalid editorial featured flag') owner, sep, name = row['id'].partition('/') if sep and name and owner.lower() == username.lower() and row['private'] is False: flags[row['id']] = row['featured'] return flags, len(rows) < size
def featured_spaces(username, cancel): username = validate_username(username).lower() with _lock: cached = _cache.get(username) if cached and monotonic() < cached[0]: _cache.move_to_end(username) return dict(cached[1]) result, deadline = {}, monotonic() + 30 try: with httpx.Client(timeout=httpx.Timeout(6, connect=3), follow_redirects=False) as client: for page in range(MAX_PAGES): if cancel.is_set(): raise Cancelled() remaining = deadline - monotonic() if remaining <= 0: raise TimeoutError() response = client.get('https://huggingface.co/spaces-json', params={ 'search': username, 'sort': 'alphabetical', 'includeNonRunning': 'true', 'p': page, }, timeout=min(6, remaining)) response.raise_for_status() flags, done = parse_page(response.json(), page, username) result.update(flags) if done: break else: raise ValueError('Featured directory page limit reached') except Cancelled: raise except Exception as error: logging.getLogger(__name__).warning('Editorial Space lookup unavailable: %s', type(error).__name__) # Keep verified observations, but never infer false for missing rows. return result with _lock: _cache[username] = (monotonic() + TTL, dict(result)) _cache.move_to_end(username) while len(_cache) > 128: _cache.popitem(last=False) return result3 unmodified lines456789101112138 unmodified lines22232425262728293031323341 unmodified lines7576777879808113 unmodified lines959697989910017 unmodified lines1181191201211221233 unmodified linesfrom ..hub import HubClient, HubError, Cancelledfrom .metadata import repo_urlfrom .issues import make_issuePLURALS = {"model": "models", "dataset": "datasets", "space": "spaces"}def repo_events(item, kind, request, cancel, on_wait=None, issues=None):client = HubClient(cancel, request.token)client.on_wait = on_wait8 unmodified linesprivate = bool(item.get("private"))checkpoint_key = kind + ':' + repoprevious = request.sync.get('repositories', {}).get('repos', {}).get(checkpoint_key, {})listing_sha = item.get('sha')if (previous.get('complete') and private == previous.get('private')and ((request.reuse_public_repositories and not private)or (listing_sha and listing_sha == previous.get('listing_sha')))):client.close()return [], None, {checkpoint_key: previous}head = Noneskipped = Falseurl = repo_url(repo, kind)41 unmodified lines# complete: an explicit refresh can retry these missing records.return result, f"{kind} {repo}: A commit was missing its date or identifier.", {}return result, None, {checkpoint_key: {'listing_sha': listing_sha, 'head': head,'private': private, 'complete': True}}except Cancelled:raiseexcept Exception as error:13 unmodified linesemit(Update("repositories", detail="Reading repositories", reset_issues=True))with ThreadPoolExecutor(max_workers=3, thread_name_prefix="repo-read") as pool:for kind, plural in PLURALS.items():path = f"/api/{plural}"params = {"author": request.username, "limit": 100, "full": "true"}visited = set()17 unmodified linesrequest.repo_visibility[kind + ':' + item['id']] = item['private']else:listing_valid = False# Small windows bound outstanding work and cancellation latency.for offset in range(0, len(items), 6):if cancel.is_set():3 unmodified lines4567891011121314151617181920218 unmodified lines303132333435363738394041424344454647484941 unmodified lines9192939495969713 unmodified lines11111211311411511611717 unmodified lines1351361371381391401411421431441451461471483 unmodified linesfrom ..hub import HubClient, HubError, Cancelledfrom .metadata import repo_urlfrom .issues import make_issuefrom .featured import featured_spacesPLURALS = {"model": "models", "dataset": "datasets", "space": "spaces"}def refresh_featured_metadata(request, cancel, sync):flags = featured_spaces(request.username, cancel)for key, row in sync.get('repositories', {}).get('repos', {}).items():if key.startswith('space:') and row.get('private') is False and key[6:] in flags:row['featured'] = flags[key[6:]]def repo_events(item, kind, request, cancel, on_wait=None, issues=None):client = HubClient(cancel, request.token)client.on_wait = on_wait8 unmodified linesprivate = bool(item.get("private"))checkpoint_key = kind + ':' + repoprevious = request.sync.get('repositories', {}).get('repos', {}).get(checkpoint_key, {})editorial = {}if kind == 'space':if private:editorial = {'featured': False}elif type(item.get('_editorial_featured')) is bool:editorial = {'featured': item['_editorial_featured']}elif type(previous.get('featured')) is bool:editorial = {'featured': previous['featured']}listing_sha = item.get('sha')if (previous.get('complete') and private == previous.get('private')and ((request.reuse_public_repositories and not private)or (listing_sha and listing_sha == previous.get('listing_sha')))):client.close()return [], None, {checkpoint_key: {**previous, **editorial}}head = Noneskipped = Falseurl = repo_url(repo, kind)41 unmodified lines# complete: an explicit refresh can retry these missing records.return result, f"{kind} {repo}: A commit was missing its date or identifier.", {}return result, None, {checkpoint_key: {'listing_sha': listing_sha, 'head': head,'private': private, 'complete': True, **editorial}}except Cancelled:raiseexcept Exception as error:13 unmodified linesemit(Update("repositories", detail="Reading repositories", reset_issues=True))with ThreadPoolExecutor(max_workers=3, thread_name_prefix="repo-read") as pool:for kind, plural in PLURALS.items():editorial = Nonepath = f"/api/{plural}"params = {"author": request.username, "limit": 100, "full": "true"}visited = set()17 unmodified linesrequest.repo_visibility[kind + ':' + item['id']] = item['private']else:listing_valid = Falseif kind == 'space' and items:if editorial is None:editorial = featured_spaces(request.username, cancel)for item in items:# Intersect with the current authenticated repository# listing; a formerly public/private Space gets no badge.if item.get('private') is False and item.get('id') in editorial:item['_editorial_featured'] = editorial[item['id']]# Small windows bound outstanding work and cancellation latency.for offset in range(0, len(items), 6):if cancel.is_set():
123456from datetime import datetime, timezoneVERSION = "0.5.14"FIRST_YEAR = 2022DATA_VERSION = 1SOURCE_VERSIONS = {s: 1 for s in ("repositories", "community", "likes", "upvotes", "papers", "blogs", "posts")}123456from datetime import datetime, timezoneVERSION = "0.5.15"FIRST_YEAR = 2022DATA_VERSION = 1SOURCE_VERSIONS = {s: 1 for s in ("repositories", "community", "likes", "upvotes", "papers", "blogs", "posts")}
54 unmodified lines55565758596011 unmodified lines72737475767754 unmodified linesowner: str = ""owner_id: str = ""storage_token: str | None = field(default=None, repr=False)full_refresh: bool = Falsesync: dict = field(default_factory=dict, repr=False)reuse_public_repositories: bool = False11 unmodified lines"bins": {key: [0] * days for key in KEYS},"private_bins": {key: [0] * days for key in KEYS},"details": {}, "details_retained": 0, "show_private": False,"viewer": "", "allow_private": False, "can_choose_profile": False,"sources": {s: {"status": "waiting", "detail": "", "pages": 0, "scanned": 0} for s in SOURCES},"warnings": [], "issues": [], "fetched_at": None, "cached": False,54 unmodified lines5556575859606111 unmodified lines7374757677787954 unmodified linesowner: str = ""owner_id: str = ""storage_token: str | None = field(default=None, repr=False)public_write_token: str | None = field(default=None, repr=False)full_refresh: bool = Falsesync: dict = field(default_factory=dict, repr=False)reuse_public_repositories: bool = False11 unmodified lines"bins": {key: [0] * days for key in KEYS},"private_bins": {key: [0] * days for key in KEYS},"details": {}, "details_retained": 0, "show_private": False,"featured_spaces": [],"viewer": "", "allow_private": False, "can_choose_profile": False,"sources": {s: {"status": "waiting", "detail": "", "pages": 0, "scanned": 0} for s in SOURCES},"warnings": [], "issues": [], "fetched_at": None, "cached": False,
7 unmodified lines8910111213141 unmodified line1617181920212217 unmodified lines40414243444546473 unmodified lines5152535455565711 unmodified lines69707172737475122 unmodified lines1981992002012022032048 unmodified lines2132142152167 unmodified linesimport osfrom datetime import datefrom threading import Lockfrom time import monotonicfrom urllib.parse import quote, urlparseimport httpx1 unmodified linefrom .config import KEYS, SOURCES, FIRST_YEAR, current_yearfrom .domain import timestamp, ActivityEventfrom .automation import AutomationIndex, validate_automationfrom .hub import HubError, validate_usernamefrom .storage import validate_bundlefrom .intensity import intensity_policy, validate_intensity_policy17 unmodified lineslog.warning('Public publisher credential check: %s', type(error).__name__)def enabled():return bool(os.getenv('HF_CONTRIB_PUBLIC_WRITE_TOKEN'))def public_repository_inventory(username):3 unmodified linesMissing/inaccessible repositories are excluded rather than assumed public."""visibility = {}deadline = monotonic() + 15with httpx.Client(timeout=httpx.Timeout(10, connect=4)) as client:for kind, plural in (('model','models'),('dataset','datasets'),('space','spaces')):root = 'https://huggingface.co/api/' + plural11 unmodified linesif not isinstance(rows, list):raise ValueError('Invalid repository listing')for row in rows:if isinstance(row.get('id'), str) and row.get('private') is False:visibility[kind + ':' + row['id']] = Falseurl, params = response.links.get('next', {}).get('url'), Nonereturn visibility122 unmodified linesif existing:if (existing['username'],existing['year']) != (value['username'],value['year']):raise ValueError('Public cache scope mismatch')if timestamp(existing['updated_at']) > timestamp(value['updated_at']):return pathself.api.batch_bucket_files(BUCKET_ID,add=[(raw,path)],token=self.token)finally:8 unmodified linesvisibility = public_repository_inventory(request.username)complete = Truevalue = project_public(bundle, request, visibility, complete)return PublicStore().save(value)7 unmodified lines8910111213141 unmodified line1617181920212217 unmodified lines4041424344454647484950515253545556575859606162636465666768693 unmodified lines7374757677787911 unmodified lines91929394959697122 unmodified lines2202212222232242252268 unmodified lines2352362372382392402412427 unmodified linesimport osfrom datetime import datefrom threading import Lockfrom time import monotonic, sleepfrom urllib.parse import quote, urlparseimport httpx1 unmodified linefrom .config import KEYS, SOURCES, FIRST_YEAR, current_yearfrom .domain import timestamp, ActivityEventfrom .automation import AutomationIndex, validate_automationfrom .hub import HubError, validate_username, retry_delayfrom .storage import validate_bundlefrom .intensity import intensity_policy, validate_intensity_policy17 unmodified lineslog.warning('Public publisher credential check: %s', type(error).__name__)def enabled(request=None):return bool(getattr(request, 'public_write_token', None) or os.getenv('HF_CONTRIB_PUBLIC_WRITE_TOKEN'))def failure_notice(error):status = getattr(getattr(error, 'response', None), 'status_code', None)if status in (401, 403):return 'Public publishing access is unavailable. Your personal backup is separate.'return 'The public copy could not be saved. You can retry with Refresh.'def retry_publication(operation):"""Retry only transient failures; never retry refused credentials or validation."""for attempt in range(3):try:return operation()except Exception as error:response = getattr(error, 'response', None)status = getattr(response, 'status_code', None)transient = isinstance(error, httpx.TransportError) or status in (429, 500, 502, 503, 504)delay = retry_delay(response.headers, 1 + attempt) if response is not None else 1 + attemptif not transient or attempt == 2 or delay > 10:raisesleep(delay)def public_repository_inventory(username):3 unmodified linesMissing/inaccessible repositories are excluded rather than assumed public."""visibility = {}deadline = monotonic() + 60with httpx.Client(timeout=httpx.Timeout(10, connect=4)) as client:for kind, plural in (('model','models'),('dataset','datasets'),('space','spaces')):root = 'https://huggingface.co/api/' + plural11 unmodified linesif not isinstance(rows, list):raise ValueError('Invalid repository listing')for row in rows:if isinstance(row, dict) and isinstance(row.get('id'), str) and row.get('private') is False:visibility[kind + ':' + row['id']] = Falseurl, params = response.links.get('next', {}).get('url'), Nonereturn visibility122 unmodified linesif existing:if (existing['username'],existing['year']) != (value['username'],value['year']):raise ValueError('Public cache scope mismatch')if existing == value or timestamp(existing['updated_at']) > timestamp(value['updated_at']):return pathself.api.batch_bucket_files(BUCKET_ID,add=[(raw,path)],token=self.token)finally:8 unmodified linesvisibility = public_repository_inventory(request.username)complete = Truevalue = project_public(bundle, request, visibility, complete)# Only the verified maintainer OAuth session can provide this field, in# storage_request(). Other users keep using the server-only service secret.# An OAuth access token must never be copied into that persistent secret.store = PublicStore(request.public_write_token) if request.public_write_token else PublicStore()return retry_publication(lambda: store.save(value))
25 unmodified lines2627282930313225 unmodified linessubject = profile.get('sub', '') if isinstance(profile, dict) and owner else ''return CollectionRequest(username=username, year=int(year), private=bool(private),token=token.token if allowed else None, owner=owner, owner_id=subject,storage_token=token.token if owner else None, full_refresh=full_refresh)def restore_saved(snapshot, profile, token):25 unmodified lines262728293031323325 unmodified linessubject = profile.get('sub', '') if isinstance(profile, dict) and owner else ''return CollectionRequest(username=username, year=int(year), private=bool(private),token=token.token if allowed else None, owner=owner, owner_id=subject,storage_token=token.token if owner else None, full_refresh=full_refresh,public_write_token=token.token if can_choose_profile(profile, token) else None)def restore_saved(snapshot, profile, token):
123version https://git-lfs.github.com/spec/v1oid sha256:b54f63bb63b3c362045dce6feb96ffb6960c38be305fe74737a0e2c00816ad8fsize 376065123456789101112131415161718192021222324252627282930313233343536373839// Real Gradio rendering with synthetic activity/OAuth. No account login/scan.const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');(async()=>{ const browser=await chromium.launch({args:['--no-sandbox','--disable-dev-shm-usage']}); fs.mkdirSync('dist/featured',{recursive:true}); try{for(const [width,theme,lang] of [[1200,'light','en'],[390,'dark','fr'],[320,'light','fr']]){ const page=await browser.newPage({viewport:{width,height:1000},reducedMotion:'reduce'}),errors=[]; page.on('pageerror',e=>errors.push(e.message)); await page.goto(process.argv[2],{waitUntil:'domcontentloaded'}); const config=await (await page.request.get(process.argv[2]+'/config')).json(); const preferenceIds=new Set(config.dependencies.filter(d=>d.targets.some(t=>t[1]==='preferences')).map(d=>d.id)); await page.locator('.load-activity:not(:disabled)').waitFor({timeout:30000}); await page.locator('[data-theme='+theme+']').click();await page.locator('[data-language='+lang+']').click(); await page.locator('.load-activity').click(); await page.waitForFunction(()=>document.querySelector('.total')?.dataset.value==='4'); const date=page.locator('.date-input');await date.fill('2026-01-06');await date.dispatchEvent('change'); await page.locator('.featured-badge').waitFor(); assert.equal(await page.locator('.featured-badge').count(),1); assert.equal(await page.locator('.featured-badge').innerText(),lang==='fr'?'À la une':'Featured'); assert.equal(await page.locator('.featured-badge').evaluate(e=>getComputedStyle(e).backgroundColor),theme==='dark'?'rgb(51, 43, 27)':'rgb(255, 244, 207)'); assert.match(await page.locator('.featured-badge').getAttribute('title'),lang==='fr'?/date de sélection/:/selection date/); assert.equal(await page.locator('.entry-row').count(),4); const box=await page.locator('.featured-badge').boundingBox();assert(box.x>=0&&box.x+box.width<=width); assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)); await page.locator('.day-panel').scrollIntoViewIfNeeded(); await page.screenshot({path:'dist/featured/gradio-'+width+'.png'}); const requests=[];page.on('request',r=>{if(r.url().includes('/gradio_api/')&&!r.url().includes('heartbeat'))requests.push({url:r.url(),body:r.postDataJSON()})}); const tab=async name=>width<600?page.locator('.mobile-tab-select').selectOption(name):page.locator('[data-tab='+name+']').click(); await tab('repositories');await page.locator('[data-filter=sub][data-value=datasets]').click(); assert.equal(await page.locator('.featured-badge').count(),0); await page.locator('[data-filter=sub][data-value=spaces]').click();assert.equal(await page.locator('.featured-badge').count(),1); await page.locator('[data-language='+(lang==='fr'?'en':'fr')+']').click(); assert.equal(await page.locator('.featured-badge').innerText(),lang==='fr'?'Featured':'À la une'); assert(requests.every(r=>r.url.endsWith('/run/predict')&&preferenceIds.has(r.body.fn_index)),'only the existing locale preference event may reach Gradio'); assert.deepEqual(errors,[]); console.log(JSON.stringify({width,theme,lang,badge:true,privateExcluded:true,filters:true,local:true,errors})); await page.close(); }}finally{await browser.close()}})().catch(e=>{console.error(e);process.exitCode=1});123456789import pytest
@pytest.fixture(autouse=True)def offline_editorial_lookup(monkeypatch): # Collector unit tests must never contact the live directory. Dedicated # featured contract tests exercise its HTTP parser through MockTransport. from contrib.collectors import repositories monkeypatch.setattr(repositories, 'featured_spaces', lambda *args: {})12345678910111213141516171819202122232425262728293031323334353637383940"""Real Gradio layout; synthetic activity/OAuth and observed editorial flags.
Never imported by app.py. No Hub/bucket I/O and no credential injection."""import osimport preview_navigation as previewfrom contrib.domain import empty_snapshot
def featured_stream(query, session, refresh=False): value=empty_snapshot(query.year, query.username) value.update(phase='complete', run_id=query.run_id, private=True, show_private=True, fetched_at='2026-11-28T10:00:00Z', featured_spaces=['fffiloni/expression-editor', 'demo-account/private']) rows=[('space.commit','fffiloni/expression-editor',False), ('space.commit','fffiloni/HF-Contrib-v2',False), ('space.commit','demo-account/private',True), ('dataset.commit','fffiloni/expression-editor',False)] for i,(key,repo,private) in enumerate(rows): value['bins'][key][5]+=1 value['private_bins'][key][5]+=int(private) value['details'].setdefault(f'{query.year}-01-06',[]).append(dict( key=key,id=str(i),at=f'{query.year}-01-06T12:00:00Z',title='Synthetic update', repo=repo,private=private,url='https://huggingface.co/spaces/'+repo,actor='')) for source in value['sources'].values():source.update(status='complete',detail='Synthetic activity') yield value
preview.ui.collection.stream=featured_streampreview.ui.collection.stop=lambda session:Nonepreview.ui.collection.is_stopping=lambda session:Falselayout=preview.layoutlayout.hydrate,layout.load_ui,layout.year_ui=preview.hydrate,preview.load,preview.selectlayout.load_activity_event,layout.navigate_year_event=preview.launch,preview.navigatelayout.preference_event,layout.load_private_event=preview.preferences,preview.privatelayout.refresh_event,layout.private_event=preview.refresh,preview.visibilitydemo=layout.build_app()with demo: preview.gr.HTML('<p>EDITORIAL BADGE PREVIEW · SYNTHETIC ACTIVITY AND OAUTH · NO HUB REQUESTS</p>')demo.queue().launch(server_name='0.0.0.0',server_port=int(os.getenv('PORT','7860')),ssr_mode=False, css_paths=[layout.ASSETS/name for name in ('theme.css','animations.css','calendar.css','welcome.css')],footer_links=[])86 unmodified lines8788899091929313 unmodified lines10710810911011111211386 unmodified linesemit(Update(source,status='complete',checkpoint={'timeline':None} if source!='repositories' else {'repos':{}}))monkeypatch.setattr(collection,'collect_activity',feed)monkeypatch.setattr(collection,'collect_repositories',lambda q,c,e:feed(q,'repositories',c,e))published=[];monkeypatch.setattr(collection.public_cache,'enabled',lambda:True)monkeypatch.setattr(collection.public_cache,'publish',lambda b,q:published.append(b))values=list(collection.stream(request(),'periodic-final',True))assert len(writes)>1 and all(b['phase']=='cancelled' for b in writes[:-1])13 unmodified linesdef verify_profile(self,name):return {}def close(self):passmonkeypatch.setattr(collection,'HubClient',Profile)monkeypatch.setattr(collection.public_cache,'enabled',lambda:False)pause=[True]def collect(q,source,cancel,emit):if source!='likes':emit(Update(source,status='complete'));return86 unmodified lines8788899091929313 unmodified lines10710810911011111211386 unmodified linesemit(Update(source,status='complete',checkpoint={'timeline':None} if source!='repositories' else {'repos':{}}))monkeypatch.setattr(collection,'collect_activity',feed)monkeypatch.setattr(collection,'collect_repositories',lambda q,c,e:feed(q,'repositories',c,e))published=[];monkeypatch.setattr(collection.public_cache,'enabled',lambda *args:True)monkeypatch.setattr(collection.public_cache,'publish',lambda b,q:published.append(b))values=list(collection.stream(request(),'periodic-final',True))assert len(writes)>1 and all(b['phase']=='cancelled' for b in writes[:-1])13 unmodified linesdef verify_profile(self,name):return {}def close(self):passmonkeypatch.setattr(collection,'HubClient',Profile)monkeypatch.setattr(collection.public_cache,'enabled',lambda *args:False)pause=[True]def collect(q,source,cancel,emit):if source!='likes':emit(Update(source,status='complete'));return
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293from threading import Eventimport httpximport pytestfrom contrib.collectors import featured, repositoriesfrom contrib.domain import CollectionRequest, Updatefrom contrib.aggregation import Accumulatorfrom contrib.hub import Cancelled
def page(rows, index=0, size=24): return {'spaces': rows, 'pageIndex': index, 'numItemsPerPage': size, 'numTotalItems': None}
def row(name='owner/editorial', flag=True, private=False): return {'id': name, 'featured': flag, 'private': private, 'cardData': {'pinned': True}, 'tags': ['featured']}
def test_directory_contract_uses_editorial_flag_and_exact_author_only(): flags, done = featured.parse_page(page([row(), row('owner/self-pinned', False), row('other/owner'), row('owner/secret', private=True)]), 0, 'owner') assert flags == {'owner/editorial': True, 'owner/self-pinned': False} and done
@pytest.mark.parametrize('bad', [None, [], page([{'id': 'owner/x', 'cardData': {'pinned': True}}]), page([row(flag='true')]), page([row(private=0)]), page([row()], index=1), page([row()], size=0)])def test_directory_contract_fails_closed_on_schema_drift(bad): with pytest.raises(ValueError): featured.parse_page(bad, 0, 'owner')
def test_editorial_lookup_is_anonymous_paginated_and_cached(monkeypatch): featured._cache.clear(); calls=[] def respond(req): calls.append(req) assert 'authorization' not in req.headers and req.url.path == '/spaces-json' assert req.url.params['includeNonRunning'] == 'true' n = int(req.url.params['p']) return httpx.Response(200, json=page([row('owner/a' if n == 0 else 'owner/b', n == 0)] if n < 2 else [], n, 1)) original=httpx.Client monkeypatch.setattr(featured.httpx, 'Client', lambda **kw: original(transport=httpx.MockTransport(respond), **kw)) assert featured.featured_spaces('owner', Event()) == {'owner/a': True, 'owner/b': False} assert featured.featured_spaces('owner', Event()) == {'owner/a': True, 'owner/b': False} assert len(calls) == 3 featured._cache.clear()
def test_optional_lookup_failure_and_cancellation(monkeypatch, caplog): featured._cache.clear() original=httpx.Client monkeypatch.setattr(featured.httpx, 'Client', lambda **kw: original(transport=httpx.MockTransport( lambda req: httpx.Response(503, text='DO-NOT-LOG')), **kw)) assert featured.featured_spaces('owner', Event()) == {} assert 'DO-NOT-LOG' not in caplog.text and not featured._cache stop=Event();stop.set() with pytest.raises(Cancelled): featured.featured_spaces('owner', stop)
@pytest.mark.parametrize('flag', [True, False])def test_unchanged_head_refreshes_featured_without_reading_commits(monkeypatch, flag): class Client: def __init__(self, *args): pass def close(self): pass def get(self, *args): raise AssertionError('Unnecessary commit rescan') monkeypatch.setattr(repositories, 'HubClient', Client) request=CollectionRequest('owner', 2026, sync={'repositories': {'repos': { 'space:owner/app': {'complete': True, 'private': False, 'listing_sha': 'same', 'featured': not flag}}}}) events, error, checkpoint = repositories.repo_events({'id': 'owner/app', 'private': False, 'sha': 'same', '_editorial_featured': flag}, 'space', request, Event()) assert not events and not error and checkpoint['space:owner/app']['featured'] is flag acc=Accumulator(request);acc.apply(Update('repositories', checkpoint={'repos': checkpoint})) assert acc.copy()['featured_spaces'] == (['owner/app'] if flag else []) checkpoint['space:owner/app']['private']=True acc.apply(Update('repositories', checkpoint={'repos': checkpoint})) assert acc.copy()['featured_spaces'] == []
def test_historical_metadata_refresh_and_saved_restore_do_not_rescan(monkeypatch): from test_storage import request, bundle from contrib.public_cache import project_public q=request();b=bundle(q) b['sync']['repositories']['repos']={ 'space:fffiloni/app': {'private':False,'complete':True,'head':'unchanged'}, 'space:fffiloni/secret': {'private':True,'complete':True,'head':'private-head'}, } acc=Accumulator(q,b) monkeypatch.setattr(repositories,'featured_spaces',lambda *a:{'fffiloni/app':True,'fffiloni/secret':True}) before=acc.copy()['bins'] repositories.refresh_featured_metadata(q,Event(),acc.sync) assert acc.copy()['featured_spaces']==['fffiloni/app'] and acc.copy()['bins']==before saved=acc.bundle(__import__('datetime').datetime.now(__import__('datetime').timezone.utc)) restored=Accumulator(q,saved).copy() assert restored['featured_spaces']==['fffiloni/app'] assert acc.sync['repositories']['repos']['space:fffiloni/app']['head']=='unchanged' assert 'featured_spaces' not in project_public(saved,q,{'space:fffiloni/app':False},True)87 unmodified lines88899091929387 unmodified linesq('.diagnostics').open=false;props.value=snapshot;receive();q('button[data-day="9"]').click();assert.equal(q('.day-entries').children.length,7);assert.match(q('.date-display').textContent,/10 janv\. 2026/);assert.equal(q('.date-control').dataset.empty,'false');assert.equal(q('.day-panel').hidden,false);87 unmodified lines88899091929394959697989910087 unmodified linesq('.diagnostics').open=false;props.value=snapshot;receive();q('button[data-day="9"]').click();assert.equal(q('.day-entries').children.length,7);props.value={...snapshot,featured_spaces:['someone/app'],revision:2};receive();assert.equal(q('.day-entries').querySelectorAll('.featured-badge').length,4,'private entries never get an editorial badge');assert.equal(q('.featured-badge').textContent,'À la une');assert.match(q('.featured-badge').title,/date de sélection/);props.value={...snapshot,featured_spaces:[],revision:3};receive();assert.equal(q('.day-entries').querySelectorAll('.featured-badge').length,0,'metadata changes invalidate cached rows');props.value=snapshot;receive();assert.match(q('.date-display').textContent,/10 janv\. 2026/);assert.equal(q('.date-control').dataset.empty,'false');assert.equal(q('.day-panel').hidden,false);
116 unmodified lines117118119120121122116 unmodified linesmonkeypatch.setattr(ui.storage, 'saved_snapshot', lambda query: None)request = gr.Request(session_hash='profile-capability')try:value = ui.hydrate('fffiloni', 2025, request, identity, token)[3]assert value['can_choose_profile'] is enabledif not enabled:116 unmodified lines117118119120121122123124125116 unmodified linesmonkeypatch.setattr(ui.storage, 'saved_snapshot', lambda query: None)request = gr.Request(session_hash='profile-capability')try:query = ui.storage_request('another-profile',2026,False,identity,token)assert bool(query.public_write_token) is enabledassert query.token is None # Public collection stays anonymous.value = ui.hydrate('fffiloni', 2025, request, identity, token)[3]assert value['can_choose_profile'] is enabledif not enabled:
28 unmodified lines2930313233344 unmodified lines3940414243444585 unmodified lines13113213313413513613710 unmodified lines14814915015115215315428 unmodified lines@pytest.mark.parametrize('year',[2024,2026])def test_public_projection_has_only_allowlisted_public_daily_counts(year):query,b,visibility=public_fixture(year)result=public.project_public(b,query,visibility,True)assert result['total']==2 and sum(result['bins']['space.commit'])==1assert sum(result['bins']['post.published'])==14 unmodified lines'public-event','Public title','PUBLIC-POST-ID','Public post content','owner_id','events','warnings','owner-repo-token','oauth-storage-token'):assert forbidden not in rawassert all(k not in result for k in ('private','private_bins','details','issues','sync','owner_id','token'))def test_public_copy_is_keyed_by_scanned_profile_not_storage_owner():85 unmodified lines@pytest.mark.parametrize('public_failure',[False,True])def test_public_publish_is_independent_of_private_backup(monkeypatch, public_failure):saved=bundle();calls,writes=setup_stream(monkeypatch,saved)monkeypatch.setattr(public,'enabled',lambda:True)published=[]def publish(value,query):published.append(value)10 unmodified linessaved=bundle();calls,writes=setup_stream(monkeypatch,saved)def failed(self,value):raise RuntimeError('private failed')monkeypatch.setattr(storage.BucketStore,'save',failed)monkeypatch.setattr(public,'enabled',lambda:True)published=[];monkeypatch.setattr(public,'publish',lambda b,q:published.append(b))restored=list(collection.stream(request(),'read-only'))[-1]assert restored['cached'] and not published28 unmodified lines293031323334354 unmodified lines40414243444546474849505152535455565758596061626364656667686970717273747576777879808185 unmodified lines16716816917017117217310 unmodified lines18418518618718818919028 unmodified lines@pytest.mark.parametrize('year',[2024,2026])def test_public_projection_has_only_allowlisted_public_daily_counts(year):query,b,visibility=public_fixture(year)b['sync']['repositories']['repos']['space:fffiloni/open']['featured']=Trueresult=public.project_public(b,query,visibility,True)assert result['total']==2 and sum(result['bins']['space.commit'])==1assert sum(result['bins']['post.published'])==14 unmodified lines'public-event','Public title','PUBLIC-POST-ID','Public post content','owner_id','events','warnings','owner-repo-token','oauth-storage-token'):assert forbidden not in rawassert all(k not in result for k in ('private','private_bins','details','issues','sync','owner_id','token','featured_spaces'))def test_verified_maintainer_session_publishes_even_with_expired_service_secret(monkeypatch):from contrib.ui.events import storage_requestfrom test_owner_access import profile_tester, TOKENmonkeypatch.setenv('HF_CONTRIB_PUBLIC_WRITE_TOKEN','expired-service')query,b,visibility=public_fixture()signed=storage_request(query.username,query.year,query.private,profile_tester(),TOKEN)query.public_write_token=signed.public_write_tokenquery.repo_visibility=visibility;query.repo_listing_complete=Trueused=[]monkeypatch.setattr(public,'PublicStore',lambda token=None: used.append(token) or SimpleNamespace(save=lambda v:v))assert public.publish(b,query)['total']==2 and used==[TOKEN.token]monkeypatch.delenv('HF_CONTRIB_PUBLIC_WRITE_TOKEN')assert public.enabled(query)assert TOKEN.token not in repr(query) and TOKEN.token not in json.dumps(b)@pytest.mark.parametrize('status,attempts', [(401,1),(403,1),(429,3),(503,3)])def test_public_retry_is_bounded_and_does_not_retry_authentication(monkeypatch,status,attempts):calls=[];waits=[]monkeypatch.setattr(public,'sleep',waits.append)def fail():calls.append(1)raise httpx.HTTPStatusError('SECRET',request=httpx.Request('POST','https://huggingface.co'),response=httpx.Response(status))with pytest.raises(httpx.HTTPStatusError) as error:public.retry_publication(fail)assert len(calls)==attempts and len(waits)==attempts-1assert 'SECRET' not in public.failure_notice(error.value)def test_public_retry_does_not_shorten_server_wait(monkeypatch):monkeypatch.setattr(public,'sleep',lambda delay: (_ for _ in ()).throw(AssertionError('Do not retry early')))def fail():raise httpx.HTTPStatusError('rate limit',request=httpx.Request('POST','https://huggingface.co'),response=httpx.Response(429,headers={'Retry-After':'120'}))with pytest.raises(httpx.HTTPStatusError):public.retry_publication(fail)def test_public_copy_is_keyed_by_scanned_profile_not_storage_owner():85 unmodified lines@pytest.mark.parametrize('public_failure',[False,True])def test_public_publish_is_independent_of_private_backup(monkeypatch, public_failure):saved=bundle();calls,writes=setup_stream(monkeypatch,saved)monkeypatch.setattr(public,'enabled',lambda *args:True)published=[]def publish(value,query):published.append(value)10 unmodified linessaved=bundle();calls,writes=setup_stream(monkeypatch,saved)def failed(self,value):raise RuntimeError('private failed')monkeypatch.setattr(storage.BucketStore,'save',failed)monkeypatch.setattr(public,'enabled',lambda *args:True)published=[];monkeypatch.setattr(public,'publish',lambda b,q:published.append(b))restored=list(collection.stream(request(),'read-only'))[-1]assert restored['cached'] and not published
CHANGELOG.md+7
PUBLIC_CACHE.md+5-1
README.md+9-1
VALIDATION.md+15-1
assets/calendar.css+2
assets/day-details.js+12-3
assets/locales.json+3
assets/theme.css+2
contrib/aggregation.py+3
contrib/collection.py+7-3
contrib/collectors/featured.pyAdded+72
contrib/collectors/repositories.py+27-2
contrib/config.py+1-1
contrib/domain.py+2
contrib/public_cache.py+34-8
contrib/ui/events.py+2-1
releases/HF-Contrib-v2-0.5.15.zipAdded+3
tests/check_featured.cjsAdded+39
tests/conftest.pyAdded+9
tests/preview_featured.pyAdded+40
tests/test_checkpointing.py+2-2
tests/test_featured.pyAdded+93
tests/test_interactions.cjs+7
tests/test_owner_access.py+3
tests/test_public_cache.py+39-3