File size: 5,800 Bytes
0dc67e0
db33294
0dc67e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db33294
0dc67e0
 
 
 
db33294
 
 
0dc67e0
db33294
 
 
 
0dc67e0
 
 
 
 
db33294
0dc67e0
 
 
db33294
0dc67e0
 
 
db33294
0dc67e0
b5017bd
0dc67e0
fdf5004
0dc67e0
 
 
db33294
0dc67e0
 
db33294
0dc67e0
 
db33294
0dc67e0
 
db33294
0dc67e0
 
 
f2d04f3
0dc67e0
 
f2d04f3
0dc67e0
 
 
 
 
 
 
f2d04f3
0dc67e0
 
 
f2d04f3
0dc67e0
f2d04f3
0dc67e0
 
f2d04f3
0dc67e0
 
f2d04f3
0dc67e0
 
 
 
 
 
 
f2d04f3
0dc67e0
 
f2d04f3
0dc67e0
 
f2d04f3
0dc67e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2d04f3
0dc67e0
 
f2d04f3
0dc67e0
 
 
f2d04f3
0dc67e0
f2d04f3
0dc67e0
 
 
f2d04f3
0dc67e0
 
 
f2d04f3
0dc67e0
f2d04f3
0dc67e0
 
 
 
 
f2d04f3
0dc67e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from sentence_transformers import SentenceTransformer, util
import pickle
import google.generativeai as genai
from datetime import datetime
from typing import Dict
import os

app = FastAPI(title="Jimma University Plagiarism API")

# ====================== SAFE LIMITS ======================
MAX_TEXT_LENGTH = 8000
MAX_PROMPT_LENGTH = 4000
SIMILARITY_THRESHOLD = 30.0
# =========================================================

# ====================== RATING FUNCTION ======================
def convert_to_rating(similarity_percent: float) -> int:
    if similarity_percent >= 80:
        return 5
    elif similarity_percent >= 60:
        return 4
    elif similarity_percent >= 40:
        return 3
    elif similarity_percent >= 20:
        return 2
    else:
        return 1
# ============================================================

# ====================== ROOT ======================
@app.get("/")
def home():
    return {"message": "Jimma University Plagiarism API is running πŸš€"}

@app.get("/health")
def health():
    return {"status": "ok"}
# ==================================================

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# ====================== CONFIG ======================
GEMINI_API_KEY = os.getenv(
    "GEMINI_API_KEY",
    "AQ.Ab8RN6Id1IlRKgMi19Vmy7PGrY82ZxG5D34vsDOnsFOFdrRI6g"
)

MODEL_PATH = "plagiarism_sbert_model"
EMBEDDINGS_FILE = "reference_embeddings.pkl"
# ===================================================

# ====================== LOAD MODEL (FIXED) ======================
if not os.path.exists(MODEL_PATH):
    raise RuntimeError("❌ Model folder not found")

model = SentenceTransformer(MODEL_PATH)

print("βœ… SBERT model loaded")

# ====================== LOAD REFERENCE DATASET ======================
if not os.path.exists(EMBEDDINGS_FILE):
    raise RuntimeError("❌ Reference embeddings file not found")

with open(EMBEDDINGS_FILE, "rb") as f:
    data = pickle.load(f)

ref_embeddings = data["embeddings"]
df_ref = data["df_ref"]

print("βœ… Reference dataset loaded")
# ================================================================

# ====================== GEMINI ======================
genai.configure(api_key=GEMINI_API_KEY)
gemini_model = genai.GenerativeModel('gemini-2.5-flash')

print("βœ… System ready")
# ===================================================

# ====================== REQUEST MODEL ======================
class PlagiarismRequest(BaseModel):
    text: str
    title: str = "Submitted Document"
    student_name: str = "Unknown Student"
    year: str = "2026"
# ============================================================

# ====================== API ======================
@app.post("/check_plagiarism")
async def check_plagiarism(req: PlagiarismRequest) -> Dict:

    text = req.text.strip()

    if len(text) < 200:
        raise HTTPException(400, "Text too short (minimum 200 characters)")

    if len(text) > MAX_TEXT_LENGTH:
        text = text[:MAX_TEXT_LENGTH]

    # ================= SBERT ENCODING =================
    try:
        query_embedding = model.encode(
            text,
            convert_to_tensor=True,
            normalize_embeddings=True
        )

        # IMPORTANT FIX: cosine similarity stays in 0–1 range
        cosine_scores = util.cos_sim(query_embedding, ref_embeddings)[0]

        # convert to percentage properly
        similarities = (cosine_scores * 100).cpu().numpy()

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Embedding error: {str(e)}")

    # ================= TOP MATCH =================
    top_idx = int(similarities.argmax())
    top_similarity = float(similarities[top_idx])

    rating = convert_to_rating(top_similarity)
    stars = "β˜…" * rating + "β˜†" * (5 - rating)

    # ================= LOW RISK =================
    if top_similarity <= SIMILARITY_THRESHOLD:
        return {
            "status": "low_risk",
            "similarity_percent": round(top_similarity, 2),
            "rating": rating,
            "stars": stars,
            "message": "No significant plagiarism detected."
        }

    # ================= SOURCE =================
    row = df_ref.iloc[top_idx]
    source_title = str(row.get("title", "Reference Project"))[:150]
    source_student = str(row.get("student_name", "Original Student"))
    source_year = str(row.get("year", "2023"))

    category = "LOW" if top_similarity <= 30 else "MEDIUM" if top_similarity <= 70 else "HIGH"
    emoji = "βœ…" if category == "LOW" else "βš–οΈ" if category == "MEDIUM" else "❌"

    # ================= GEMINI PROMPT =================
    prompt = f"""
You are a strict academic plagiarism supervisor at Jimma University.

{emoji} {category} SIMILARITY CASE

Source Title: {source_title}
Student Name: {source_student}
Year: {source_year}

Suspicious Title: {req.title}
Student Name: {req.student_name}
Year: {req.year}

Similarity Score: {top_similarity:.1f}%

1. Conceptual Similarity:
2. Conceptual Differences:
3. Technology Differences:
4. Supervisor Recommendation:
"""

    try:
        prompt = prompt[:MAX_PROMPT_LENGTH]
        response = gemini_model.generate_content(prompt)
        report = response.text.strip()

    except Exception as e:
        report = f"Gemini error: {str(e)}"

    return {
        "status": "suspicious",
        "similarity_percent": round(top_similarity, 2),
        "rating": rating,
        "stars": stars,
        "most_similar_source": source_title,
        "source_student": source_student,
        "gemini_report": report,
        "timestamp": datetime.now().isoformat()
    }