Spaces:
Sleeping
Sleeping
File size: 8,579 Bytes
efae98e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | 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,
}
|