Spaces:
Running
Running
Download agents/semantic.py from AJAYKASU/AI_Humanizer: direct link, hf CLI and curl.
- Browser
- Download file 1.72 kB
-
https://huggingface.co/spaces/AJAYKASU/AI_Humanizer/resolve/main/agents/semantic.py
- Command line
-
hf download hf://spaces/AJAYKASU/AI_Humanizer/agents/semantic.py
-
curl -L -o semantic.py https://huggingface.co/spaces/AJAYKASU/AI_Humanizer/resolve/main/agents/semantic.py
1.72 kB
| import os | |
| import logging | |
| from huggingface_hub import InferenceClient | |
| from scipy.spatial.distance import cosine | |
| logger = logging.getLogger(__name__) | |
| class SemanticScorer: | |
| """ | |
| Computes semantic similarity loss between texts using embedding models. | |
| """ | |
| def __init__(self, hf_token=None): | |
| self.token = hf_token or os.getenv("HF_TOKEN", "") | |
| self.client = InferenceClient(token=self.token) | |
| # Using a small, fast embedding model suitable for semantic similarity | |
| self.model = "sentence-transformers/all-MiniLM-L6-v2" | |
| def compute_loss(self, original_text, candidate_text): | |
| """ | |
| Returns L_sem = 1 - cosine_similarity(E(original), E(candidate)) | |
| Range: [0, 2] (0 = identical, 2 = opposite/unrelated) | |
| """ | |
| if not original_text or not candidate_text: | |
| return 1.0 # Max loss for empty input | |
| try: | |
| # Get embeddings for both texts | |
| # API returns a list of floats (embedding vector) | |
| emb_orig = self.client.feature_extraction(original_text, model=self.model) | |
| emb_cand = self.client.feature_extraction(candidate_text, model=self.model) | |
| # Ensure they are 1D arrays | |
| if len(emb_orig.shape) > 1: | |
| emb_orig = emb_orig[0] # taking first sentence/pooling | |
| if len(emb_cand.shape) > 1: | |
| emb_cand = emb_cand[0] | |
| # Compute cosine distance | |
| # distance = 1 - similarity | |
| loss = cosine(emb_orig, emb_cand) | |
| return float(loss) | |
| except Exception as exc: | |
| logger.error("Semantic scoring failed: %s", exc) | |
| return 0.5 # Fallback loss (neutral penalty) | |