Spaces:
Sleeping
Sleeping
Download engine.py from simrantanwar977/plagiarism-engine: direct link, hf CLI and curl.
- Browser
- Download file 8.58 kB
-
https://huggingface.co/spaces/simrantanwar977/plagiarism-engine/resolve/main/engine.py
- Command line
-
hf download hf://spaces/simrantanwar977/plagiarism-engine/engine.py
-
curl -L -o engine.py https://huggingface.co/spaces/simrantanwar977/plagiarism-engine/resolve/main/engine.py
8.58 kB
| import os | |
| import re | |
| import asyncio | |
| import httpx | |
| from typing import List, Dict, Any, Optional, Tuple | |
| from sentence_transformers import SentenceTransformer | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| import numpy as np | |
| # Environment variables | |
| SEARXNG_URL = os.environ.get("SEARXNG_URL", "https://simrantanwar977-searxng-proxy.hf.space") | |
| OPENALEX_KEY = os.environ.get("OPENALEX_KEY", "") | |
| OPENALEX_EMAIL = os.environ.get("OPENALEX_EMAIL", "simrantanwar977@gmail.com") | |
| # Load the embedding model once at module import (cached on disk after first run) | |
| print("Loading sentence-transformer model...") | |
| EMBEDDER = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") | |
| print("Model loaded.") | |
| # --- Sentence splitting ----------------------------------------------------- | |
| def split_sentences(text: str) -> List[str]: | |
| """Naive sentence splitter; punctuation-based.""" | |
| parts = re.split(r"(?<=[.!?])\s+(?=[A-Z])", text.strip()) | |
| return [p.strip() for p in parts if len(p.strip()) > 20] | |
| def sentence_to_query(sentence: str, max_words: int = 12) -> str: | |
| """Pick a representative substring for searching: longest content phrase.""" | |
| words = re.findall(r"[A-Za-z][A-Za-z\-']+", sentence) | |
| if len(words) <= max_words: | |
| return " ".join(words) | |
| # Use middle window — usually most distinctive | |
| start = (len(words) - max_words) // 2 | |
| return " ".join(words[start:start + max_words]) | |
| # --- SearxNG client --------------------------------------------------------- | |
| async def searxng_query(client: httpx.AsyncClient, query: str, num: int = 5) -> List[Dict[str, str]]: | |
| """Query the SearxNG proxy for a single phrase. Returns list of {title, url, content}.""" | |
| quoted = f'"{query}"' | |
| try: | |
| r = await client.get( | |
| f"{SEARXNG_URL}/search", | |
| params={"q": quoted, "format": "json", "categories": "general"}, | |
| timeout=20.0, | |
| headers={"User-Agent": "plagiarism-engine/1.0"}, | |
| ) | |
| if r.status_code != 200: | |
| return [] | |
| data = r.json() | |
| results = data.get("results", [])[:num] | |
| return [ | |
| { | |
| "title": x.get("title", ""), | |
| "url": x.get("url", ""), | |
| "content": x.get("content", ""), | |
| } | |
| for x in results | |
| if x.get("url") | |
| ] | |
| except Exception as e: | |
| print(f"[searxng] error for '{query[:40]}': {e}") | |
| return [] | |
| # --- OpenAlex client -------------------------------------------------------- | |
| async def openalex_query(client: httpx.AsyncClient, query: str, num: int = 3) -> List[Dict[str, str]]: | |
| """Query OpenAlex for academic matches. Returns list of {title, url, content}.""" | |
| params = { | |
| "search": query, | |
| "per_page": num, | |
| "select": "id,title,abstract_inverted_index,doi,best_oa_location", | |
| "mailto": OPENALEX_EMAIL, | |
| } | |
| if OPENALEX_KEY: | |
| params["api_key"] = OPENALEX_KEY | |
| try: | |
| r = await client.get( | |
| "https://api.openalex.org/works", | |
| params=params, | |
| timeout=20.0, | |
| ) | |
| if r.status_code != 200: | |
| return [] | |
| data = r.json() | |
| out = [] | |
| for w in data.get("results", []): | |
| # Reconstruct abstract from inverted index | |
| inv = w.get("abstract_inverted_index") or {} | |
| if inv: | |
| positions = [] | |
| for word, idxs in inv.items(): | |
| for i in idxs: | |
| positions.append((i, word)) | |
| positions.sort() | |
| abstract = " ".join(w for _, w in positions) | |
| else: | |
| abstract = "" | |
| url = w.get("doi") or w.get("id", "") | |
| best_oa = w.get("best_oa_location") or {} | |
| if best_oa.get("pdf_url"): | |
| url = best_oa["pdf_url"] | |
| elif best_oa.get("landing_page_url"): | |
| url = best_oa["landing_page_url"] | |
| out.append({ | |
| "title": w.get("title") or "", | |
| "url": url, | |
| "content": abstract[:2000], | |
| }) | |
| return out | |
| except Exception as e: | |
| print(f"[openalex] error for '{query[:40]}': {e}") | |
| return [] | |
| # --- Similarity scoring ----------------------------------------------------- | |
| def compute_similarities(user_sentences: List[str], candidate_texts: List[str]) -> np.ndarray: | |
| """Returns matrix of shape (len(user_sentences), len(candidate_texts)) with cosine similarity.""" | |
| if not user_sentences or not candidate_texts: | |
| return np.zeros((len(user_sentences), len(candidate_texts))) | |
| user_emb = EMBEDDER.encode(user_sentences, convert_to_numpy=True, show_progress_bar=False) | |
| cand_emb = EMBEDDER.encode(candidate_texts, convert_to_numpy=True, show_progress_bar=False) | |
| # Normalize | |
| user_emb = user_emb / (np.linalg.norm(user_emb, axis=1, keepdims=True) + 1e-9) | |
| cand_emb = cand_emb / (np.linalg.norm(cand_emb, axis=1, keepdims=True) + 1e-9) | |
| return user_emb @ cand_emb.T | |
| # --- Main pipeline ---------------------------------------------------------- | |
| async def run_plagiarism_check( | |
| text: str, | |
| include_academic: bool = True, | |
| include_web: bool = True, | |
| max_sources: int = 10, | |
| ) -> Dict[str, Any]: | |
| sentences = split_sentences(text) | |
| if not sentences: | |
| return { | |
| "overall_plag_percent": 0.0, | |
| "flagged_sentences": [], | |
| "total_sentences": 0, | |
| "queries_made": 0, | |
| "error": "No valid sentences found", | |
| } | |
| # Cap sentences searched for speed; use longest sentences (most distinctive) | |
| indexed = list(enumerate(sentences)) | |
| indexed.sort(key=lambda x: -len(x[1])) | |
| to_search = indexed[: min(max_sources, len(indexed))] | |
| queries_made = 0 | |
| all_candidates: List[Tuple[int, Dict[str, str], str]] = [] | |
| # (sentence_index, candidate_dict, source_type) | |
| async with httpx.AsyncClient() as client: | |
| tasks = [] | |
| for sent_idx, sent in to_search: | |
| q = sentence_to_query(sent, max_words=12) | |
| if include_web: | |
| tasks.append(("web", sent_idx, searxng_query(client, q, num=3))) | |
| if include_academic: | |
| tasks.append(("academic", sent_idx, openalex_query(client, q, num=2))) | |
| for source_type, sent_idx, coro in tasks: | |
| results = await coro | |
| queries_made += 1 | |
| for r in results: | |
| if r.get("content") and len(r["content"]) > 30: | |
| all_candidates.append((sent_idx, r, source_type)) | |
| if not all_candidates: | |
| return { | |
| "overall_plag_percent": 0.0, | |
| "flagged_sentences": [], | |
| "total_sentences": len(sentences), | |
| "queries_made": queries_made, | |
| } | |
| # Compute similarity between each user sentence and the candidates retrieved for it | |
| # Group candidates by sentence for efficiency | |
| flagged: List[Dict[str, Any]] = [] | |
| by_sent: Dict[int, List[Tuple[Dict[str, str], str]]] = {} | |
| for sent_idx, cand, st in all_candidates: | |
| by_sent.setdefault(sent_idx, []).append((cand, st)) | |
| for sent_idx, cand_list in by_sent.items(): | |
| sentence = sentences[sent_idx] | |
| cand_texts = [c["content"] for c, _ in cand_list] | |
| sim_matrix = compute_similarities([sentence], cand_texts) | |
| sims = sim_matrix[0] # shape (len(cand_list),) | |
| sources = [] | |
| for i, ((cand, st), sim) in enumerate(zip(cand_list, sims)): | |
| if sim >= 0.55: # threshold | |
| sources.append({ | |
| "url": cand["url"], | |
| "title": cand.get("title") or None, | |
| "matched_text": cand["content"][:300], | |
| "similarity": float(sim), | |
| "source_type": st, | |
| }) | |
| if sources: | |
| best = max(s["similarity"] for s in sources) | |
| sources.sort(key=lambda s: -s["similarity"]) | |
| flagged.append({ | |
| "sentence": sentence, | |
| "sentence_index": sent_idx, | |
| "best_similarity": best, | |
| "sources": sources[:5], | |
| }) | |
| flagged_words = sum(len(f["sentence"].split()) for f in flagged) | |
| total_words = sum(len(s.split()) for s in sentences) or 1 | |
| overall = round(100.0 * flagged_words / total_words, 1) | |
| return { | |
| "overall_plag_percent": overall, | |
| "flagged_sentences": flagged, | |
| "total_sentences": len(sentences), | |
| "queries_made": queries_made, | |
| } | |