"""Best-effort semantic ranking of prequalified LoRA metadata on shared CPU.""" import json import os import time import requests _ENDPOINT = "https://amisima-qwen3-5-picture-captioner.hf.space/gradio_api/call/rank_loras" _TIME_LIMIT = 55 _OWNER = "amisima" def _is_owner(request): if request is None: return False raw = getattr(request, "request", None) info = (getattr(raw, "scope", {}).get("session") or {}).get("oauth_info") or {} profile = info.get("userinfo") or {} try: if profile.get("preferred_username") == _OWNER and float(info.get("expires_at", 0)) > time.time(): return True except (TypeError, ValueError): pass # Direct API calls may authenticate as the owner with their own Hub token. header = (getattr(request, "headers", None) or {}).get("authorization", "") if not header.startswith("Bearer hf_"): return False try: response = requests.get( "https://huggingface.co/api/whoami-v2", headers={"Authorization": header}, timeout=(3, 4), allow_redirects=False, ) return response.ok and response.json().get("name") == _OWNER except (requests.RequestException, ValueError): return False def _label(candidate): parts = [] for key in ("name", "title", "label", "description", "trigger", "triggers", "trigger_words", "activation_words", "trainedWords", "tags", "aliases", "category"): value = candidate.get(key) if isinstance(value, (list, tuple)): value = ", ".join(item for item in value if isinstance(item, str)) if isinstance(value, str): value = " ".join(value.split())[:130] if value and value not in parts: parts.append(value) return " | ".join(parts)[:270] def rerank_loras(prompt, candidates, *, limit=8, max_choices=1, request=None): """Return original records, [] for a valid NONE, or None for local fallback.""" if not _is_owner(request): return None return _rank_service(prompt, candidates, limit=limit, max_choices=max_choices) def _rank_service(prompt, candidates, *, limit=8, max_choices=1): access_key = os.getenv("LORA_HERETIC_KEY") if not access_key or not prompt or max_choices != 1: return None known = {} catalog = [] for candidate in list(candidates)[:min(limit, 8)]: label = _label(candidate) if label: item_id = f"L{len(known) + 1}" known[item_id] = candidate catalog.append({"id": item_id, "text": label}) if not catalog: return None deadline = time.monotonic() + _TIME_LIMIT try: submit = requests.post( _ENDPOINT, json={"data": [prompt[:1600], catalog, access_key]}, timeout=(4, 7), allow_redirects=False, ) submit.raise_for_status() event_id = submit.json()["event_id"] if not isinstance(event_id, str) or len(event_id) != 32 or not all(c in "0123456789abcdef" for c in event_id): return None with requests.get( f"{_ENDPOINT}/{event_id}", stream=True, timeout=(4, _TIME_LIMIT), allow_redirects=False, ) as stream: stream.raise_for_status() event = "" for line in stream.iter_lines(decode_unicode=True): if time.monotonic() > deadline: return None if line.startswith("event:"): event = line[6:].strip() if event == "error": return None if event == "complete" and line.startswith("data:"): output = json.loads(line[5:].strip()) ids = output[0]["ids"] if ids == []: return [] if isinstance(ids, list) and len(ids) == 1 and ids[0] in known: return [known[ids[0]]] return None except (requests.RequestException, KeyError, IndexError, TypeError, ValueError): return None return None