first commit
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
"""Public, advisory configuration for the optional browser processing beta."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from django.templatetags.static import static
|
||||
|
||||
from django.urls import reverse
|
||||
|
||||
from analysis.models import BrowserProcessingSettings, ClassificationRule
|
||||
|
||||
POLICY_VERSION = 1
|
||||
SPEECH_LABEL_TERMS = (
|
||||
"speech", "conversation", "narration", "monologue", "babbling", "whisper",
|
||||
"speaking", "speech synthesizer",
|
||||
)
|
||||
GATE_RESULTS = {"whitelist_match", "speech_only", "no_match", "unavailable", "error"}
|
||||
RELEVANCE_THRESHOLD = 0.5
|
||||
SPEECH_THRESHOLD = 0.5
|
||||
MODEL_VERSION = "google-yamnet-1"
|
||||
|
||||
|
||||
def browser_config():
|
||||
"""Keep template configuration in one small, non-secret object."""
|
||||
return {
|
||||
"browserProcessingBeta": BrowserProcessingSettings.enabled(),
|
||||
"policyUrl": reverse("browser_policy"),
|
||||
"policyVersion": POLICY_VERSION,
|
||||
}
|
||||
|
||||
|
||||
def browser_policy():
|
||||
enabled = BrowserProcessingSettings.enabled()
|
||||
policy = {
|
||||
"version": POLICY_VERSION,
|
||||
"browser_processing_beta_enabled": enabled,
|
||||
"whitelist": [],
|
||||
"privacy_sensitive_speech": [],
|
||||
"thresholds": {},
|
||||
"model_version": MODEL_VERSION,
|
||||
"model_url": "",
|
||||
"class_map_url": "",
|
||||
}
|
||||
if not enabled:
|
||||
return policy
|
||||
rules = ClassificationRule.objects.filter(enabled=True).order_by("value")
|
||||
policy["whitelist"] = list(rules.filter(rule_type=ClassificationRule.RuleType.WHITELIST).values_list("value", flat=True))
|
||||
class_map_path = Path(__file__).resolve().parents[1] / "static/browser-yamnet/yamnet_class_map.json"
|
||||
class_names = json.loads(class_map_path.read_text(encoding="utf-8"))
|
||||
speech_classes = {name for name in class_names if any(term in name.lower() for term in SPEECH_LABEL_TERMS)}
|
||||
speech_classes.update(value for value in rules.filter(rule_type=ClassificationRule.RuleType.BLACKLIST).values_list("value", flat=True)
|
||||
if any(term in value.lower() for term in SPEECH_LABEL_TERMS))
|
||||
policy["privacy_sensitive_speech"] = sorted(speech_classes)
|
||||
policy["thresholds"] = {"relevance": RELEVANCE_THRESHOLD, "speech": SPEECH_THRESHOLD}
|
||||
policy["model_url"] = static("browser-yamnet/model.json")
|
||||
policy["class_map_url"] = static("browser-yamnet/yamnet_class_map.json")
|
||||
return policy
|
||||
|
||||
|
||||
def advisory_browser_metadata(post_data):
|
||||
"""Parse bounded diagnostics; never use this to authorize or classify audio."""
|
||||
raw = post_data.get("browser_processing_metadata", "")
|
||||
if not raw or len(raw) > 1024:
|
||||
return {}
|
||||
try:
|
||||
submitted = json.loads(raw)
|
||||
except (TypeError, ValueError):
|
||||
return {}
|
||||
if not isinstance(submitted, dict):
|
||||
return {}
|
||||
metadata = {}
|
||||
for key in ("browser_processing_used", "browser_override"):
|
||||
if type(submitted.get(key)) is bool:
|
||||
metadata[key] = submitted[key]
|
||||
version = submitted.get("browser_processing_version")
|
||||
if type(version) is int and 0 < version <= POLICY_VERSION:
|
||||
metadata["browser_processing_version"] = version
|
||||
gate_result = submitted.get("browser_gate_result")
|
||||
if isinstance(gate_result, str) and gate_result in GATE_RESULTS:
|
||||
metadata["browser_gate_result"] = gate_result
|
||||
speech = submitted.get("browser_speech_detected")
|
||||
if type(speech) is bool:
|
||||
metadata["browser_speech_detected"] = speech
|
||||
return metadata
|
||||
@@ -0,0 +1,16 @@
|
||||
import requests
|
||||
from pathlib import Path
|
||||
from django.conf import settings
|
||||
class ClassifierError(Exception): pass
|
||||
def classify(upload):
|
||||
if not settings.CLASSIFIER_URL: raise ClassifierError('Classifier is not configured.')
|
||||
if upload.size>settings.MAX_AUDIO_UPLOAD_SIZE: raise ClassifierError('Audio is too large.')
|
||||
if not (str(getattr(upload,'content_type','')).startswith('audio/') or Path(upload.name).suffix.lower() in {'.aac','.aif','.aiff','.flac','.m4a','.mp3','.ogg','.opus','.wav','.weba'}): raise ClassifierError('Unsupported audio format.')
|
||||
try:
|
||||
upload.seek(0)
|
||||
response=requests.post(settings.CLASSIFIER_URL,files={'file':(upload.name,upload,upload.content_type or 'application/octet-stream')},timeout=settings.CLASSIFIER_TIMEOUT)
|
||||
response.raise_for_status();data=response.json()
|
||||
except (requests.RequestException,ValueError) as exc: raise ClassifierError('Classifier request failed.') from exc
|
||||
if not isinstance(data,dict) or not isinstance(data.get('predictions'),list): raise ClassifierError('Invalid classifier response.')
|
||||
upload.seek(0)
|
||||
return data
|
||||
Reference in New Issue
Block a user