Karim Krklec commited on
Commit
a641ed5
·
1 Parent(s): dcce181

Obavljene optimizacije

Browse files
__pycache__/classifier.cpython-313.pyc CHANGED
Binary files a/__pycache__/classifier.cpython-313.pyc and b/__pycache__/classifier.cpython-313.pyc differ
 
__pycache__/feature_extraction.cpython-313.pyc CHANGED
Binary files a/__pycache__/feature_extraction.cpython-313.pyc and b/__pycache__/feature_extraction.cpython-313.pyc differ
 
__pycache__/language_config.cpython-313.pyc CHANGED
Binary files a/__pycache__/language_config.cpython-313.pyc and b/__pycache__/language_config.cpython-313.pyc differ
 
app.py CHANGED
@@ -1,3 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import json
3
  import difflib
@@ -8,7 +25,7 @@ from flask import Flask, request, jsonify
8
  from flask_cors import CORS
9
 
10
  from classifier import predict, ucitaj_model
11
- from feature_extraction import extract_all_features
12
 
13
 
14
  # ─────────────────────────────────────────────────────────────────────────────
@@ -23,7 +40,7 @@ CORS(app, resources={r"/api/*": {"origins": "*"}})
23
  # Učitaj model jednom pri pokretanju servera
24
  # (Ne učitavamo za svaki zahtjev — to bi bilo presporo)
25
  print("Učitavam model...")
26
- MODEL, SCALER, FEATURE_NAMES = ucitaj_model()
27
 
28
  if MODEL is None:
29
  print("UPOZORENJE: Model nije pronađen.")
@@ -42,6 +59,16 @@ def greska(poruka: str, status: int = 400):
42
 
43
 
44
  def izracunaj_slicnost(kod_a: str, kod_b: str) -> float:
 
 
 
 
 
 
 
 
 
 
45
  return difflib.SequenceMatcher(None, kod_a.strip(), kod_b.strip()).ratio()
46
 
47
 
@@ -68,6 +95,7 @@ def health():
68
  "status": "ok",
69
  "model_loaded": MODEL is not None,
70
  "feature_count": len(FEATURE_NAMES) if FEATURE_NAMES else 0,
 
71
  })
72
 
73
 
@@ -117,6 +145,14 @@ def analyze():
117
  model=MODEL,
118
  scaler=SCALER,
119
  feature_names=FEATURE_NAMES,
 
 
 
 
 
 
 
 
120
  )
121
 
122
  return jsonify(rezultat)
@@ -124,7 +160,19 @@ def analyze():
124
 
125
  @app.route("/api/analyze-batch", methods=["POST"])
126
  def analyze_batch():
127
-
 
 
 
 
 
 
 
 
 
 
 
 
128
  podaci = request.get_json(silent=True)
129
  if not podaci:
130
  return greska("Zahtjev mora sadržavati JSON tijelo.")
@@ -133,54 +181,108 @@ def analyze_batch():
133
  if not submissions:
134
  return greska("Polje 'submissions' je prazno.")
135
 
136
- if len(submissions) > 200:
137
- return greska("Maksimalno 200 kodova po zahtjevu.")
138
-
139
- rezultati = []
140
- for sub in submissions:
141
- sub_id = sub.get("id", "nepoznat")
142
- kod = sub.get("code", "").strip()
143
- jezik = sub.get("language")
144
- datoteka = sub.get("filename")
145
-
146
- if not kod:
147
- rezultati.append({
148
- "id": sub_id,
149
- "error": "Prazni kod."
150
- })
151
- continue
152
-
153
- rez = predict(
154
- code=kod,
155
- language=jezik,
156
- filename=datoteka,
157
- model=MODEL,
158
- scaler=SCALER,
159
- feature_names=FEATURE_NAMES,
160
- )
161
- rez["id"] = sub_id
162
- rezultati.append(rez)
163
-
164
- # Sažetak za tablični prikaz
165
- probs = [
166
- r["ai_probability"]
167
- for r in rezultati
168
- if r.get("ai_probability") is not None
169
- ]
170
-
171
- summary = {
172
- "total": len(rezultati),
173
- "high_risk": sum(1 for p in probs if p >= 0.70),
174
- "medium_risk": sum(1 for p in probs if 0.40 <= p < 0.70),
175
- "low_risk": sum(1 for p in probs if p < 0.40),
176
- "avg_ai_probability": round(sum(probs) / len(probs), 4) if probs else 0.0,
177
- }
178
-
179
- return jsonify({"results": rezultati, "summary": summary})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
 
182
  @app.route("/api/similarity", methods=["POST"])
183
  def similarity():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  podaci = request.get_json(silent=True)
185
  if not podaci:
186
  return greska("Zahtjev mora sadržavati JSON tijelo.")
@@ -189,9 +291,6 @@ def similarity():
189
  if len(submissions) < 2:
190
  return greska("Potrebna su najmanje 2 koda za usporedbu.")
191
 
192
- if len(submissions) > 100:
193
- return greska("Maksimalno 100 kodova po zahtjevu.")
194
-
195
  ids = [s.get("id", f"kod_{i}") for i, s in enumerate(submissions)]
196
  codes = [s.get("code", "") for s in submissions]
197
  n = len(codes)
@@ -248,5 +347,6 @@ if __name__ == "__main__":
248
  app.run(
249
  host="0.0.0.0",
250
  port=5000,
251
- debug=True,
 
252
  )
 
1
+ """
2
+ app.py
3
+ ======
4
+ Flask backend za web aplikaciju za detekciju AI generiranog koda.
5
+
6
+ Pokretanje:
7
+ python app.py
8
+
9
+ API rute:
10
+ GET /api/health — provjera radi li server
11
+ POST /api/analyze — analiza jednog isječka koda
12
+ POST /api/analyze-batch — analiza više isječaka odjednom
13
+ POST /api/similarity — međusobna sličnost više kodova
14
+
15
+ React frontend šalje zahtjeve na ove rute i prikazuje rezultate.
16
+ """
17
+
18
  import os
19
  import json
20
  import difflib
 
25
  from flask_cors import CORS
26
 
27
  from classifier import predict, ucitaj_model
28
+ from feature_extraction import extract_all_features, analyze_lines
29
 
30
 
31
  # ─────────────────────────────────────────────────────────────────────────────
 
40
  # Učitaj model jednom pri pokretanju servera
41
  # (Ne učitavamo za svaki zahtjev — to bi bilo presporo)
42
  print("Učitavam model...")
43
+ MODEL, SCALER, FEATURE_NAMES, THRESHOLD = ucitaj_model()
44
 
45
  if MODEL is None:
46
  print("UPOZORENJE: Model nije pronađen.")
 
59
 
60
 
61
  def izracunaj_slicnost(kod_a: str, kod_b: str) -> float:
62
+ """
63
+ Računa sličnost između dva isječka koda kao broj između 0.0 i 1.0.
64
+
65
+ Koristi SequenceMatcher koji gleda zajednične podnizove.
66
+ 0.0 = potpuno različiti kodovi
67
+ 1.0 = identični kodovi
68
+
69
+ Ovo je korisno za otkrivanje je li više studenata koristilo isti AI prompt —
70
+ tada će njihovi kodovi biti međusobno neobično slični.
71
+ """
72
  return difflib.SequenceMatcher(None, kod_a.strip(), kod_b.strip()).ratio()
73
 
74
 
 
95
  "status": "ok",
96
  "model_loaded": MODEL is not None,
97
  "feature_count": len(FEATURE_NAMES) if FEATURE_NAMES else 0,
98
+ "threshold": round(THRESHOLD, 3) if THRESHOLD else 0.65,
99
  })
100
 
101
 
 
145
  model=MODEL,
146
  scaler=SCALER,
147
  feature_names=FEATURE_NAMES,
148
+ threshold=THRESHOLD,
149
+ )
150
+
151
+ # Dodaj anotacije sumnjivih linija za prikaz u code editoru
152
+ rezultat["line_annotations"] = analyze_lines(
153
+ code=kod,
154
+ language=jezik,
155
+ filename=datoteka,
156
  )
157
 
158
  return jsonify(rezultat)
 
160
 
161
  @app.route("/api/analyze-batch", methods=["POST"])
162
  def analyze_batch():
163
+ """
164
+ Analizira više isječaka koda — streaming verzija.
165
+
166
+ Umjesto da čeka sve rezultate pa ih pošalje odjednom (što uzrokuje
167
+ timeout kod velikog broja fajlova), šalje svaki rezultat čim je gotov
168
+ kao Server-Sent Events (SSE) stream.
169
+
170
+ Frontend čita stream liniju po liniju i ažurira UI u realnom vremenu.
171
+
172
+ Format streama — svaka linija je JSON objekt jedne od ove dvije vrste:
173
+ {"type": "result", "data": { ...rezultat za jedan fajl... }}
174
+ {"type": "summary", "data": { ...ukupna statistika... }}
175
+ """
176
  podaci = request.get_json(silent=True)
177
  if not podaci:
178
  return greska("Zahtjev mora sadržavati JSON tijelo.")
 
181
  if not submissions:
182
  return greska("Polje 'submissions' je prazno.")
183
 
184
+ def generate():
185
+ rezultati = []
186
+
187
+ for sub in submissions:
188
+ sub_id = sub.get("id", "nepoznat")
189
+ kod = sub.get("code", "").strip()
190
+ jezik = sub.get("language")
191
+ datoteka = sub.get("filename")
192
+
193
+ if not kod:
194
+ rez = {"id": sub_id, "error": "Prazni kod."}
195
+ else:
196
+ try:
197
+ rez = predict(
198
+ code=kod,
199
+ language=jezik,
200
+ filename=datoteka,
201
+ model=MODEL,
202
+ scaler=SCALER,
203
+ feature_names=FEATURE_NAMES,
204
+ threshold=THRESHOLD,
205
+ )
206
+ rez["id"] = sub_id
207
+ rez["line_annotations"] = analyze_lines(
208
+ code=kod,
209
+ language=jezik,
210
+ filename=datoteka,
211
+ )
212
+ except Exception as e:
213
+ rez = {"id": sub_id, "error": str(e)}
214
+
215
+ rezultati.append(rez)
216
+
217
+ # Pošalji rezultat odmah — ne čekamo ostale
218
+ yield json.dumps({"type": "result", "data": rez},
219
+ ensure_ascii=False) + "\n"
220
+
221
+ # Na kraju pošalji summary
222
+ probs = [
223
+ r["ai_probability"]
224
+ for r in rezultati
225
+ if r.get("ai_probability") is not None
226
+ ]
227
+ summary = {
228
+ "total": len(rezultati),
229
+ "high_risk": sum(1 for p in probs if p >= 0.70),
230
+ "medium_risk": sum(1 for p in probs if 0.40 <= p < 0.70),
231
+ "low_risk": sum(1 for p in probs if p < 0.40),
232
+ "avg_ai_probability": round(sum(probs) / len(probs), 4) if probs else 0.0,
233
+ }
234
+ yield json.dumps({"type": "summary", "data": summary},
235
+ ensure_ascii=False) + "\n"
236
+
237
+ from flask import stream_with_context
238
+ return app.response_class(
239
+ stream_with_context(generate()),
240
+ mimetype="application/x-ndjson",
241
+ headers={
242
+ "X-Accel-Buffering": "no", # isključi nginx buffering ako postoji
243
+ "Cache-Control": "no-cache",
244
+ }
245
+ )
246
 
247
 
248
  @app.route("/api/similarity", methods=["POST"])
249
  def similarity():
250
+ """
251
+ Računa međusobnu sličnost između više kodova i vraća matricu sličnosti.
252
+
253
+ Ovo otkriva je li više studenata predalo gotovo identičan kod
254
+ — što sugerira korištenje istog AI prompta.
255
+
256
+ Zahtjev (JSON):
257
+ {
258
+ "submissions": [
259
+ {"id": "student_01", "code": "..."},
260
+ {"id": "student_02", "code": "..."},
261
+ ...
262
+ ]
263
+ }
264
+
265
+ Odgovor (JSON):
266
+ {
267
+ "ids": ["student_01", "student_02", ...],
268
+ "matrix": [
269
+ [1.00, 0.87, 0.12, ...], ← sličnost student_01 s ostalima
270
+ [0.87, 1.00, 0.15, ...],
271
+ ...
272
+ ],
273
+ "suspicious_pairs": [
274
+ {
275
+ "id_a": "student_01",
276
+ "id_b": "student_02",
277
+ "similarity": 0.87
278
+ },
279
+ ...
280
+ ]
281
+ }
282
+
283
+ suspicious_pairs sadrži sve parove sa sličnošću > 0.70
284
+ (konfigurabilno, trenutno 70%).
285
+ """
286
  podaci = request.get_json(silent=True)
287
  if not podaci:
288
  return greska("Zahtjev mora sadržavati JSON tijelo.")
 
291
  if len(submissions) < 2:
292
  return greska("Potrebna su najmanje 2 koda za usporedbu.")
293
 
 
 
 
294
  ids = [s.get("id", f"kod_{i}") for i, s in enumerate(submissions)]
295
  codes = [s.get("code", "") for s in submissions]
296
  n = len(codes)
 
347
  app.run(
348
  host="0.0.0.0",
349
  port=5000,
350
+ debug=True,
351
+ threaded=True, # potrebno za streaming — svaki zahtjev u svom threadu
352
  )
app2.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ app.py
3
+ ======
4
+ Flask backend za web aplikaciju za detekciju AI generiranog koda.
5
+
6
+ Pokretanje:
7
+ python app.py
8
+
9
+ API rute:
10
+ GET /api/health — provjera radi li server
11
+ POST /api/analyze — analiza jednog isječka koda
12
+ POST /api/analyze-batch — analiza više isječaka odjednom
13
+ POST /api/similarity — međusobna sličnost više kodova
14
+
15
+ React frontend šalje zahtjeve na ove rute i prikazuje rezultate.
16
+ """
17
+
18
+ import os
19
+ import json
20
+ import difflib
21
+ import warnings
22
+ warnings.filterwarnings("ignore")
23
+
24
+ from flask import Flask, request, jsonify
25
+ from flask_cors import CORS
26
+
27
+ from classifier import predict, ucitaj_model
28
+ from feature_extraction import extract_all_features, analyze_lines
29
+
30
+
31
+ # ─────────────────────────────────────────────────────────────────────────────
32
+ # INICIJALIZACIJA
33
+ # ─────────────────────────────────────────────────────────────────────────────
34
+
35
+ app = Flask(__name__)
36
+
37
+ # CORS dopušta React frontendu (localhost:3000) da komunicira s ovim serverom
38
+ CORS(app, resources={r"/api/*": {"origins": "*"}})
39
+
40
+ # Učitaj model jednom pri pokretanju servera
41
+ # (Ne učitavamo za svaki zahtjev — to bi bilo presporo)
42
+ print("Učitavam model...")
43
+ MODEL, SCALER, FEATURE_NAMES, THRESHOLD = ucitaj_model()
44
+
45
+ if MODEL is None:
46
+ print("UPOZORENJE: Model nije pronađen.")
47
+ print("Pokreni prvo: python classifier.py")
48
+ else:
49
+ print(f"Model učitan ({len(FEATURE_NAMES)} značajki).")
50
+
51
+
52
+ # ─────────────────────────────────────────────────────────────────────────────
53
+ # POMOĆNE FUNKCIJE
54
+ # ─────────────────────────────────────────────────────────────────────────────
55
+
56
+ def greska(poruka: str, status: int = 400):
57
+ """Vraća JSON odgovor s greškom."""
58
+ return jsonify({"error": poruka}), status
59
+
60
+
61
+ def izracunaj_slicnost(kod_a: str, kod_b: str) -> float:
62
+ """
63
+ Računa sličnost između dva isječka koda kao broj između 0.0 i 1.0.
64
+
65
+ Koristi SequenceMatcher koji gleda zajednične podnizove.
66
+ 0.0 = potpuno različiti kodovi
67
+ 1.0 = identični kodovi
68
+
69
+ Ovo je korisno za otkrivanje je li više studenata koristilo isti AI prompt —
70
+ tada će njihovi kodovi biti međusobno neobično slični.
71
+ """
72
+ return difflib.SequenceMatcher(None, kod_a.strip(), kod_b.strip()).ratio()
73
+
74
+
75
+ # ─────────────────────────────────────────────────────────────────────────────
76
+ # RUTE
77
+ # ─────────────────────────────────────────────────────────────────────────────
78
+
79
+ @app.route("/api/health", methods=["GET"])
80
+ def health():
81
+ """
82
+ Provjera radi li server i je li model učitan.
83
+
84
+ React frontend poziva ovo pri pokretanju da provjeri
85
+ može li komunicirati sa serverom.
86
+
87
+ Odgovor:
88
+ {
89
+ "status": "ok",
90
+ "model_loaded": true,
91
+ "feature_count": 40
92
+ }
93
+ """
94
+ return jsonify({
95
+ "status": "ok",
96
+ "model_loaded": MODEL is not None,
97
+ "feature_count": len(FEATURE_NAMES) if FEATURE_NAMES else 0,
98
+ "threshold": round(THRESHOLD, 3) if THRESHOLD else 0.65,
99
+ })
100
+
101
+
102
+ @app.route("/api/analyze", methods=["POST"])
103
+ def analyze():
104
+ """
105
+ Analizira jedan isječak koda i vraća procjenu AI podrijetla.
106
+
107
+ Zahtjev (JSON):
108
+ {
109
+ "code": "def foo(x): return x", ← obavezno
110
+ "language": "python", ← opcionalno
111
+ "filename": "main.py" ← opcionalno
112
+ }
113
+
114
+ Odgovor (JSON):
115
+ {
116
+ "ai_probability": 0.73,
117
+ "verdict": "Vjerojatno AI",
118
+ "detected_language": "python",
119
+ "top_features": [
120
+ {"name": "avg_identifier_length", "value": 8.5, "importance": 0.084},
121
+ ...
122
+ ],
123
+ "all_features": { ... },
124
+ "error": null
125
+ }
126
+ """
127
+ podaci = request.get_json(silent=True)
128
+ if not podaci:
129
+ return greska("Zahtjev mora sadržavati JSON tijelo.")
130
+
131
+ kod = podaci.get("code", "").strip()
132
+ if not kod:
133
+ return greska("Polje 'code' je obavezno i ne smije biti prazno.")
134
+
135
+ if len(kod) > 100_000:
136
+ return greska("Kod je predugačak. Maksimalno 100.000 znakova.")
137
+
138
+ jezik = podaci.get("language")
139
+ datoteka = podaci.get("filename")
140
+
141
+ rezultat = predict(
142
+ code=kod,
143
+ language=jezik,
144
+ filename=datoteka,
145
+ model=MODEL,
146
+ scaler=SCALER,
147
+ feature_names=FEATURE_NAMES,
148
+ threshold=THRESHOLD,
149
+ )
150
+
151
+ # Dodaj anotacije sumnjivih linija za prikaz u code editoru
152
+ rezultat["line_annotations"] = analyze_lines(
153
+ code=kod,
154
+ language=jezik,
155
+ filename=datoteka,
156
+ )
157
+
158
+ return jsonify(rezultat)
159
+
160
+
161
+ @app.route("/api/analyze-batch", methods=["POST"])
162
+ def analyze_batch():
163
+ """
164
+ Analizira više isječaka koda odjednom.
165
+ Korisno za nastavnika koji učita više studentskih radova.
166
+
167
+ Zahtjev (JSON):
168
+ {
169
+ "submissions": [
170
+ {"id": "student_01", "code": "...", "language": "python"},
171
+ {"id": "student_02", "code": "...", "language": "python"},
172
+ ...
173
+ ]
174
+ }
175
+
176
+ Odgovor (JSON):
177
+ {
178
+ "results": [
179
+ {
180
+ "id": "student_01",
181
+ "ai_probability": 0.73,
182
+ "verdict": "Vjerojatno AI",
183
+ "detected_language": "python",
184
+ "top_features": [...],
185
+ "error": null
186
+ },
187
+ ...
188
+ ],
189
+ "summary": {
190
+ "total": 30,
191
+ "high_risk": 8,
192
+ "medium_risk": 5,
193
+ "low_risk": 17,
194
+ "avg_ai_probability": 0.41
195
+ }
196
+ }
197
+ """
198
+ podaci = request.get_json(silent=True)
199
+ if not podaci:
200
+ return greska("Zahtjev mora sadržavati JSON tijelo.")
201
+
202
+ submissions = podaci.get("submissions", [])
203
+ if not submissions:
204
+ return greska("Polje 'submissions' je prazno.")
205
+
206
+ rezultati = []
207
+ for sub in submissions:
208
+ sub_id = sub.get("id", "nepoznat")
209
+ kod = sub.get("code", "").strip()
210
+ jezik = sub.get("language")
211
+ datoteka = sub.get("filename")
212
+
213
+ if not kod:
214
+ rezultati.append({
215
+ "id": sub_id,
216
+ "error": "Prazni kod."
217
+ })
218
+ continue
219
+
220
+ rez = predict(
221
+ code=kod,
222
+ language=jezik,
223
+ filename=datoteka,
224
+ model=MODEL,
225
+ scaler=SCALER,
226
+ feature_names=FEATURE_NAMES,
227
+ threshold=THRESHOLD,
228
+ )
229
+ rez["id"] = sub_id
230
+ # Dodaj anotacije sumnjivih linija
231
+ rez["line_annotations"] = analyze_lines(
232
+ code=kod,
233
+ language=jezik,
234
+ filename=datoteka,
235
+ )
236
+ rezultati.append(rez)
237
+
238
+ # Sažetak za tablični prikaz
239
+ probs = [
240
+ r["ai_probability"]
241
+ for r in rezultati
242
+ if r.get("ai_probability") is not None
243
+ ]
244
+
245
+ summary = {
246
+ "total": len(rezultati),
247
+ "high_risk": sum(1 for p in probs if p >= 0.70),
248
+ "medium_risk": sum(1 for p in probs if 0.40 <= p < 0.70),
249
+ "low_risk": sum(1 for p in probs if p < 0.40),
250
+ "avg_ai_probability": round(sum(probs) / len(probs), 4) if probs else 0.0,
251
+ }
252
+
253
+ return jsonify({"results": rezultati, "summary": summary})
254
+
255
+
256
+ @app.route("/api/similarity", methods=["POST"])
257
+ def similarity():
258
+ """
259
+ Računa međusobnu sličnost između više kodova i vraća matricu sličnosti.
260
+
261
+ Ovo otkriva je li više studenata predalo gotovo identičan kod
262
+ — što sugerira korištenje istog AI prompta.
263
+
264
+ Zahtjev (JSON):
265
+ {
266
+ "submissions": [
267
+ {"id": "student_01", "code": "..."},
268
+ {"id": "student_02", "code": "..."},
269
+ ...
270
+ ]
271
+ }
272
+
273
+ Odgovor (JSON):
274
+ {
275
+ "ids": ["student_01", "student_02", ...],
276
+ "matrix": [
277
+ [1.00, 0.87, 0.12, ...], ← sličnost student_01 s ostalima
278
+ [0.87, 1.00, 0.15, ...],
279
+ ...
280
+ ],
281
+ "suspicious_pairs": [
282
+ {
283
+ "id_a": "student_01",
284
+ "id_b": "student_02",
285
+ "similarity": 0.87
286
+ },
287
+ ...
288
+ ]
289
+ }
290
+
291
+ suspicious_pairs sadrži sve parove sa sličnošću > 0.70
292
+ (konfigurabilno, trenutno 70%).
293
+ """
294
+ podaci = request.get_json(silent=True)
295
+ if not podaci:
296
+ return greska("Zahtjev mora sadržavati JSON tijelo.")
297
+
298
+ submissions = podaci.get("submissions", [])
299
+ if len(submissions) < 2:
300
+ return greska("Potrebna su najmanje 2 koda za usporedbu.")
301
+
302
+ ids = [s.get("id", f"kod_{i}") for i, s in enumerate(submissions)]
303
+ codes = [s.get("code", "") for s in submissions]
304
+ n = len(codes)
305
+
306
+ # Izgradi n×n matricu sličnosti
307
+ # matrix[i][j] = sličnost između koda i i koda j
308
+ matrica = [[0.0] * n for _ in range(n)]
309
+ sumnjivi_parovi = []
310
+
311
+ for i in range(n):
312
+ for j in range(n):
313
+ if i == j:
314
+ matrica[i][j] = 1.0
315
+ elif j > i:
316
+ sim = izracunaj_slicnost(codes[i], codes[j])
317
+ matrica[i][j] = round(sim, 4)
318
+ matrica[j][i] = round(sim, 4)
319
+
320
+ # Označi kao sumnjivo ako je sličnost > 70%
321
+ if sim > 0.70:
322
+ sumnjivi_parovi.append({
323
+ "id_a": ids[i],
324
+ "id_b": ids[j],
325
+ "similarity": round(sim, 4),
326
+ })
327
+
328
+ # Sortiraj sumnjive parove po sličnosti (najsličniji prvi)
329
+ sumnjivi_parovi.sort(key=lambda x: x["similarity"], reverse=True)
330
+
331
+ return jsonify({
332
+ "ids": ids,
333
+ "matrix": matrica,
334
+ "suspicious_pairs": sumnjivi_parovi,
335
+ })
336
+
337
+
338
+ # ─────────────────────────────────────────────────────────────────────────────
339
+ # POKRETANJE
340
+ # ─────────────────────────────────────────────────────────────────────────────
341
+
342
+ if __name__ == "__main__":
343
+ print("\n" + "=" * 50)
344
+ print(" AI Code Detector — Backend")
345
+ print("=" * 50)
346
+ print(" Server pokrenut na: http://localhost:5000")
347
+ print(" API rute:")
348
+ print(" GET /api/health")
349
+ print(" POST /api/analyze")
350
+ print(" POST /api/analyze-batch")
351
+ print(" POST /api/similarity")
352
+ print("\n Zaustavi server s Ctrl+C")
353
+ print("=" * 50 + "\n")
354
+
355
+ app.run(
356
+ host="0.0.0.0",
357
+ port=5000,
358
+ debug=True, # automatski restart kad se promijeni kod
359
+ )
classifier.py CHANGED
@@ -28,8 +28,10 @@ from sklearn.metrics import (
28
  classification_report,
29
  confusion_matrix,
30
  roc_auc_score,
 
31
  )
32
  from sklearn.preprocessing import StandardScaler
 
33
 
34
  from feature_extraction import extract_all_features
35
 
@@ -52,12 +54,30 @@ PERPLEXITY_MISSING = -1.0
52
 
53
  # Random Forest parametri
54
  RF_PARAMS = {
55
- "n_estimators": 300, # broj stabala — više = stabilnije, ali sporije
56
- "max_depth": None, # bez ograničenja dubine (stabla rastu do čistih listova)
57
- "min_samples_leaf": 2, # svaki list mora imati min. 2 primjera (smanjuje overfitting)
58
- "class_weight": "balanced", # kompenzira neuravnotežene klase (više human nego AI)
 
 
 
 
 
 
59
  "random_state": 42,
60
- "n_jobs": -1, # koristi sve dostupne CPU jezgre
 
 
 
 
 
 
 
 
 
 
 
 
61
  }
62
 
63
 
@@ -171,9 +191,13 @@ def treniraj(X, y, feature_names):
171
  X_train_scaled = scaler.fit_transform(X_train)
172
  X_test_scaled = scaler.transform(X_test)
173
 
174
- # 3. Treniranje Random Foresta
175
- print("\n Treniram Random Forest...")
176
- model = RandomForestClassifier(**RF_PARAMS)
 
 
 
 
177
  model.fit(X_train_scaled, y_train)
178
 
179
  # 4. Evaluacija na test skupu
@@ -202,19 +226,53 @@ def treniraj(X, y, feature_names):
202
  auc = roc_auc_score(y_test, y_pred_prob)
203
  print(f" AUC-ROC: {auc:.4f}")
204
 
205
- # 5. Cross-validation — pouzdanija procjena jer trenira/testira 5 puta
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  print("\n 5-fold cross-validation (može potrajati minutu)...")
207
  X_scaled_full = scaler.transform(X)
 
208
  cv_scores = cross_val_score(
209
  model, X_scaled_full, y,
210
- cv=5, scoring="f1", n_jobs=-1
211
  )
212
  print(f" CV F1 scores: {[f'{s:.3f}' for s in cv_scores]}")
213
  print(f" CV F1 prosjek: {cv_scores.mean():.3f} "
214
  f"(±{cv_scores.std():.3f})")
215
 
216
  # Top 10 najvažnijih značajki
217
- importances = model.feature_importances_
 
 
 
 
 
 
 
 
218
  top_idx = np.argsort(importances)[::-1][:10]
219
  print("\n Top 10 najvažnijih značajki:")
220
  for rank, idx in enumerate(top_idx, 1):
@@ -253,13 +311,19 @@ def spremi_model(model, scaler, feature_names):
253
  """
254
  os.makedirs(MODEL_DIR, exist_ok=True)
255
 
256
- with open(MODEL_PATH, "wb") as f: pickle.dump(model, f)
257
- with open(SCALER_PATH, "wb") as f: pickle.dump(scaler, f)
258
- with open(FEATURES_PATH, "wb") as f: pickle.dump(feature_names, f)
 
 
259
 
260
  print(f"\n Model spremljen u: {MODEL_PATH}")
261
  print(f" Scaler spremljen u: {SCALER_PATH}")
262
  print(f" Nazivi značajki spremljeni: {FEATURES_PATH}")
 
 
 
 
263
 
264
 
265
  # ─────────────────────────────────────────────────────────────────────────────
@@ -268,20 +332,28 @@ def spremi_model(model, scaler, feature_names):
268
 
269
  def ucitaj_model():
270
  """
271
- Učitava model, scaler i nazive značajki s diska.
272
  Poziva se jednom pri pokretanju web servera.
273
 
274
  Vraća:
275
- (model, scaler, feature_names) ili (None, None, None) ako model ne postoji.
 
276
  """
 
 
277
  if not all(os.path.exists(p) for p in [MODEL_PATH, SCALER_PATH, FEATURES_PATH]):
278
- return None, None, None
279
 
280
  with open(MODEL_PATH, "rb") as f: model = pickle.load(f)
281
  with open(SCALER_PATH, "rb") as f: scaler = pickle.load(f)
282
  with open(FEATURES_PATH, "rb") as f: feature_names = pickle.load(f)
283
 
284
- return model, scaler, feature_names
 
 
 
 
 
285
 
286
 
287
 
@@ -393,21 +465,26 @@ def generate_explanations(features: dict, ai_prob: float) -> list:
393
  )
394
 
395
  num_docs = features.get("num_docstrings", 0)
396
- num_fns = features.get("num_functions", 1)
397
- if num_docs > 0 and num_fns > 0:
398
- doc_coverage = num_docs / num_fns
399
- if doc_coverage >= 0.9:
 
 
 
 
 
400
  dodaj(
401
  f"Every function in the submission includes a formal docstring "
402
- f"({num_docs} of {num_fns} functions documented). "
403
  f"Complete docstring coverage is a strong marker of AI-generated code; "
404
  f"students rarely document all functions unless explicitly required.",
405
  "high", "num_docstrings"
406
  )
407
- elif doc_coverage >= 0.5:
408
  dodaj(
409
- f"More than half of the functions include docstrings "
410
- f"({num_docs} of {num_fns}), which is above the student average.",
411
  "medium", "num_docstrings"
412
  )
413
 
@@ -416,16 +493,16 @@ def generate_explanations(features: dict, ai_prob: float) -> list:
416
  avg_fn_len = features.get("avg_function_length", 0)
417
  if avg_fn_len > 20:
418
  dodaj(
419
- f"Functions are notably long on average ({avg_fn_len:.0f} lines). "
420
  f"AI models tend to produce complete, self-contained implementations; "
421
  f"students more often break logic across multiple smaller functions "
422
  f"or leave parts incomplete.",
423
  "medium", "avg_function_length"
424
  )
425
- elif avg_fn_len > 0 and avg_fn_len < 5:
426
  dodaj(
427
- f"Functions are very short on average ({avg_fn_len:.1f} lines), "
428
- f"which may indicate a human programmer's incremental coding style.",
429
  "positive", "avg_function_length"
430
  )
431
 
@@ -532,7 +609,7 @@ def generate_explanations(features: dict, ai_prob: float) -> list:
532
 
533
 
534
  def predict(code: str, language: str = None, filename: str = None,
535
- model=None, scaler=None, feature_names=None) -> dict:
536
  """
537
  Analizira isječak koda i vraća procjenu vjerojatnosti AI podrijetla.
538
 
@@ -557,7 +634,9 @@ def predict(code: str, language: str = None, filename: str = None,
557
  """
558
  # Učitaj model ako nije proslijeđen
559
  if model is None:
560
- model, scaler, feature_names = ucitaj_model()
 
 
561
 
562
  if model is None:
563
  return {
@@ -569,6 +648,23 @@ def predict(code: str, language: str = None, filename: str = None,
569
  "error": "Model nije treniran. Pokreni: python classifier.py"
570
  }
571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572
  # Izvuci značajke
573
  sve_znacajke = extract_all_features(
574
  code=code, language=language, filename=filename
@@ -588,20 +684,27 @@ def predict(code: str, language: str = None, filename: str = None,
588
  # Predikcija
589
  ai_prob = float(model.predict_proba(X_scaled)[0][1])
590
 
591
- # Tumačenje
592
- if ai_prob >= 0.80:
 
 
593
  verdict = "Vjerojatno AI"
594
- elif ai_prob >= 0.60:
595
  verdict = "Moguće AI"
596
- elif ai_prob >= 0.40:
597
  verdict = "Nejasno"
598
- elif ai_prob >= 0.20:
599
  verdict = "Moguće čovječji"
600
  else:
601
  verdict = "Vjerojatno čovječji"
602
 
603
  # Top 5 značajki koje su doprinijele odluci
604
- importances = model.feature_importances_
 
 
 
 
 
605
  top_idx = np.argsort(importances)[::-1][:5]
606
  top_features = [
607
  {
@@ -639,6 +742,37 @@ def main():
639
  print(f"\n Učitavam dataset iz '{DATASET_PATH}'...")
640
  X, y, feature_names = ucitaj_dataset(DATASET_PATH)
641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
642
  # Treniraj
643
  model, scaler, metrics = treniraj(X, y, feature_names)
644
 
 
28
  classification_report,
29
  confusion_matrix,
30
  roc_auc_score,
31
+ precision_recall_curve,
32
  )
33
  from sklearn.preprocessing import StandardScaler
34
+ from sklearn.calibration import CalibratedClassifierCV
35
 
36
  from feature_extraction import extract_all_features
37
 
 
54
 
55
  # Random Forest parametri
56
  RF_PARAMS = {
57
+ "n_estimators": 300,
58
+ "max_depth": None,
59
+ "min_samples_leaf": 2,
60
+ # Dajemo veću kaznu za lažno pozitivne (nevin student označen kao AI)
61
+ # {0: 1.0, 1: 0.8} znači da je greška na human klasi 1.25x skuplja od greške na AI klasi
62
+ # "balanced" automatski kompenzira neravnotežu klasa
63
+ # Human dobiva veći težinski faktor jer je manjina (29% vs 71%)
64
+ "class_weight": "balanced",
65
+ # Uz to koristimo max_features za bolju generalizaciju
66
+ "max_features": "sqrt",
67
  "random_state": 42,
68
+ "n_jobs": -1,
69
+ }
70
+
71
+ # Prag ispod kojeg smatramo kod "premalog" za pouzdanu analizu
72
+ MINIMUM_LINES = 5
73
+
74
+ # Prag vjerojatnosti — konzervativniji pragovi smanjuju lažno pozitivne
75
+ THRESHOLDS = {
76
+ "likely_ai": 0.80, # gore → "Vjerojatno AI"
77
+ "possible_ai": 0.65, # gore → "Moguće AI"
78
+ "unclear": 0.45, # gore → "Nejasno"
79
+ "possible_human": 0.25, # gore → "Moguće čovječji"
80
+ # ispod → "Vjerojatno čovječji"
81
  }
82
 
83
 
 
191
  X_train_scaled = scaler.fit_transform(X_train)
192
  X_test_scaled = scaler.transform(X_test)
193
 
194
+ # 3. Treniranje Random Foresta + kalibracija vjerojatnosti
195
+ # CalibratedClassifierCV popravlja iskrivljene vjerojatnosti RF-a.
196
+ # Bez kalibracije, RF može davati 60% za nešto što je zapravo 30%.
197
+ # method='isotonic' je jači, ali treba više podataka (>1000 primjera — ok)
198
+ print("\n Treniram Random Forest + kalibriram vjerojatnosti...")
199
+ base_model = RandomForestClassifier(**RF_PARAMS)
200
+ model = CalibratedClassifierCV(base_model, method='isotonic', cv=3)
201
  model.fit(X_train_scaled, y_train)
202
 
203
  # 4. Evaluacija na test skupu
 
226
  auc = roc_auc_score(y_test, y_pred_prob)
227
  print(f" AUC-ROC: {auc:.4f}")
228
 
229
+ # 5. Pronalazi optimalni prag odluke koji maksimizira F1 za human klasu
230
+ # Cilj: smanjiti lažno pozitivne (FP) čak i ako propustimo koji AI
231
+ precisions, recalls, thresholds = precision_recall_curve(
232
+ y_test, y_pred_prob, pos_label=0 # gledamo human klasu (0)
233
+ )
234
+ # Tražimo prag gdje je precision za human >= 0.85
235
+ # (tj. kad kažemo "human", u barem 85% slučajeva stvarno je human)
236
+ optimal_threshold = 0.5 # fallback
237
+ for prec, rec, thr in zip(precisions, recalls, thresholds):
238
+ if prec >= 0.85 and rec >= 0.30:
239
+ optimal_threshold = thr
240
+ break
241
+
242
+ print(f"\n Optimalni prag odluke za AI klasu: {1 - optimal_threshold:.2f}")
243
+ print(f" (Prag ispod kojeg klasificiramo kao Human)")
244
+
245
+ # Spremi optimalni prag uz model
246
+ threshold_path = os.path.join(MODEL_DIR, "threshold.pkl")
247
+ os.makedirs(MODEL_DIR, exist_ok=True)
248
+ with open(threshold_path, "wb") as f_thr:
249
+ pickle.dump(float(1 - optimal_threshold), f_thr)
250
+
251
+ # 6. Cross-validation s miješanjem — pouzdanija procjena
252
+ # StratifiedKFold + shuffle sprječava situaciju gdje jedna fold
253
+ # sadrži samo jedan tip podataka (npr. samo AIGCodeSet)
254
+ from sklearn.model_selection import StratifiedKFold
255
  print("\n 5-fold cross-validation (može potrajati minutu)...")
256
  X_scaled_full = scaler.transform(X)
257
+ skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
258
  cv_scores = cross_val_score(
259
  model, X_scaled_full, y,
260
+ cv=skf, scoring="f1", n_jobs=-1
261
  )
262
  print(f" CV F1 scores: {[f'{s:.3f}' for s in cv_scores]}")
263
  print(f" CV F1 prosjek: {cv_scores.mean():.3f} "
264
  f"(±{cv_scores.std():.3f})")
265
 
266
  # Top 10 najvažnijih značajki
267
+ # CalibratedClassifierCV omotava base estimator, pa trebamo
268
+ # dohvatiti feature_importances_ iz jednog od kalibriranih estimatora
269
+ try:
270
+ base_rf = model.calibrated_classifiers_[0].estimator
271
+ importances = base_rf.feature_importances_
272
+ except Exception:
273
+ # Fallback ako struktura nije očekivana
274
+ importances = np.zeros(len(feature_names))
275
+
276
  top_idx = np.argsort(importances)[::-1][:10]
277
  print("\n Top 10 najvažnijih značajki:")
278
  for rank, idx in enumerate(top_idx, 1):
 
311
  """
312
  os.makedirs(MODEL_DIR, exist_ok=True)
313
 
314
+ THRESHOLD_PATH = os.path.join(MODEL_DIR, "threshold.pkl")
315
+
316
+ with open(MODEL_PATH, "wb") as f: pickle.dump(model, f)
317
+ with open(SCALER_PATH, "wb") as f: pickle.dump(scaler, f)
318
+ with open(FEATURES_PATH, "wb") as f: pickle.dump(feature_names, f)
319
 
320
  print(f"\n Model spremljen u: {MODEL_PATH}")
321
  print(f" Scaler spremljen u: {SCALER_PATH}")
322
  print(f" Nazivi značajki spremljeni: {FEATURES_PATH}")
323
+ if os.path.exists(THRESHOLD_PATH):
324
+ with open(THRESHOLD_PATH, "rb") as f:
325
+ thr = pickle.load(f)
326
+ print(f" Optimalni prag: {thr:.2f}")
327
 
328
 
329
  # ─────────────────────────────────────────────────────────────────────────────
 
332
 
333
  def ucitaj_model():
334
  """
335
+ Učitava model, scaler, nazive značajki i optimalni prag s diska.
336
  Poziva se jednom pri pokretanju web servera.
337
 
338
  Vraća:
339
+ (model, scaler, feature_names, threshold) ili
340
+ (None, None, None, 0.65) ako model ne postoji.
341
  """
342
+ THRESHOLD_PATH = os.path.join(MODEL_DIR, "threshold.pkl")
343
+
344
  if not all(os.path.exists(p) for p in [MODEL_PATH, SCALER_PATH, FEATURES_PATH]):
345
+ return None, None, None, 0.65
346
 
347
  with open(MODEL_PATH, "rb") as f: model = pickle.load(f)
348
  with open(SCALER_PATH, "rb") as f: scaler = pickle.load(f)
349
  with open(FEATURES_PATH, "rb") as f: feature_names = pickle.load(f)
350
 
351
+ threshold = 0.65 # konzervativni default
352
+ if os.path.exists(THRESHOLD_PATH):
353
+ with open(THRESHOLD_PATH, "rb") as f:
354
+ threshold = pickle.load(f)
355
+
356
+ return model, scaler, feature_names, threshold
357
 
358
 
359
 
 
465
  )
466
 
467
  num_docs = features.get("num_docstrings", 0)
468
+ # Aproksimiramo broj funkcija iz function_density i total_lines
469
+ # jer structural features sada vraćaju gustoće, ne apsolutne brojeve
470
+ fn_density = features.get("function_density", 0)
471
+ total_lines = features.get("total_lines", 1)
472
+ num_fns_est = max(1, round(fn_density * total_lines))
473
+
474
+ if num_docs > 0:
475
+ doc_coverage = num_docs / max(num_fns_est, 1)
476
+ if num_docs >= 3 and doc_coverage >= 0.8:
477
  dodaj(
478
  f"Every function in the submission includes a formal docstring "
479
+ f"({num_docs} docstrings detected). "
480
  f"Complete docstring coverage is a strong marker of AI-generated code; "
481
  f"students rarely document all functions unless explicitly required.",
482
  "high", "num_docstrings"
483
  )
484
+ elif num_docs >= 2:
485
  dodaj(
486
+ f"Multiple functions include docstrings ({num_docs} detected), "
487
+ f"which is above the typical student average.",
488
  "medium", "num_docstrings"
489
  )
490
 
 
493
  avg_fn_len = features.get("avg_function_length", 0)
494
  if avg_fn_len > 20:
495
  dodaj(
496
+ f"Functions are notably long on average ({avg_fn_len:.0f} lines per function). "
497
  f"AI models tend to produce complete, self-contained implementations; "
498
  f"students more often break logic across multiple smaller functions "
499
  f"or leave parts incomplete.",
500
  "medium", "avg_function_length"
501
  )
502
+ elif 0 < avg_fn_len < 6:
503
  dodaj(
504
+ f"Functions are concise on average ({avg_fn_len:.1f} lines), "
505
+ f"which is consistent with a human programmer's incremental coding style.",
506
  "positive", "avg_function_length"
507
  )
508
 
 
609
 
610
 
611
  def predict(code: str, language: str = None, filename: str = None,
612
+ model=None, scaler=None, feature_names=None, threshold: float = None) -> dict:
613
  """
614
  Analizira isječak koda i vraća procjenu vjerojatnosti AI podrijetla.
615
 
 
634
  """
635
  # Učitaj model ako nije proslijeđen
636
  if model is None:
637
+ model, scaler, feature_names, threshold = ucitaj_model()
638
+ else:
639
+ threshold = 0.65 # konzervativni default ako je model proslijeđen direktno
640
 
641
  if model is None:
642
  return {
 
648
  "error": "Model nije treniran. Pokreni: python classifier.py"
649
  }
650
 
651
+ # Provjera minimalne duljine — kratki kodovi nemaju dovoljno signala
652
+ # za pouzdanu analizu i skloni su lažno pozitivnim rezultatima
653
+ meaningful_lines = len([l for l in code.splitlines() if l.strip()])
654
+ if meaningful_lines < MINIMUM_LINES:
655
+ return {
656
+ "ai_probability": None,
657
+ "verdict": "Premalo koda za analizu",
658
+ "detected_language": None,
659
+ "top_features": [],
660
+ "all_features": {},
661
+ "error": (
662
+ f"Analiza zahtijeva najmanje {MINIMUM_LINES} nepraznih linija koda. "
663
+ f"Predani isječak ima {meaningful_lines} "
664
+ f"({'liniju' if meaningful_lines == 1 else 'linije' if meaningful_lines < 5 else 'linija'})."
665
+ )
666
+ }
667
+
668
  # Izvuci značajke
669
  sve_znacajke = extract_all_features(
670
  code=code, language=language, filename=filename
 
684
  # Predikcija
685
  ai_prob = float(model.predict_proba(X_scaled)[0][1])
686
 
687
+ # Tumačenje — koristimo optimalni prag pronađen pri treniranju
688
+ # Sve iznad threshold-a ide prema "AI", sve ispod prema "Human"
689
+ ai_cutoff = threshold # npr. 0.68 pronađen automatski
690
+ if ai_prob >= min(ai_cutoff + 0.15, 0.90):
691
  verdict = "Vjerojatno AI"
692
+ elif ai_prob >= ai_cutoff:
693
  verdict = "Moguće AI"
694
+ elif ai_prob >= ai_cutoff - 0.20:
695
  verdict = "Nejasno"
696
+ elif ai_prob >= ai_cutoff - 0.40:
697
  verdict = "Moguće čovječji"
698
  else:
699
  verdict = "Vjerojatno čovječji"
700
 
701
  # Top 5 značajki koje su doprinijele odluci
702
+ # Dohvati importances iz base estimatora unutar CalibratedClassifierCV
703
+ try:
704
+ base_rf = model.calibrated_classifiers_[0].estimator
705
+ importances = base_rf.feature_importances_
706
+ except Exception:
707
+ importances = np.ones(len(feature_names)) / len(feature_names)
708
  top_idx = np.argsort(importances)[::-1][:5]
709
  top_features = [
710
  {
 
742
  print(f"\n Učitavam dataset iz '{DATASET_PATH}'...")
743
  X, y, feature_names = ucitaj_dataset(DATASET_PATH)
744
 
745
+ # ── UNDERSAMPLING ──────────────────────────────────────────────────────
746
+ # Balansiramo klase uzimanjem max 3x više human primjera nego AI.
747
+ # Bez ovoga model s 63:1 omjerom gotovo uvijek predviđa human.
748
+ # Cilj: human ≈ 2-3x AI → model nauči obje klase jednako dobro.
749
+
750
+ n_ai = int(np.sum(y == 1))
751
+ n_human = int(np.sum(y == 0))
752
+ target_human = min(n_human, n_ai * 3) # max 3x više human nego AI
753
+
754
+ if n_human > target_human:
755
+ print(f"\n Undersampling: {n_human} → {target_human} human primjera")
756
+ print(f" (zadržavamo svih {n_ai} AI + {target_human} human = "
757
+ f"{n_ai + target_human} ukupno, omjer {target_human//n_ai}:1)")
758
+
759
+ rng = np.random.default_rng(42)
760
+ human_idx = np.where(y == 0)[0]
761
+ ai_idx = np.where(y == 1)[0]
762
+
763
+ # Nasumično uzimamo target_human primjera iz human klase
764
+ chosen_human = rng.choice(human_idx, size=target_human, replace=False)
765
+
766
+ # Spajamo s AI primjerima i miješamo
767
+ all_idx = np.concatenate([chosen_human, ai_idx])
768
+ rng.shuffle(all_idx)
769
+
770
+ X = X[all_idx]
771
+ y = y[all_idx]
772
+ print(f" Nakon undersamplinga: Human={int(np.sum(y==0))}, "
773
+ f"AI={int(np.sum(y==1))}, Ukupno={len(y)}")
774
+ # ───────���──────────────────────────────────────────────────────────────
775
+
776
  # Treniraj
777
  model, scaler, metrics = treniraj(X, y, feature_names)
778
 
data/dataset.csv CHANGED
The diff for this file is too large to render. See raw diff
 
download_dataset.py CHANGED
@@ -1,211 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import csv
3
  import time
4
 
5
  from datasets import load_dataset
6
-
7
  from feature_extraction import extract_all_features
8
 
 
 
 
9
 
10
  # ─────────────────────────────────────────────────────────────────────────────
11
- # KONFIGURACIJA
12
  # ─────────────────────────────────────────────────────────────────────────────
13
 
14
- OUTPUT_DIR = "data"
15
- OUTPUT_FILE = os.path.join(OUTPUT_DIR, "dataset.csv")
 
16
 
17
- # Koliko primjera uzeti po datasetu (None = sve)
18
- # Za prvi brzi test stavi npr. 500, za pravo treniranje None
19
- MAX_SAMPLES_PER_DATASET = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
 
22
  # ─────────────────────────────────────────────────────────────────────────────
23
- # PARSERI ZA SVAKI DATASET
24
- # Svaki dataset ima svoju strukturu — ove funkcije je normaliziraju
25
- # u isti format: lista rječnika s ključevima "code", "label", "language"
26
  # ─────────────────────────────────────────────────────────────────────────────
27
 
28
  def parse_aigcodeset(max_samples=None):
29
- print(" Skidanje AIGCodeSet dataseta...")
 
 
 
 
30
  try:
31
  ds = load_dataset("basakdemirok/AIGCodeSet", split="train")
32
  except Exception as e:
33
- print(f" [GREŠKA] Nije moguće skinuti AIGCodeSet: {e}")
34
- return []
 
 
35
 
36
  primjeri = []
37
  for row in ds:
38
- # Izvuci kod — provjeri moguće nazive kolona
39
- code = row.get("code") or row.get("source_code") or row.get("content") or ""
40
- if not code or not code.strip():
41
- continue
42
-
43
- # Odredi oznaku — sve što nije "human" je AI
44
- raw_label = str(row.get("label", "")).lower()
45
- if "human" in raw_label:
46
- label = 0 # ljudski kod
47
- else:
48
- label = 1 # AI generirani kod
49
 
50
  primjeri.append({
51
- "code": code,
52
- "label": label,
53
- "language": "python", # AIGCodeSet je samo Python
54
- "source": "AIGCodeSet",
55
  })
 
 
 
 
 
56
 
57
- if max_samples and len(primjeri) >= max_samples:
58
- break
 
59
 
60
- human_count = sum(1 for p in primjeri if p["label"] == 0)
61
- ai_count = sum(1 for p in primjeri if p["label"] == 1)
62
- print(f" Učitano {len(primjeri)} primjera "
63
- f"({human_count} human, {ai_count} AI)")
64
  return primjeri
65
 
66
 
67
  def parse_ai_code_detection(max_samples=None):
68
- print(" Skidanje ai-code-detection dataseta...")
 
 
 
 
69
  try:
70
  ds = load_dataset("serafeimdossas/ai-code-detection", split="train")
71
  except Exception as e:
72
- print(f" [GREŠKA] Nije moguće skinuti ai-code-detection: {e}")
73
- return []
 
74
 
75
  primjeri = []
76
  for row in ds:
77
- code = row.get("code") or row.get("solution") or row.get("content") or ""
78
- if not code or not code.strip():
79
- continue
80
 
81
- raw_label = str(row.get("label", "")).lower()
82
- if "human" in raw_label:
83
- label = 0
84
- else:
85
- label = 1
86
 
87
  primjeri.append({
88
- "code": code,
89
- "label": label,
90
- "language": "python",
91
- "source": "ai-code-detection",
92
  })
 
 
 
 
 
 
93
 
94
- if max_samples and len(primjeri) >= max_samples:
95
- break
96
 
97
- human_count = sum(1 for p in primjeri if p["label"] == 0)
98
- ai_count = sum(1 for p in primjeri if p["label"] == 1)
99
- print(f" Učitano {len(primjeri)} primjera "
100
- f"({human_count} human, {ai_count} AI)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  return primjeri
102
 
103
 
104
  # ─────────────────────────────────────────────────────────────────────────────
105
- # IZVLAČENJE ZNAČAJKI I SPREMANJE U CSV
106
  # ─────────────────────────────────────────────────────────────────────────────
107
 
108
- def procesiraj_i_spremi(primjeri: list, output_path: str) -> None:
109
  os.makedirs(os.path.dirname(output_path), exist_ok=True)
110
-
111
- uspjesno = 0
112
- greske = 0
113
- pisac = None
114
- f = None
115
-
116
  print(f"\n Izvlačim značajke iz {len(primjeri)} primjera...")
117
- start_time = time.time()
118
 
119
  for i, primjer in enumerate(primjeri):
120
-
121
- # Ispis napretka svaki 100 primjera
122
  if i > 0 and i % 100 == 0:
123
- proteklo = time.time() - start_time
124
  preostalo = (proteklo / i) * (len(primjeri) - i)
125
- print(f" [{i}/{len(primjeri)}] "
126
- f"~{preostalo:.0f}s preostalo...", end="\r")
127
-
128
  try:
129
- # Izvuci sve značajke
130
  znacajke = extract_all_features(
131
  code=primjer["code"],
132
- language=primjer["language"],
133
  )
134
-
135
- # Dodaj oznaku i izvor uz značajke
136
- redak = {
137
- "label": primjer["label"],
138
- **znacajke,
139
- "source": primjer["source"],
140
- }
141
-
142
- # Otvori CSV i piši zaglavlje samo pri prvom retku
143
  if pisac is None:
144
  f = open(output_path, "w", newline="", encoding="utf-8")
145
  pisac = csv.DictWriter(f, fieldnames=list(redak.keys()))
146
  pisac.writeheader()
147
-
148
  pisac.writerow(redak)
149
  uspjesno += 1
150
-
151
  except Exception as e:
152
  greske += 1
153
- if greske <= 5: # ispiši samo prvih 5 grešaka
154
- print(f"\n [UPOZORENJE] Greška na primjeru {i}: {e}")
155
-
156
- if f:
157
- f.close()
158
 
159
- trajanje = time.time() - start_time
160
- print(f"\n Gotovo za {trajanje:.1f}s")
161
  print(f" Uspješno: {uspjesno} / {len(primjeri)}")
162
- if greske:
163
- print(f" Greške: {greske} (preskočeni)")
164
 
165
 
166
- # ─────────────────────────────────────────────────────────────────────────────
167
- # STATISTIKA O DATASETU
168
- # ─────────────────────────────────────────────────────────────────────────────
169
-
170
- def ispisi_statistiku(csv_path: str) -> None:
171
- """
172
- Učita gotovi CSV i ispiše osnovnu statistiku:
173
- broj primjera, omjer klasa, raspodjela po sourceu.
174
- """
175
- if not os.path.exists(csv_path):
176
- print(" CSV ne postoji, nema statistike.")
177
- return
178
-
179
- redovi = []
180
- with open(csv_path, "r", encoding="utf-8") as f:
181
- reader = csv.DictReader(f)
182
- redovi = list(reader)
183
-
184
- if not redovi:
185
- print(" CSV je prazan.")
186
- return
187
-
188
- ukupno = len(redovi)
189
- human = sum(1 for r in redovi if r["label"] == "0")
190
- ai = sum(1 for r in redovi if r["label"] == "1")
191
- num_feats = len(redovi[0]) - 2 # -2 za label i source
192
-
193
- # Statistika po sourceu
194
  from collections import Counter
195
  sources = Counter(r["source"] for r in redovi)
196
 
197
- print(f"\n{'═' * 50}")
198
  print(f" STATISTIKA DATASETA")
199
- print(f"{'═' * 50}")
200
- print(f" Ukupno primjera: {ukupno}")
201
- print(f" Human (label=0): {human} ({100*human/ukupno:.1f}%)")
202
- print(f" AI (label=1): {ai} ({100*ai/ukupno:.1f}%)")
203
- print(f" Broj značajki: {num_feats}")
204
  print(f"\n Po datasetu:")
205
- for source, count in sources.most_common():
206
- print(f" {source:<30} {count}")
 
207
  print(f"\n Spremljeno u: {csv_path}")
208
- print(f"{'═' * 50}\n")
209
 
210
 
211
  # ─────────────────────────────────────────────────────────────────────────────
@@ -217,43 +268,55 @@ def main():
217
  print(" Preuzimanje dataseta i izvlačenje značajki")
218
  print("=" * 50)
219
 
220
- print("\nKoji dataset želiš preuzeti?")
221
- print(" 1 — AIGCodeSet (7.583 Python primjera)")
222
- print(" 2 — ai-code-detection (Rosetta Code + CodeNet)")
223
- print(" 3 — Oba spojena (preporučeno)")
 
 
 
 
224
 
225
- odabir = input("\nOdabir (1/2/3): ").strip()
226
 
227
- # Brzi test mod
228
- print("\nBrzi test mod? (uzima samo 200 primjera, brže za provjeru)")
229
  test_mod = input("(d/n, Enter za ne): ").strip().lower()
230
- max_s = 200 if test_mod in ("d", "da", "y", "yes") else MAX_SAMPLES_PER_DATASET
231
 
232
- # Skidanje odabranog dataseta
233
  print()
234
  svi_primjeri = []
235
 
236
- if odabir in ("1", "3"):
237
  svi_primjeri += parse_aigcodeset(max_samples=max_s)
238
 
239
- if odabir in ("2", "3"):
240
  svi_primjeri += parse_ai_code_detection(max_samples=max_s)
241
 
 
 
 
 
242
  if not svi_primjeri:
243
- print("\n Nema primjera za procesiranje. Provjeri internetsku vezu.")
244
  return
245
 
246
- human_ukupno = sum(1 for p in svi_primjeri if p["label"] == 0)
247
- ai_ukupno = sum(1 for p in svi_primjeri if p["label"] == 1)
248
- print(f"\n Ukupno primjera za procesiranje: {len(svi_primjeri)}"
249
- f" ({human_ukupno} human, {ai_ukupno} AI)")
250
 
251
- # Izvuci značajke i spremi CSV
252
- procesiraj_i_spremi(svi_primjeri, OUTPUT_FILE)
 
 
253
 
254
- # Ispiši statistiku
255
- ispisi_statistiku(OUTPUT_FILE)
 
 
 
256
 
 
 
257
  print(" Sljedeći korak: python classifier.py")
258
 
259
 
 
1
+ """
2
+ download_dataset.py
3
+ ===================
4
+ Automatski skida besplatne datasete s HuggingFacea,
5
+ izvlači značajke i sprema u CSV za treniranje klasifikatora.
6
+
7
+ Pokretanje:
8
+ pip install datasets
9
+ python download_dataset.py
10
+ """
11
+
12
  import os
13
  import csv
14
  import time
15
 
16
  from datasets import load_dataset
 
17
  from feature_extraction import extract_all_features
18
 
19
+ OUTPUT_DIR = "data"
20
+ OUTPUT_FILE = os.path.join(OUTPUT_DIR, "dataset.csv")
21
+
22
 
23
  # ─────────────────────────────────────────────────────────────────────────────
24
+ # POMOĆNA FUNKCIJA: prepoznavanje labela
25
  # ─────────────────────────────────────────────────────────────────────────────
26
 
27
+ def parsiraj_label(raw_value) -> int:
28
+ """
29
+ Prepoznaje label bez obzira na format u datasetu.
30
 
31
+ Podržani formati:
32
+ - Integer: 0 → human, 1 → AI
33
+ - String: "human", "human-written", "Human_written" → human
34
+ sve ostalo → AI
35
+ - Boolean: False → human, True → AI
36
+
37
+ Vraća:
38
+ 0 za human, 1 za AI
39
+ """
40
+ # Integer ili integer u stringu
41
+ if isinstance(raw_value, (int, float)):
42
+ return int(raw_value)
43
+
44
+ # Boolean
45
+ if isinstance(raw_value, bool):
46
+ return 1 if raw_value else 0
47
+
48
+ # String — normaliziramo i tražimo ključne riječi
49
+ s = str(raw_value).lower().strip()
50
+
51
+ # Eksplicitni integer u stringu
52
+ if s in ("0",): return 0
53
+ if s in ("1",): return 1
54
+
55
+ # Opisni stringovi
56
+ if any(k in s for k in ("human", "person", "manual", "real")):
57
+ return 0 # human
58
+
59
+ return 1 # AI (sve ostalo: model nazivi, "ai", "generated", itd.)
60
+
61
+
62
+ def debug_labeli(ds, dataset_name, n=5):
63
+ """Ispiše prvih n labela da vidimo format."""
64
+ print(f" DEBUG {dataset_name} — prvih {n} labela:")
65
+ for i, row in enumerate(ds):
66
+ if i >= n: break
67
+ raw = row.get("label", row.get("is_generated", row.get("source", "?")))
68
+ print(f" [{i}] raw='{raw}' ({type(raw).__name__}) → {parsiraj_label(raw)}")
69
 
70
 
71
  # ─────────────────────────────────────────────────────────────────────────────
72
+ # PARSERI
 
 
73
  # ─────────────────────────────────────────────────────────────────────────────
74
 
75
  def parse_aigcodeset(max_samples=None):
76
+ """
77
+ AIGCodeSet — 4.755 human + 2.828 AI Python primjera.
78
+ Generirani modeli: CodeLlama, Codestral, Gemini.
79
+ """
80
+ print(" Skidanje AIGCodeSet...")
81
  try:
82
  ds = load_dataset("basakdemirok/AIGCodeSet", split="train")
83
  except Exception as e:
84
+ print(f" [GREŠKA] {e}"); return []
85
+
86
+ # Debug: prvih par labela da vidimo format
87
+ debug_labeli(ds, "AIGCodeSet")
88
 
89
  primjeri = []
90
  for row in ds:
91
+ code = (row.get("code") or row.get("source_code") or
92
+ row.get("content") or "")
93
+ if not code.strip(): continue
94
+
95
+ # Probaj sve moguće kolone za label
96
+ raw = (row.get("label") if row.get("label") is not None
97
+ else row.get("is_generated") if row.get("is_generated") is not None
98
+ else row.get("type", "1"))
99
+
100
+ label = parsiraj_label(raw)
 
101
 
102
  primjeri.append({
103
+ "code": code, "label": label,
104
+ "language": "python", "source": "AIGCodeSet"
 
 
105
  })
106
+ if max_samples and len(primjeri) >= max_samples: break
107
+
108
+ h = sum(1 for p in primjeri if p["label"] == 0)
109
+ a = sum(1 for p in primjeri if p["label"] == 1)
110
+ print(f" Učitano {len(primjeri)} ({h} human, {a} AI)")
111
 
112
+ if h == 0:
113
+ print(" UPOZORENJE: niti jedan human primjer nije prepoznat!")
114
+ print(" Provjeri debug output iznad — možda je kolona drukčija.")
115
 
 
 
 
 
116
  return primjeri
117
 
118
 
119
  def parse_ai_code_detection(max_samples=None):
120
+ """
121
+ ai-code-detection — 5.684 human + 6.143 AI Python primjera.
122
+ Rosetta Code + CodeNet programski zadaci.
123
+ """
124
+ print(" Skidanje ai-code-detection...")
125
  try:
126
  ds = load_dataset("serafeimdossas/ai-code-detection", split="train")
127
  except Exception as e:
128
+ print(f" [GREŠKA] {e}"); return []
129
+
130
+ debug_labeli(ds, "ai-code-detection")
131
 
132
  primjeri = []
133
  for row in ds:
134
+ code = (row.get("code") or row.get("solution") or
135
+ row.get("content") or "")
136
+ if not code.strip(): continue
137
 
138
+ raw = (row.get("label") if row.get("label") is not None
139
+ else row.get("is_generated", "1"))
140
+ label = parsiraj_label(raw)
 
 
141
 
142
  primjeri.append({
143
+ "code": code, "label": label,
144
+ "language": "python", "source": "ai-code-detection"
 
 
145
  })
146
+ if max_samples and len(primjeri) >= max_samples: break
147
+
148
+ h = sum(1 for p in primjeri if p["label"] == 0)
149
+ a = sum(1 for p in primjeri if p["label"] == 1)
150
+ print(f" Učitano {len(primjeri)} ({h} human, {a} AI)")
151
+ return primjeri
152
 
 
 
153
 
154
+ def parse_mbpp(max_samples=None):
155
+ """MBPP — 374 Python zadataka pisanih od programera."""
156
+ print(" Skidanje MBPP (human Python)...")
157
+ try:
158
+ ds = load_dataset("google-research-datasets/mbpp", split="train")
159
+ except Exception as e:
160
+ print(f" [GREŠKA] {e}"); return []
161
+
162
+ primjeri = []
163
+ for row in ds:
164
+ code = row.get("code") or ""
165
+ if not code.strip(): continue
166
+ primjeri.append({
167
+ "code": code, "label": 0,
168
+ "language": "python", "source": "MBPP"
169
+ })
170
+ if max_samples and len(primjeri) >= max_samples: break
171
+
172
+ print(f" Učitano {len(primjeri)} MBPP primjera (sve human)")
173
+ return primjeri
174
+
175
+
176
+ def parse_humaneval(max_samples=None):
177
+ """HumanEval — 164 Python benchmark funkcija (human rješenja)."""
178
+ print(" Skidanje HumanEval (human Python)...")
179
+ try:
180
+ ds = load_dataset("openai/openai_humaneval", split="test")
181
+ except Exception as e:
182
+ print(f" [GREŠKA] {e}"); return []
183
+
184
+ primjeri = []
185
+ for row in ds:
186
+ code = row.get("canonical_solution") or ""
187
+ if not code.strip() or len(code.splitlines()) < 2: continue
188
+ primjeri.append({
189
+ "code": code, "label": 0,
190
+ "language": "python", "source": "HumanEval"
191
+ })
192
+ if max_samples and len(primjeri) >= max_samples: break
193
+
194
+ print(f" Učitano {len(primjeri)} HumanEval primjera (sve human)")
195
  return primjeri
196
 
197
 
198
  # ─────────────────────────────────────────────────────────────────────────────
199
+ # OBRADA I SPREMANJE
200
  # ─────────────────────────────────────────────────────────────────────────────
201
 
202
+ def procesiraj_i_spremi(primjeri, output_path):
203
  os.makedirs(os.path.dirname(output_path), exist_ok=True)
204
+ uspjesno = greske = 0
205
+ pisac = f = None
206
+ start = time.time()
 
 
 
207
  print(f"\n Izvlačim značajke iz {len(primjeri)} primjera...")
 
208
 
209
  for i, primjer in enumerate(primjeri):
 
 
210
  if i > 0 and i % 100 == 0:
211
+ proteklo = time.time() - start
212
  preostalo = (proteklo / i) * (len(primjeri) - i)
213
+ print(f" [{i}/{len(primjeri)}] ~{preostalo:.0f}s preostalo...", end="\r")
 
 
214
  try:
 
215
  znacajke = extract_all_features(
216
  code=primjer["code"],
217
+ language=primjer["language"]
218
  )
219
+ redak = {"label": primjer["label"], **znacajke, "source": primjer["source"]}
 
 
 
 
 
 
 
 
220
  if pisac is None:
221
  f = open(output_path, "w", newline="", encoding="utf-8")
222
  pisac = csv.DictWriter(f, fieldnames=list(redak.keys()))
223
  pisac.writeheader()
 
224
  pisac.writerow(redak)
225
  uspjesno += 1
 
226
  except Exception as e:
227
  greske += 1
228
+ if greske <= 5:
229
+ print(f"\n [UPOZORENJE] Primjer {i}: {e}")
 
 
 
230
 
231
+ if f: f.close()
232
+ print(f"\n Gotovo za {time.time()-start:.1f}s")
233
  print(f" Uspješno: {uspjesno} / {len(primjeri)}")
234
+ if greske: print(f" Greške: {greske}")
 
235
 
236
 
237
+ def ispisi_statistiku(csv_path):
238
+ if not os.path.exists(csv_path): return
239
+ redovi = list(csv.DictReader(open(csv_path, encoding="utf-8")))
240
+ if not redovi: return
241
+ ukupno = len(redovi)
242
+ human = sum(1 for r in redovi if r["label"] == "0")
243
+ ai = sum(1 for r in redovi if r["label"] == "1")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  from collections import Counter
245
  sources = Counter(r["source"] for r in redovi)
246
 
247
+ print(f"\n{'═'*50}")
248
  print(f" STATISTIKA DATASETA")
249
+ print(f"{'═'*50}")
250
+ print(f" Ukupno: {ukupno}")
251
+ print(f" Human (0): {human} ({100*human/ukupno:.1f}%)")
252
+ print(f" AI (1): {ai} ({100*ai/ukupno:.1f}%)")
253
+ print(f" Značajki: {len(redovi[0]) - 2}")
254
  print(f"\n Po datasetu:")
255
+ for src, cnt in sources.most_common():
256
+ print(f" {src:<35} {cnt}")
257
+ print(f" Omjer human:AI = 1:{ai//max(human,1):.1f}")
258
  print(f"\n Spremljeno u: {csv_path}")
259
+ print(f"{'═'*50}\n")
260
 
261
 
262
  # ─────────────────────────────────────────────────────────────────────────────
 
268
  print(" Preuzimanje dataseta i izvlačenje značajki")
269
  print("=" * 50)
270
 
271
+ print("""
272
+ Koji dataset želiš preuzeti?
273
+
274
+ 1 — AIGCodeSet (4.755 human + 2.828 AI)
275
+ 2 — ai-code-detection (5.684 human + 6.143 AI)
276
+ 3 — Opcije 1 + 2 (preporučeno)
277
+ 4 — Sve + MBPP + HumanEval (najviše podataka)
278
+ """)
279
 
280
+ odabir = input("Odabir (1/2/3/4): ").strip()
281
 
282
+ print("\nBrzi test mod? (200 primjera, provjera parsera)")
 
283
  test_mod = input("(d/n, Enter za ne): ").strip().lower()
284
+ max_s = 200 if test_mod in ("d", "da", "y", "yes") else None
285
 
 
286
  print()
287
  svi_primjeri = []
288
 
289
+ if odabir in ("1", "3", "4"):
290
  svi_primjeri += parse_aigcodeset(max_samples=max_s)
291
 
292
+ if odabir in ("2", "3", "4"):
293
  svi_primjeri += parse_ai_code_detection(max_samples=max_s)
294
 
295
+ if odabir in ("4",):
296
+ svi_primjeri += parse_mbpp(max_samples=max_s)
297
+ svi_primjeri += parse_humaneval(max_samples=max_s)
298
+
299
  if not svi_primjeri:
300
+ print("\n Nema primjera. Provjeri internet i odabir.")
301
  return
302
 
303
+ h = sum(1 for p in svi_primjeri if p["label"] == 0)
304
+ a = sum(1 for p in svi_primjeri if p["label"] == 1)
305
+ print(f"\n Ukupno: {len(svi_primjeri)} ({h} human, {a} AI)")
 
306
 
307
+ if h == 0:
308
+ print("\n GREŠKA: Nijedan human primjer nije pronađen!")
309
+ print(" Provjeri debug output iznad.")
310
+ return
311
 
312
+ omjer = a / max(h, 1)
313
+ print(f" Omjer AI:human = {omjer:.1f}:1")
314
+ if omjer > 5:
315
+ print(" UPOZORENJE: Dataset je nebalansiran (>5:1).")
316
+ print(" classifier.py će primijeniti undersampling.")
317
 
318
+ procesiraj_i_spremi(svi_primjeri, OUTPUT_FILE)
319
+ ispisi_statistiku(OUTPUT_FILE)
320
  print(" Sljedeći korak: python classifier.py")
321
 
322
 
feature_extraction.py CHANGED
@@ -623,3 +623,185 @@ public class Calculator {
623
  print(f" {display_name:<32} {val}")
624
 
625
  print(f"\n Ukupno značajki: {len(features)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623
  print(f" {display_name:<32} {val}")
624
 
625
  print(f"\n Ukupno značajki: {len(features)}")
626
+
627
+
628
+ # ─────────────────────────────────────────────────────────────────────────────
629
+ # ANALIZA PO LINIJAMA — za prikaz sumnjivih linija u UI-u
630
+ # ─────────────────────────────────────────────────────────────────────────────
631
+
632
+ def analyze_lines(code: str, language: str = None, filename: str = None) -> list:
633
+ """
634
+ Analizira kod liniju po liniju i vraća listu sumnjivih linija.
635
+
636
+ Svaki element liste je rječnik:
637
+ {
638
+ "line": int, # broj linije (1-based)
639
+ "tone": str, # "red" = jak signal, "amber" = umjeren
640
+ "note": str, # kratko objašnjenje (prikazuje se u UI-u)
641
+ }
642
+
643
+ Detektira sljedeće AI signale po liniji:
644
+ - Docstringovi i formalni blok komentari (jak signal)
645
+ - Jednolinijski komentari (umjeren signal)
646
+ - Linije s dugačkim identifikatorima (umjeren signal)
647
+ - Type anotacije (umjeren signal)
648
+ - Try/except/raise/throw s formalnim porukama (umjeren signal)
649
+ - Linije s višestrukim opisnim identifikatorima (jak signal)
650
+
651
+ Parametri:
652
+ code (str): Izvorni kod kao string.
653
+ language (str|None): Naziv jezika — ako None, automatski se detektira.
654
+ filename (str|None): Ime datoteke — pomaže detekciji jezika.
655
+
656
+ Vraća:
657
+ list: Lista rječnika s anotacijama, sortirana po broju linije.
658
+ """
659
+ import re
660
+
661
+ if language is None:
662
+ if filename is not None:
663
+ language = detect_language_from_extension(filename) or detect_language_from_code(code)
664
+ else:
665
+ language = detect_language_from_code(code)
666
+
667
+ try:
668
+ lang_config = get_config(language)
669
+ except ValueError:
670
+ lang_config = get_config("python")
671
+
672
+ lines = code.splitlines()
673
+ annotations = []
674
+ in_docstring = False
675
+ docstring_char = None
676
+
677
+ inline_pat = lang_config.get("inline_comment", r"^\s*#")
678
+
679
+ for i, line in enumerate(lines, start=1):
680
+ stripped = line.strip()
681
+ if not stripped:
682
+ continue
683
+
684
+ # ── DOCSTRINGOVI / BLOK KOMENTARI ─────────────────────────────────
685
+ # Python docstringovi (""" ili ''')
686
+ if language == "python":
687
+ triple_count = stripped.count('"""') + stripped.count("'''")
688
+ if not in_docstring and ('"""' in stripped or "'''" in stripped):
689
+ docstring_char = '"""' if '"""' in stripped else "'''"
690
+ # Ako se otvara i zatvara na istoj liniji → jednolinijski docstring
691
+ if stripped.count(docstring_char) >= 2 and len(stripped) > 6:
692
+ annotations.append({
693
+ "line": i, "tone": "red",
694
+ "note": "Formal docstring — strong AI indicator"
695
+ })
696
+ else:
697
+ in_docstring = True
698
+ annotations.append({
699
+ "line": i, "tone": "red",
700
+ "note": "Docstring block — strong AI indicator"
701
+ })
702
+ continue
703
+ elif in_docstring:
704
+ annotations.append({
705
+ "line": i, "tone": "red",
706
+ "note": "Docstring content"
707
+ })
708
+ if docstring_char and docstring_char in stripped:
709
+ in_docstring = False
710
+ continue
711
+
712
+ # Javadoc / JSDoc blokovi (/** ... */)
713
+ if language in ("java", "javascript", "typescript", "cpp", "c"):
714
+ if stripped.startswith("/**") or stripped.startswith("* ") or stripped == "*/":
715
+ annotations.append({
716
+ "line": i, "tone": "red",
717
+ "note": "Formal documentation comment — strong AI indicator"
718
+ })
719
+ continue
720
+
721
+ # ── JEDNOLINIJSKI KOMENTARI ────────────────────────────────────────
722
+ if re.match(inline_pat, line):
723
+ # Gledamo duljinu komentara — kratki (#) ne flagiramo
724
+ comment_text = re.sub(inline_pat, "", line).strip()
725
+ word_count = len(comment_text.split())
726
+ if word_count >= 4:
727
+ annotations.append({
728
+ "line": i, "tone": "amber",
729
+ "note": f"Inline comment ({word_count} words) — elevated comment density"
730
+ })
731
+ continue
732
+
733
+ # ── DUGAČKI IDENTIFIKATORI ─────────────────────────────────────────
734
+ # VAŽNO: Prije analize, uklonimo sadržaj string literala s linije.
735
+ # Bez ovoga, regex bi uhvatio i prirodne riječi unutar stringova
736
+ # (npr. "Ucitajte red matrice") kao identifikatore — što je pogrešno.
737
+ code_only = re.sub(r'"[^"]*"', '""', stripped) # ukloni "..."
738
+ code_only = re.sub(r"'[^']*'", "''", code_only) # ukloni '...'
739
+ code_only = re.sub(r"`[^`]*`", "``", code_only) # ukloni `...`
740
+
741
+ identifiers = re.findall(r'\b([a-zA-Z_][a-zA-Z0-9_]{4,})\b', code_only)
742
+
743
+ # Preskačemo rezervirane riječi i uobičajene kratke stdlib nazive
744
+ reserved = {
745
+ "return", "import", "function", "class", "interface", "public",
746
+ "private", "static", "const", "false", "true", "none", "self",
747
+ "print", "printf", "scanf", "range", "raise", "while", "break",
748
+ "continue", "yield", "lambda", "assert", "except", "finally",
749
+ "include", "define", "string", "vector", "struct", "unsigned",
750
+ "length", "value", "write", "reads", "fopen", "fclose", "malloc",
751
+ "sizeof", "stdio", "stdlib", "nullptr", "virtual", "override",
752
+ "inline", "extern", "register", "volatile", "switch", "default",
753
+ }
754
+ real_ids = [x for x in identifiers if x.lower() not in reserved]
755
+
756
+ if len(real_ids) >= 2:
757
+ avg_len = sum(len(x) for x in real_ids) / len(real_ids)
758
+ if avg_len >= 9:
759
+ annotations.append({
760
+ "line": i, "tone": "red",
761
+ "note": f"Very long identifiers (avg {avg_len:.0f} chars) — AI naming pattern"
762
+ })
763
+ continue
764
+ elif avg_len >= 7:
765
+ annotations.append({
766
+ "line": i, "tone": "amber",
767
+ "note": f"Descriptive identifier names (avg {avg_len:.0f} chars)"
768
+ })
769
+ continue
770
+
771
+ # ── TYPE ANOTACIJE (Python) ────────────────────────────────────────
772
+ if language == "python":
773
+ if re.search(r'\)\s*->\s*\w', stripped) or re.search(r':\s*(int|float|str|bool|list|dict|tuple|set|Optional|Union|List|Dict)\b', stripped):
774
+ annotations.append({
775
+ "line": i, "tone": "amber",
776
+ "note": "Type annotation — uncommon in student code"
777
+ })
778
+ continue
779
+
780
+ # ── TRY/EXCEPT/RAISE S PORUKAMA ────────────────────────────────────
781
+ if re.match(r'^\s*(raise|throw)\s+\w*Error\s*\(', line) or \
782
+ re.match(r'^\s*(raise|throw)\s+\w*Exception\s*\(', line):
783
+ annotations.append({
784
+ "line": i, "tone": "amber",
785
+ "note": "Explicit exception with message — AI error handling pattern"
786
+ })
787
+ continue
788
+
789
+ if re.match(r'^\s*(except|catch)\s*[\(\w]', line):
790
+ annotations.append({
791
+ "line": i, "tone": "amber",
792
+ "note": "Exception handling — AI code often handles all edge cases"
793
+ })
794
+ continue
795
+
796
+ # Makni previše sumnjivih linija — ako je >60% flagirano, to gubi smisao
797
+ # Prikaži samo najsumnjivije linije (max 40% koda)
798
+ total_nonblank = sum(1 for l in lines if l.strip())
799
+ max_annotations = max(3, int(total_nonblank * 0.40))
800
+
801
+ # Sortiraj: red prije amber, onda po broju linije
802
+ priority = {"red": 0, "amber": 1}
803
+ annotations.sort(key=lambda a: (priority.get(a["tone"], 2), a["line"]))
804
+ annotations = annotations[:max_annotations]
805
+ annotations.sort(key=lambda a: a["line"])
806
+
807
+ return annotations
frontend/src/App.jsx CHANGED
@@ -5,11 +5,28 @@ import BatchScreen from './screens/BatchScreen'
5
  import SimilarityScreen from './screens/SimilarityScreen'
6
  import DetailScreen from './screens/DetailScreen'
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  export default function App() {
9
- const [screen, setScreen] = useState('analyze')
10
  const [detailRow, setDetailRow] = useState(null)
11
- const [serverOk, setServerOk] = useState(null)
12
 
 
13
  useEffect(() => {
14
  fetch('/api/health')
15
  .then(r => r.json())
@@ -17,12 +34,37 @@ export default function App() {
17
  .catch(() => setServerOk(false))
18
  }, [])
19
 
20
- const navigate = (s) => { setScreen(s); setDetailRow(null) }
21
- const openDetail = (row) => { setDetailRow(row); setScreen('detail') }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  return (
24
  <div style={{ minHeight: '100vh', background: '#0A0F1C', position: 'relative' }}>
25
- {/* Atmospheric glow */}
26
  <div style={{
27
  position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 0,
28
  background: 'radial-gradient(ellipse 1200px 600px at 50% -10%, rgba(0,212,255,0.08), transparent 60%)',
@@ -31,14 +73,13 @@ export default function App() {
31
  <div style={{ position: 'relative', zIndex: 1 }}>
32
  <Navbar active={screen === 'detail' ? 'batch' : screen} onNavigate={navigate}/>
33
 
34
- {/* Server status banner */}
35
  {serverOk === false && (
36
  <div style={{
37
  background: 'rgba(239,68,68,0.12)', borderBottom: '1px solid rgba(239,68,68,0.25)',
38
  padding: '10px 80px', display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: '#EF4444',
39
  }}>
40
  <span>⚠</span>
41
- <span>Flask server not reachable. Start it with: <code style={{ fontFamily: 'JetBrains Mono, monospace', background: 'rgba(239,68,68,0.12)', padding: '2px 6px', borderRadius: 4 }}>python app.py</code></span>
42
  </div>
43
  )}
44
 
@@ -53,9 +94,17 @@ export default function App() {
53
  )}
54
 
55
  {screen === 'analyze' && <AnalyzeScreen/>}
56
- {screen === 'batch' && <BatchScreen onOpenRow={openDetail}/>}
57
  {screen === 'similarity' && <SimilarityScreen/>}
58
- {screen === 'detail' && <DetailScreen row={detailRow} onBack={() => setScreen('batch')}/>}
 
 
 
 
 
 
 
 
 
59
  </div>
60
  </div>
61
  )
 
5
  import SimilarityScreen from './screens/SimilarityScreen'
6
  import DetailScreen from './screens/DetailScreen'
7
 
8
+ // Hash-based routing — svaki ekran ima vlastiti URL fragment
9
+ // Tako browser back/forward gumb rade ispravno
10
+ const SCREEN_TO_HASH = {
11
+ analyze: '#analyze',
12
+ batch: '#batch',
13
+ similarity: '#similarity',
14
+ detail: '#detail',
15
+ }
16
+ const HASH_TO_SCREEN = Object.fromEntries(
17
+ Object.entries(SCREEN_TO_HASH).map(([k, v]) => [v, k])
18
+ )
19
+
20
+ function getScreenFromHash() {
21
+ return HASH_TO_SCREEN[window.location.hash] || 'analyze'
22
+ }
23
+
24
  export default function App() {
25
+ const [screen, setScreen] = useState(getScreenFromHash)
26
  const [detailRow, setDetailRow] = useState(null)
27
+ const [serverOk, setServerOk] = useState(null)
28
 
29
+ // Health check
30
  useEffect(() => {
31
  fetch('/api/health')
32
  .then(r => r.json())
 
34
  .catch(() => setServerOk(false))
35
  }, [])
36
 
37
+ // Slušamo browser back/forward
38
+ useEffect(() => {
39
+ const onPop = () => {
40
+ const s = getScreenFromHash()
41
+ setScreen(s)
42
+ // Ako se vraćamo s detail-a, detailRow ostaje — batch zadržava state
43
+ }
44
+ window.addEventListener('popstate', onPop)
45
+ return () => window.removeEventListener('popstate', onPop)
46
+ }, [])
47
+
48
+ // Navigacija — pushState mijenja URL i bilježi u history
49
+ const navigate = (s) => {
50
+ if (s !== 'batch' && s !== 'detail') setDetailRow(null)
51
+ window.history.pushState({ screen: s }, '', SCREEN_TO_HASH[s])
52
+ setScreen(s)
53
+ }
54
+
55
+ const openDetail = (row) => {
56
+ setDetailRow(row)
57
+ window.history.pushState({ screen: 'detail' }, '', '#detail')
58
+ setScreen('detail')
59
+ }
60
+
61
+ const backToBatch = () => {
62
+ window.history.pushState({ screen: 'batch' }, '', '#batch')
63
+ setScreen('batch')
64
+ }
65
 
66
  return (
67
  <div style={{ minHeight: '100vh', background: '#0A0F1C', position: 'relative' }}>
 
68
  <div style={{
69
  position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 0,
70
  background: 'radial-gradient(ellipse 1200px 600px at 50% -10%, rgba(0,212,255,0.08), transparent 60%)',
 
73
  <div style={{ position: 'relative', zIndex: 1 }}>
74
  <Navbar active={screen === 'detail' ? 'batch' : screen} onNavigate={navigate}/>
75
 
 
76
  {serverOk === false && (
77
  <div style={{
78
  background: 'rgba(239,68,68,0.12)', borderBottom: '1px solid rgba(239,68,68,0.25)',
79
  padding: '10px 80px', display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: '#EF4444',
80
  }}>
81
  <span>⚠</span>
82
+ <span>Flask server not reachable — <code style={{ fontFamily: 'JetBrains Mono, monospace', background: 'rgba(239,68,68,0.12)', padding: '2px 6px', borderRadius: 4 }}>python app.py</code></span>
83
  </div>
84
  )}
85
 
 
94
  )}
95
 
96
  {screen === 'analyze' && <AnalyzeScreen/>}
 
97
  {screen === 'similarity' && <SimilarityScreen/>}
98
+
99
+ {/* BatchScreen ostaje montiran dok smo u batch/detail ciklusu */}
100
+ <div style={{ display: screen === 'batch' || screen === 'detail' ? 'block' : 'none' }}>
101
+ <div style={{ display: screen === 'batch' ? 'block' : 'none' }}>
102
+ <BatchScreen onOpenRow={openDetail}/>
103
+ </div>
104
+ <div style={{ display: screen === 'detail' ? 'block' : 'none' }}>
105
+ <DetailScreen row={detailRow} onBack={backToBatch}/>
106
+ </div>
107
+ </div>
108
  </div>
109
  </div>
110
  )
frontend/src/api/client.js CHANGED
@@ -1,4 +1,4 @@
1
- // api/client.js — sve API pozive na Flask backend
2
 
3
  const BASE = '/api'
4
 
@@ -22,9 +22,70 @@ export const checkHealth = () => request('GET', '/health')
22
  export const analyzeCode = (code, language, filename) =>
23
  request('POST', '/analyze', { code, language, filename })
24
 
25
- // Analiza više kodova odjednom
26
- export const analyzeBatch = (submissions) =>
27
- request('POST', '/analyze-batch', { submissions })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  // Matrica sličnosti
30
  export const computeSimilarity = (submissions) =>
 
1
+ // api/client.js — svi API pozivi na Flask backend
2
 
3
  const BASE = '/api'
4
 
 
22
  export const analyzeCode = (code, language, filename) =>
23
  request('POST', '/analyze', { code, language, filename })
24
 
25
+ /**
26
+ * Batch analiza s real-time streamingom.
27
+ *
28
+ * Umjesto da čeka sve rezultate (što uzrokuje timeout),
29
+ * čita NDJSON stream i poziva callback za svaki rezultat
30
+ * čim stigne s backenda.
31
+ *
32
+ * @param {Array} submissions - lista { id, file, code }
33
+ * @param {Function} onResult - poziva se za svaki gotov fajl: (result, index, total) => void
34
+ * @param {Function} onProgress - poziva se s postotkom napretka: (pct) => void
35
+ * @returns {Promise<Object>} - summary objekt na kraju
36
+ */
37
+ export async function analyzeBatch(submissions, onResult, onProgress) {
38
+ const res = await fetch(`${BASE}/analyze-batch`, {
39
+ method: 'POST',
40
+ headers: { 'Content-Type': 'application/json' },
41
+ body: JSON.stringify({ submissions }),
42
+ })
43
+
44
+ if (!res.ok) {
45
+ const err = await res.json().catch(() => ({}))
46
+ throw new Error(err.error || `HTTP ${res.status}`)
47
+ }
48
+
49
+ // Čitamo stream liniju po liniju
50
+ const reader = res.body.getReader()
51
+ const decoder = new TextDecoder()
52
+ let buffer = ''
53
+ let count = 0
54
+ let summary = null
55
+ const total = submissions.length
56
+
57
+ while (true) {
58
+ const { done, value } = await reader.read()
59
+ if (done) break
60
+
61
+ buffer += decoder.decode(value, { stream: true })
62
+ const lines = buffer.split('\n')
63
+
64
+ // Sve linije osim zadnje su kompletne
65
+ buffer = lines.pop()
66
+
67
+ for (const line of lines) {
68
+ if (!line.trim()) continue
69
+ try {
70
+ const msg = JSON.parse(line)
71
+
72
+ if (msg.type === 'result') {
73
+ count++
74
+ if (onResult) onResult(msg.data, count, total)
75
+ if (onProgress) onProgress(Math.round((count / total) * 100))
76
+ }
77
+
78
+ if (msg.type === 'summary') {
79
+ summary = msg.data
80
+ }
81
+ } catch {
82
+ // Ignoriraj neispravne linije
83
+ }
84
+ }
85
+ }
86
+
87
+ return summary || { total: count }
88
+ }
89
 
90
  // Matrica sličnosti
91
  export const computeSimilarity = (submissions) =>
frontend/src/api/client2.js ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // api/client.js — sve API pozive na Flask backend
2
+
3
+ const BASE = '/api'
4
+
5
+ async function request(method, path, body) {
6
+ const res = await fetch(`${BASE}${path}`, {
7
+ method,
8
+ headers: { 'Content-Type': 'application/json' },
9
+ body: body ? JSON.stringify(body) : undefined,
10
+ })
11
+ if (!res.ok) {
12
+ const err = await res.json().catch(() => ({}))
13
+ throw new Error(err.error || `HTTP ${res.status}`)
14
+ }
15
+ return res.json()
16
+ }
17
+
18
+ // Provjera statusa servera
19
+ export const checkHealth = () => request('GET', '/health')
20
+
21
+ // Analiza jednog isječka koda
22
+ export const analyzeCode = (code, language, filename) =>
23
+ request('POST', '/analyze', { code, language, filename })
24
+
25
+ // Analiza više kodova odjednom
26
+ export const analyzeBatch = (submissions) =>
27
+ request('POST', '/analyze-batch', { submissions })
28
+
29
+ // Matrica sličnosti
30
+ export const computeSimilarity = (submissions) =>
31
+ request('POST', '/similarity', { submissions })
frontend/src/components/CodeEditor.jsx CHANGED
@@ -1,30 +1,63 @@
 
1
  import { LangBadge } from './primitives'
2
 
 
3
  function SyntaxTinted({ code }) {
4
- const tokens = code.split(/(\b(?:def|return|if|else|elif|for|while|import|from|class|in|not|and|or|True|False|None|self|function|const|let|var|=>|public|private|static|void|int|string|bool)\b|"[^"]*"|'[^']*'|`[^`]*`|#[^\n]*|\/\/[^\n]*|\/\*[\s\S]*?\*\/|\b\d+\b)/g)
 
 
5
  return tokens.map((t, i) => {
6
- if (/^(def|return|if|else|elif|for|while|import|from|class|in|not|and|or|True|False|None|self|function|const|let|var|public|private|static|void|int|string|bool)$/.test(t))
7
  return <span key={i} style={{ color: '#22E0FF' }}>{t}</span>
8
- if (/^["'`].*["'`]$/.test(t)) return <span key={i} style={{ color: '#10B981' }}>{t}</span>
9
- if (/^(#|\/\/)/.test(t)) return <span key={i} style={{ color: '#64748B', fontStyle: 'italic' }}>{t}</span>
10
- if (/^\d+$/.test(t)) return <span key={i} style={{ color: '#F59E0B' }}>{t}</span>
 
 
 
11
  return <span key={i}>{t}</span>
12
  })
13
  }
14
 
15
- export default function CodeEditor({ code, onChange, lang = 'Python', readOnly = false, height = 360, annotations = [], filename }) {
 
 
 
 
 
 
 
 
 
16
  const lines = (code || '').split('\n')
17
- const displayName = filename || 'submission.' + (lang === 'Python' ? 'py' : lang === 'Java' ? 'java' : lang === 'JavaScript' ? 'js' : 'txt')
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  return (
20
  <div style={{
21
- background: '#0F172A', border: '1px solid rgba(148,163,184,0.12)',
22
- borderRadius: 10, overflow: 'hidden', boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.03)',
 
 
 
23
  }}>
24
- {/* Header bar */}
 
25
  <div style={{
26
  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
27
- padding: '10px 14px', borderBottom: '1px solid rgba(148,163,184,0.12)',
 
28
  background: 'rgba(15,23,41,0.6)',
29
  }}>
30
  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
@@ -33,73 +66,168 @@ export default function CodeEditor({ code, onChange, lang = 'Python', readOnly =
33
  <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#F59E0B', opacity: 0.6 }}/>
34
  <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#10B981', opacity: 0.6 }}/>
35
  </div>
36
- <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12, color: '#94A3B8' }}>{displayName}</span>
 
 
37
  </div>
38
  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
39
- {!readOnly && <span style={{ fontSize: 10, color: '#64748B', letterSpacing: '0.04em', textTransform: 'uppercase' }}>Auto-detected</span>}
 
 
 
 
 
 
 
 
 
40
  <LangBadge lang={lang}/>
41
  </div>
42
  </div>
43
 
44
- {/* Editor body */}
45
- <div style={{ display: 'flex', height, position: 'relative', overflow: 'hidden' }}>
46
- {/* Line numbers */}
47
- <div style={{
48
- padding: '12px 12px 12px 16px', background: 'rgba(10,15,28,0.4)',
49
- fontFamily: 'JetBrains Mono, monospace', fontSize: 12, lineHeight: 1.7,
50
- color: '#475569', textAlign: 'right', userSelect: 'none',
51
- borderRight: '1px solid rgba(148,163,184,0.08)', minWidth: 44,
52
- overflowY: 'hidden',
53
- }}>
54
- {lines.map((_, i) => {
55
- const ann = annotations.find(a => a.line === i + 1)
56
- return (
57
- <div key={i} style={{
58
- color: ann ? (ann.tone === 'red' ? '#EF4444' : '#F59E0B') : '#475569',
59
- fontWeight: ann ? 600 : 400,
60
- }}>{i + 1}</div>
61
- )
62
- })}
63
- </div>
 
 
 
 
 
 
 
 
 
64
 
65
- {/* Code area */}
66
- <div style={{ flex: 1, position: 'relative', overflow: 'auto' }}>
67
- {annotations.map((a, i) => (
68
- <div key={i} style={{
69
- position: 'absolute', left: 0, right: 0,
70
- top: `calc(12px + ${a.line - 1} * 1.7em)`, height: '1.7em',
71
- background: a.tone === 'red' ? 'rgba(239,68,68,0.08)' : 'rgba(245,158,11,0.08)',
72
- borderLeft: `2px solid ${a.tone === 'red' ? '#EF4444' : '#F59E0B'}`,
73
- pointerEvents: 'none', zIndex: 1,
74
- }}>
75
- {a.note && (
76
- <span style={{
77
- position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
78
- fontSize: 10, color: a.tone === 'red' ? '#EF4444' : '#F59E0B',
79
- fontFamily: 'Inter, sans-serif', background: a.tone === 'red' ? 'rgba(239,68,68,0.12)' : 'rgba(245,158,11,0.12)',
80
- padding: '2px 6px', borderRadius: 4,
81
- }}>⚠ {a.note}</span>
82
- )}
83
- </div>
84
- ))}
85
- {readOnly ? (
86
- <pre style={{
87
- margin: 0, padding: '12px 16px',
88
- fontFamily: 'JetBrains Mono, monospace', fontSize: 12, lineHeight: 1.7,
89
- color: '#CBD5E1', whiteSpace: 'pre', overflow: 'visible',
90
- }}><SyntaxTinted code={code}/></pre>
91
- ) : (
92
- <textarea value={code} onChange={e => onChange && onChange(e.target.value)}
93
- spellCheck="false" placeholder="Paste your code here…"
94
- style={{
95
- width: '100%', height: '100%', border: 'none', outline: 'none', resize: 'none',
96
- background: 'transparent', color: '#CBD5E1',
97
- fontFamily: 'JetBrains Mono, monospace', fontSize: 12, lineHeight: 1.7,
98
- padding: '12px 16px',
99
- }}/>
100
- )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  </div>
102
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  </div>
104
  )
105
  }
 
1
+ import { useRef } from 'react'
2
  import { LangBadge } from './primitives'
3
 
4
+ // Osnovna syntax tinting za čitljivost (nije full highlighter)
5
  function SyntaxTinted({ code }) {
6
+ const tokens = code.split(
7
+ /(\b(?:def|return|if|else|elif|for|while|import|from|class|in|not|and|or|True|False|None|self|function|const|let|var|public|private|static|void|int|string|bool|unsigned|include|struct|typedef)\b|"[^"]*"|'[^']*'|`[^`]*`|\/\/[^\n]*|#[^\n]*|\b\d+\b)/g
8
+ )
9
  return tokens.map((t, i) => {
10
+ if (/^(def|return|if|else|elif|for|while|import|from|class|in|not|and|or|True|False|None|self|function|const|let|var|public|private|static|void|int|string|bool|unsigned|struct|typedef)$/.test(t))
11
  return <span key={i} style={{ color: '#22E0FF' }}>{t}</span>
12
+ if (/^["'`].*["'`]$/.test(t))
13
+ return <span key={i} style={{ color: '#10B981' }}>{t}</span>
14
+ if (/^(#|\/\/)/.test(t))
15
+ return <span key={i} style={{ color: '#64748B', fontStyle: 'italic' }}>{t}</span>
16
+ if (/^\d+$/.test(t))
17
+ return <span key={i} style={{ color: '#F59E0B' }}>{t}</span>
18
  return <span key={i}>{t}</span>
19
  })
20
  }
21
 
22
+ export default function CodeEditor({
23
+ code,
24
+ onChange,
25
+ lang = 'Python',
26
+ readOnly = false,
27
+ height = 360,
28
+ annotations = [],
29
+ filename,
30
+ }) {
31
+ const scrollRef = useRef(null)
32
  const lines = (code || '').split('\n')
33
+ const displayName = filename || ('submission.' + (
34
+ lang === 'Python' ? 'py' :
35
+ lang === 'Java' ? 'java' :
36
+ lang === 'JavaScript' ? 'js' :
37
+ lang === 'C++' ? 'cpp' :
38
+ lang === 'C' ? 'c' : 'txt'
39
+ ))
40
+
41
+ // Mapa linija na anotacije za brzo traženje
42
+ const annotMap = {}
43
+ for (const a of annotations) {
44
+ annotMap[a.line] = a
45
+ }
46
 
47
  return (
48
  <div style={{
49
+ background: '#0F172A',
50
+ border: '1px solid rgba(148,163,184,0.12)',
51
+ borderRadius: 10,
52
+ overflow: 'hidden',
53
+ boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.03)',
54
  }}>
55
+
56
+ {/* ── Header ── */}
57
  <div style={{
58
  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
59
+ padding: '10px 14px',
60
+ borderBottom: '1px solid rgba(148,163,184,0.12)',
61
  background: 'rgba(15,23,41,0.6)',
62
  }}>
63
  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
 
66
  <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#F59E0B', opacity: 0.6 }}/>
67
  <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#10B981', opacity: 0.6 }}/>
68
  </div>
69
+ <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12, color: '#94A3B8' }}>
70
+ {displayName}
71
+ </span>
72
  </div>
73
  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
74
+ {annotations.length > 0 && (
75
+ <span style={{
76
+ fontSize: 10, color: '#F59E0B', letterSpacing: '0.04em',
77
+ background: 'rgba(245,158,11,0.10)', border: '1px solid rgba(245,158,11,0.25)',
78
+ padding: '2px 8px', borderRadius: 4,
79
+ }}>
80
+ {annotations.filter(a => a.tone === 'red').length} strong ·{' '}
81
+ {annotations.filter(a => a.tone === 'amber').length} moderate
82
+ </span>
83
+ )}
84
  <LangBadge lang={lang}/>
85
  </div>
86
  </div>
87
 
88
+ {/* ── Editor tijelo ──
89
+ Jedan scroll container koji sadrži i broj linije i kod,
90
+ tako da se uvijek pomiču zajedno.
91
+ */}
92
+ {readOnly ? (
93
+ <div ref={scrollRef} style={{ height, overflow: 'auto' }}>
94
+ <table style={{
95
+ borderCollapse: 'collapse',
96
+ width: '100%',
97
+ fontFamily: 'JetBrains Mono, monospace',
98
+ fontSize: 12,
99
+ lineHeight: 1.7,
100
+ }}>
101
+ <tbody>
102
+ {lines.map((line, idx) => {
103
+ const lineNum = idx + 1
104
+ const ann = annotMap[lineNum]
105
+ const isRed = ann?.tone === 'red'
106
+ const isAmber = ann?.tone === 'amber'
107
+ const bgColor = isRed
108
+ ? 'rgba(239,68,68,0.10)'
109
+ : isAmber
110
+ ? 'rgba(245,158,11,0.08)'
111
+ : 'transparent'
112
+ const borderLeft = isRed
113
+ ? '2px solid #EF4444'
114
+ : isAmber
115
+ ? '2px solid #F59E0B'
116
+ : '2px solid transparent'
117
 
118
+ return (
119
+ <tr key={idx} title={ann?.note || ''} style={{ background: bgColor }}>
120
+
121
+ {/* Broj linije */}
122
+ <td style={{
123
+ width: 44,
124
+ minWidth: 44,
125
+ padding: '0 10px 0 16px',
126
+ textAlign: 'right',
127
+ color: ann ? (isRed ? '#EF4444' : '#F59E0B') : '#475569',
128
+ userSelect: 'none',
129
+ borderRight: '1px solid rgba(148,163,184,0.08)',
130
+ borderLeft,
131
+ verticalAlign: 'top',
132
+ paddingTop: '1px',
133
+ whiteSpace: 'nowrap',
134
+ }}>
135
+ {lineNum}
136
+ </td>
137
+
138
+ {/* Ikona oznake (samo za označene linije) */}
139
+ <td style={{
140
+ width: 20,
141
+ minWidth: 20,
142
+ textAlign: 'center',
143
+ verticalAlign: 'top',
144
+ paddingTop: '2px',
145
+ color: isRed ? '#EF4444' : isAmber ? '#F59E0B' : 'transparent',
146
+ fontSize: 9,
147
+ }}>
148
+ {ann ? '⚠' : ''}
149
+ </td>
150
+
151
+ {/* Kod */}
152
+ <td style={{
153
+ padding: '0 16px',
154
+ color: '#CBD5E1',
155
+ whiteSpace: 'pre',
156
+ verticalAlign: 'top',
157
+ }}>
158
+ <SyntaxTinted code={line}/>
159
+ </td>
160
+
161
+ {/* Tooltip poruka (prikazuje se desno ako postoji anotacija) */}
162
+ {ann && (
163
+ <td style={{
164
+ padding: '0 12px',
165
+ fontSize: 10,
166
+ color: isRed ? '#EF4444' : '#F59E0B',
167
+ background: isRed ? 'rgba(239,68,68,0.08)' : 'rgba(245,158,11,0.08)',
168
+ whiteSpace: 'nowrap',
169
+ verticalAlign: 'top',
170
+ maxWidth: 280,
171
+ overflow: 'hidden',
172
+ textOverflow: 'ellipsis',
173
+ paddingTop: '2px',
174
+ fontStyle: 'italic',
175
+ }}>
176
+ {ann.note}
177
+ </td>
178
+ )}
179
+ </tr>
180
+ )
181
+ })}
182
+ </tbody>
183
+ </table>
184
  </div>
185
+ ) : (
186
+ // Edit mode — textarea s brojevima linija u sync
187
+ <div style={{ display: 'flex', height, overflow: 'hidden' }}>
188
+ {/* Brojevi linija za edit mode — sinkronizirani scrollom */}
189
+ <div style={{
190
+ padding: '12px 12px 12px 16px',
191
+ background: 'rgba(10,15,28,0.4)',
192
+ fontFamily: 'JetBrains Mono, monospace',
193
+ fontSize: 12,
194
+ lineHeight: 1.7,
195
+ color: '#475569',
196
+ textAlign: 'right',
197
+ userSelect: 'none',
198
+ borderRight: '1px solid rgba(148,163,184,0.08)',
199
+ minWidth: 44,
200
+ overflowY: 'hidden',
201
+ pointerEvents: 'none',
202
+ }}>
203
+ {lines.map((_, i) => <div key={i}>{i + 1}</div>)}
204
+ </div>
205
+ <textarea
206
+ value={code}
207
+ onChange={e => onChange && onChange(e.target.value)}
208
+ spellCheck="false"
209
+ placeholder="Paste your code here…"
210
+ onScroll={e => {
211
+ // Sinkroniziramo scroll brojeva linija s textarea
212
+ const prev = e.target.previousSibling
213
+ if (prev) prev.scrollTop = e.target.scrollTop
214
+ }}
215
+ style={{
216
+ flex: 1,
217
+ border: 'none',
218
+ outline: 'none',
219
+ resize: 'none',
220
+ background: 'transparent',
221
+ color: '#CBD5E1',
222
+ fontFamily: 'JetBrains Mono, monospace',
223
+ fontSize: 12,
224
+ lineHeight: 1.7,
225
+ padding: '12px 16px',
226
+ overflowY: 'auto',
227
+ }}
228
+ />
229
+ </div>
230
+ )}
231
  </div>
232
  )
233
  }
frontend/src/components/Dropzone.jsx CHANGED
@@ -27,7 +27,7 @@ export default function Dropzone({ files = [], onUpload }) {
27
  {files.length > 0 ? `${files.length} files ready to analyze` : 'Drop student files here or click to upload'}
28
  </div>
29
  <div style={{ fontSize: 13, color: '#64748B' }}>
30
- Accepts <span style={{ fontFamily: 'JetBrains Mono, monospace', color: '#94A3B8' }}>.py .js .java .cpp .ts .go .rs</span> · max 200 files
31
  </div>
32
  {files.length > 0 && (
33
  <div style={{ marginTop: 20, display: 'flex', justifyContent: 'center', gap: 6, flexWrap: 'wrap', maxWidth: 600, marginLeft: 'auto', marginRight: 'auto' }}>
 
27
  {files.length > 0 ? `${files.length} files ready to analyze` : 'Drop student files here or click to upload'}
28
  </div>
29
  <div style={{ fontSize: 13, color: '#64748B' }}>
30
+ Accepts <span style={{ fontFamily: 'JetBrains Mono, monospace', color: '#94A3B8' }}>.py .js .java .cpp .ts .go .rs .c .h</span>
31
  </div>
32
  {files.length > 0 && (
33
  <div style={{ marginTop: 20, display: 'flex', justifyContent: 'center', gap: 6, flexWrap: 'wrap', maxWidth: 600, marginLeft: 'auto', marginRight: 'auto' }}>
frontend/src/components/Dropzone2.jsx ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react'
2
+ import { Icon } from './primitives'
3
+
4
+ export default function Dropzone({ files = [], onUpload }) {
5
+ const [dragOver, setDragOver] = useState(false)
6
+ return (
7
+ <div
8
+ onDragOver={e => { e.preventDefault(); setDragOver(true) }}
9
+ onDragLeave={() => setDragOver(false)}
10
+ onDrop={e => { e.preventDefault(); setDragOver(false); onUpload && onUpload(e.dataTransfer.files) }}
11
+ onClick={() => { const i = document.createElement('input'); i.type = 'file'; i.multiple = true; i.accept = '.py,.js,.java,.cpp,.ts,.go,.rs,.rb,.c,.h'; i.onchange = e => onUpload && onUpload(e.target.files); i.click() }}
12
+ style={{
13
+ border: `1.5px dashed ${dragOver ? 'rgba(0,212,255,0.6)' : 'rgba(148,163,184,0.25)'}`,
14
+ borderRadius: 12, padding: '48px 24px', textAlign: 'center',
15
+ background: dragOver ? 'rgba(0,212,255,0.04)' : 'rgba(17,24,39,0.5)',
16
+ cursor: 'pointer', transition: 'all .12s cubic-bezier(0.22,1,0.36,1)',
17
+ backdropFilter: 'blur(20px)',
18
+ }}>
19
+ <div style={{
20
+ width: 56, height: 56, margin: '0 auto 18px', borderRadius: 12,
21
+ background: 'rgba(0,212,255,0.10)', border: '1px solid rgba(0,212,255,0.25)',
22
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
23
+ }}>
24
+ <Icon name="upload" size={24} color="#00D4FF"/>
25
+ </div>
26
+ <div style={{ fontSize: 18, fontWeight: 600, color: '#F8FAFC', marginBottom: 6 }}>
27
+ {files.length > 0 ? `${files.length} files ready to analyze` : 'Drop student files here or click to upload'}
28
+ </div>
29
+ <div style={{ fontSize: 13, color: '#64748B' }}>
30
+ Accepts <span style={{ fontFamily: 'JetBrains Mono, monospace', color: '#94A3B8' }}>.py .js .java .cpp .ts .go .rs</span> · max 200 files
31
+ </div>
32
+ {files.length > 0 && (
33
+ <div style={{ marginTop: 20, display: 'flex', justifyContent: 'center', gap: 6, flexWrap: 'wrap', maxWidth: 600, marginLeft: 'auto', marginRight: 'auto' }}>
34
+ {files.slice(0, 10).map((f, i) => (
35
+ <span key={i} style={{
36
+ fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
37
+ padding: '4px 10px', background: 'rgba(0,212,255,0.08)',
38
+ border: '1px solid rgba(0,212,255,0.20)', borderRadius: 6, color: '#00D4FF',
39
+ }}>{f.name || f}</span>
40
+ ))}
41
+ {files.length > 10 && <span style={{ fontSize: 11, color: '#64748B', alignSelf: 'center' }}>+{files.length - 10} more</span>}
42
+ </div>
43
+ )}
44
+ </div>
45
+ )
46
+ }
frontend/src/components/Heatmap.jsx CHANGED
@@ -1,7 +1,5 @@
1
  import { useState } from 'react'
2
 
3
- // Pretvara vrijednost 0-100 u boju:
4
- // tamno plava (0%) → cyan (50%) → amber (75%) → crvena (100%)
5
  function colorFor(v) {
6
  if (v == null) return '#0F1729'
7
  if (v < 30) {
@@ -20,123 +18,85 @@ function colorFor(v) {
20
  return `rgb(${Math.round(245 + t * (239 - 245))}, ${Math.round(158 + t * (68 - 158))}, ${Math.round(11 + t * (68 - 11))})`
21
  }
22
 
23
- export default function Heatmap({ data, ids }) {
24
- const [tip, setTip] = useState(null)
 
25
 
26
  if (!data || !ids || ids.length === 0) {
27
- return (
28
- <div style={{ padding: 40, textAlign: 'center', color: '#64748B', fontSize: 14 }}>
29
- No similarity data available.
30
- </div>
31
- )
32
  }
33
 
34
  const n = ids.length
35
-
36
- // Veličina ćelije: veća za manji broj fajlova, manja za veći broj
37
- // Min 20px, max 80px — tako da uvijek bude vidljivo
38
  const cellSize = Math.max(20, Math.min(80, Math.floor(480 / n)))
39
  const labelW = 72
40
- const showPct = cellSize >= 36 // prikaži postotak u ćeliji ako ima mjesta
 
 
 
 
 
 
 
 
 
41
 
42
  return (
43
  <div style={{ position: 'relative' }}>
44
-
45
- {/* Upozorenje za mali broj fajlova */}
46
  {n < 3 && (
47
- <div style={{
48
- marginBottom: 16, padding: '10px 14px',
49
- background: 'rgba(245,158,11,0.08)', border: '1px solid rgba(245,158,11,0.25)',
50
- borderRadius: 8, fontSize: 12, color: '#F59E0B',
51
- }}>
52
- Heatmap je najkorisniji s 3 ili više datoteka. Trenutno prikazuje {n} datoteke.
53
  </div>
54
  )}
55
 
56
- <div style={{ overflowX: 'auto', overflowY: 'auto' }}>
57
- {/* Gornji labeli (kosi tekst) */}
58
  <div style={{ display: 'flex', marginLeft: labelW }}>
59
  {ids.map((id, i) => (
60
- <div key={i} style={{
61
- width: cellSize, flexShrink: 0,
62
- height: labelW,
63
- display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
64
- paddingBottom: 8,
65
- }}>
66
- <span style={{
67
- fontFamily: 'JetBrains Mono, monospace',
68
- fontSize: Math.max(8, Math.min(11, cellSize * 0.35)),
69
- color: '#94A3B8',
70
- transform: 'rotate(-45deg)',
71
- transformOrigin: 'bottom center',
72
- whiteSpace: 'nowrap',
73
- display: 'block',
74
- }}>{id}</span>
75
  </div>
76
  ))}
77
  </div>
78
 
79
- {/* Grid s lijeve strane labelima */}
80
  <div style={{ display: 'flex' }}>
81
-
82
  {/* Lijevi labeli */}
83
  <div style={{ display: 'flex', flexDirection: 'column', width: labelW, flexShrink: 0 }}>
84
  {ids.map((id, i) => (
85
- <div key={i} style={{
86
- height: cellSize, flexShrink: 0,
87
- display: 'flex', alignItems: 'center', justifyContent: 'flex-end',
88
- paddingRight: 10,
89
- fontFamily: 'JetBrains Mono, monospace',
90
- fontSize: Math.max(8, Math.min(11, cellSize * 0.35)),
91
- color: '#94A3B8',
92
- whiteSpace: 'nowrap',
93
- }}>{id}</div>
94
  ))}
95
  </div>
96
 
97
- {/* Matrica ćelija */}
98
- <div style={{
99
- display: 'flex', flexDirection: 'column',
100
- border: '1px solid rgba(148,163,184,0.15)',
101
- borderRadius: 6, overflow: 'hidden',
102
- }}>
103
  {data.map((row, i) => (
104
  <div key={i} style={{ display: 'flex' }}>
105
  {row.map((v, j) => {
106
- // Backend vraća 0.0–1.0, colorFor treba 0–100
107
  const pct = Math.round(v * 100)
108
  const isDiag = i === j
109
- const bg = isDiag ? '#1F2937' : colorFor(pct)
110
-
111
- // Boja teksta unutar ćelije — tamna za svijetle boje, bijela za tamne
112
  const textColor = pct > 45 && pct < 75 ? '#0A0F1C' : '#FFFFFF'
113
 
114
  return (
115
  <div key={j}
116
  onMouseEnter={e => setTip({ x: e.clientX, y: e.clientY, a: ids[i], b: ids[j], pct, isDiag })}
117
- onMouseMove={e => setTip({ x: e.clientX, y: e.clientY, a: ids[i], b: ids[j], pct, isDiag })}
118
  onMouseLeave={() => setTip(null)}
 
119
  style={{
120
  width: cellSize, height: cellSize, flexShrink: 0,
121
  background: bg,
122
- border: '1px solid rgba(10,15,28,0.3)',
123
  cursor: isDiag ? 'default' : 'pointer',
124
  display: 'flex', alignItems: 'center', justifyContent: 'center',
 
 
125
  transition: 'filter .1s',
126
- position: 'relative',
127
  }}>
128
- {/* Postotak unutar ćelije (samo ako ima mjesta i nije dijagonala) */}
129
  {showPct && !isDiag && (
130
- <span style={{
131
- fontFamily: 'JetBrains Mono, monospace',
132
- fontSize: Math.max(8, cellSize * 0.28),
133
- fontWeight: 700,
134
- color: textColor,
135
- userSelect: 'none',
136
- lineHeight: 1,
137
- }}>{pct}%</span>
138
  )}
139
- {/* Dijagonala — prikaži "—" */}
140
  {isDiag && showPct && (
141
  <span style={{ fontSize: cellSize * 0.3, color: '#475569' }}>—</span>
142
  )}
@@ -152,10 +112,7 @@ export default function Heatmap({ data, ids }) {
152
  {/* Legenda */}
153
  <div style={{ marginTop: 20, display: 'flex', alignItems: 'center', gap: 12 }}>
154
  <span style={{ fontSize: 11, color: '#94A3B8', letterSpacing: '0.04em', textTransform: 'uppercase' }}>Similarity</span>
155
- <div style={{
156
- display: 'flex', height: 10, width: 200, borderRadius: 4,
157
- overflow: 'hidden', border: '1px solid rgba(148,163,184,0.10)',
158
- }}>
159
  {Array.from({ length: 40 }).map((_, i) => (
160
  <div key={i} style={{ flex: 1, background: colorFor(i * 2.5 + 1) }}/>
161
  ))}
@@ -166,33 +123,22 @@ export default function Heatmap({ data, ids }) {
166
  <span style={{ color: '#F59E0B' }}>75%</span>
167
  <span style={{ color: '#EF4444' }}>100%</span>
168
  </div>
 
 
 
 
 
169
  </div>
170
 
171
  {/* Tooltip */}
172
  {tip && !tip.isDiag && (
173
- <div style={{
174
- position: 'fixed', left: tip.x + 14, top: tip.y + 14,
175
- background: 'rgba(10,15,28,0.97)', border: '1px solid rgba(0,212,255,0.4)',
176
- padding: '10px 14px', borderRadius: 8, zIndex: 200,
177
- fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: '#F8FAFC',
178
- boxShadow: '0 8px 24px rgba(0,0,0,0.5)', pointerEvents: 'none',
179
- }}>
180
- <div style={{ color: '#94A3B8', fontSize: 10, marginBottom: 4 }}>
181
- {tip.a} ↔ {tip.b}
182
- </div>
183
- <div style={{
184
- fontSize: 20, fontWeight: 700,
185
- color: colorFor(tip.pct),
186
- lineHeight: 1,
187
- }}>
188
- {tip.pct}%
189
- </div>
190
  <div style={{ fontSize: 10, color: '#64748B', marginTop: 3 }}>
191
- {tip.pct >= 80 ? 'Very high similarity' :
192
- tip.pct >= 60 ? 'High similarity' :
193
- tip.pct >= 40 ? 'Moderate similarity' :
194
- 'Low similarity'}
195
  </div>
 
196
  </div>
197
  )}
198
  </div>
 
1
  import { useState } from 'react'
2
 
 
 
3
  function colorFor(v) {
4
  if (v == null) return '#0F1729'
5
  if (v < 30) {
 
18
  return `rgb(${Math.round(245 + t * (239 - 245))}, ${Math.round(158 + t * (68 - 158))}, ${Math.round(11 + t * (68 - 11))})`
19
  }
20
 
21
+ export default function Heatmap({ data, ids, onSelectPair }) {
22
+ const [tip, setTip] = useState(null)
23
+ const [selected, setSelected] = useState(null) // { i, j }
24
 
25
  if (!data || !ids || ids.length === 0) {
26
+ return <div style={{ padding: 40, textAlign: 'center', color: '#64748B', fontSize: 14 }}>No data.</div>
 
 
 
 
27
  }
28
 
29
  const n = ids.length
 
 
 
30
  const cellSize = Math.max(20, Math.min(80, Math.floor(480 / n)))
31
  const labelW = 72
32
+ const showPct = cellSize >= 36
33
+
34
+ const handleClick = (i, j) => {
35
+ if (i === j) return
36
+ const newSel = selected?.i === i && selected?.j === j ? null : { i, j }
37
+ setSelected(newSel)
38
+ if (onSelectPair) {
39
+ onSelectPair(newSel ? { i, j, idA: ids[i], idB: ids[j], similarity: Math.round(data[i][j] * 100) } : null)
40
+ }
41
+ }
42
 
43
  return (
44
  <div style={{ position: 'relative' }}>
 
 
45
  {n < 3 && (
46
+ <div style={{ marginBottom: 16, padding: '10px 14px', background: 'rgba(245,158,11,0.08)', border: '1px solid rgba(245,158,11,0.25)', borderRadius: 8, fontSize: 12, color: '#F59E0B' }}>
47
+ Heatmap je najkorisniji s 3 ili više datoteka.
 
 
 
 
48
  </div>
49
  )}
50
 
51
+ <div style={{ overflowX: 'auto' }}>
52
+ {/* Gornji labeli */}
53
  <div style={{ display: 'flex', marginLeft: labelW }}>
54
  {ids.map((id, i) => (
55
+ <div key={i} style={{ width: cellSize, flexShrink: 0, height: labelW, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: 8 }}>
56
+ <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: Math.max(8, Math.min(11, cellSize * 0.35)), color: '#64748B', transform: 'rotate(-45deg)', transformOrigin: 'bottom center', whiteSpace: 'nowrap', display: 'block' }}>{id}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  </div>
58
  ))}
59
  </div>
60
 
61
+ {/* Grid */}
62
  <div style={{ display: 'flex' }}>
 
63
  {/* Lijevi labeli */}
64
  <div style={{ display: 'flex', flexDirection: 'column', width: labelW, flexShrink: 0 }}>
65
  {ids.map((id, i) => (
66
+ <div key={i} style={{ height: cellSize, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: 10, fontFamily: 'JetBrains Mono, monospace', fontSize: Math.max(8, Math.min(11, cellSize * 0.35)), color: '#64748B', whiteSpace: 'nowrap' }}>{id}</div>
 
 
 
 
 
 
 
 
67
  ))}
68
  </div>
69
 
70
+ {/* Ćelije */}
71
+ <div style={{ display: 'flex', flexDirection: 'column', border: '1px solid rgba(148,163,184,0.15)', borderRadius: 6, overflow: 'hidden' }}>
 
 
 
 
72
  {data.map((row, i) => (
73
  <div key={i} style={{ display: 'flex' }}>
74
  {row.map((v, j) => {
 
75
  const pct = Math.round(v * 100)
76
  const isDiag = i === j
77
+ const isSel = selected?.i === i && selected?.j === j
78
+ const bg = isDiag ? '#1F2937' : colorFor(pct)
 
79
  const textColor = pct > 45 && pct < 75 ? '#0A0F1C' : '#FFFFFF'
80
 
81
  return (
82
  <div key={j}
83
  onMouseEnter={e => setTip({ x: e.clientX, y: e.clientY, a: ids[i], b: ids[j], pct, isDiag })}
84
+ onMouseMove={e => setTip({ x: e.clientX, y: e.clientY, a: ids[i], b: ids[j], pct, isDiag })}
85
  onMouseLeave={() => setTip(null)}
86
+ onClick={() => handleClick(i, j)}
87
  style={{
88
  width: cellSize, height: cellSize, flexShrink: 0,
89
  background: bg,
90
+ border: isSel ? '2px solid #00D4FF' : '1px solid rgba(10,15,28,0.3)',
91
  cursor: isDiag ? 'default' : 'pointer',
92
  display: 'flex', alignItems: 'center', justifyContent: 'center',
93
+ boxSizing: 'border-box',
94
+ outline: isSel ? '2px solid rgba(0,212,255,0.4)' : 'none',
95
  transition: 'filter .1s',
 
96
  }}>
 
97
  {showPct && !isDiag && (
98
+ <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: Math.max(8, cellSize * 0.28), fontWeight: 700, color: textColor, userSelect: 'none', lineHeight: 1 }}>{pct}%</span>
 
 
 
 
 
 
 
99
  )}
 
100
  {isDiag && showPct && (
101
  <span style={{ fontSize: cellSize * 0.3, color: '#475569' }}>—</span>
102
  )}
 
112
  {/* Legenda */}
113
  <div style={{ marginTop: 20, display: 'flex', alignItems: 'center', gap: 12 }}>
114
  <span style={{ fontSize: 11, color: '#94A3B8', letterSpacing: '0.04em', textTransform: 'uppercase' }}>Similarity</span>
115
+ <div style={{ display: 'flex', height: 10, width: 200, borderRadius: 4, overflow: 'hidden', border: '1px solid rgba(148,163,184,0.10)' }}>
 
 
 
116
  {Array.from({ length: 40 }).map((_, i) => (
117
  <div key={i} style={{ flex: 1, background: colorFor(i * 2.5 + 1) }}/>
118
  ))}
 
123
  <span style={{ color: '#F59E0B' }}>75%</span>
124
  <span style={{ color: '#EF4444' }}>100%</span>
125
  </div>
126
+ {selected && (
127
+ <span style={{ marginLeft: 16, fontSize: 11, color: '#00D4FF' }}>
128
+ Klikni ponovo za deselect · skrolaj dolje za usporedbu
129
+ </span>
130
+ )}
131
  </div>
132
 
133
  {/* Tooltip */}
134
  {tip && !tip.isDiag && (
135
+ <div style={{ position: 'fixed', left: tip.x + 14, top: tip.y + 14, background: 'rgba(10,15,28,0.97)', border: '1px solid rgba(0,212,255,0.4)', padding: '10px 14px', borderRadius: 8, zIndex: 200, fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: '#F8FAFC', boxShadow: '0 8px 24px rgba(0,0,0,0.5)', pointerEvents: 'none' }}>
136
+ <div style={{ color: '#94A3B8', fontSize: 10, marginBottom: 4 }}>{tip.a} ↔ {tip.b}</div>
137
+ <div style={{ fontSize: 20, fontWeight: 700, color: colorFor(tip.pct), lineHeight: 1 }}>{tip.pct}%</div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  <div style={{ fontSize: 10, color: '#64748B', marginTop: 3 }}>
139
+ {tip.pct >= 80 ? 'Very high similarity' : tip.pct >= 60 ? 'High similarity' : tip.pct >= 40 ? 'Moderate' : 'Low similarity'}
 
 
 
140
  </div>
141
+ <div style={{ fontSize: 9, color: '#475569', marginTop: 4 }}>Klikni za usporedbu koda</div>
142
  </div>
143
  )}
144
  </div>
frontend/src/components/Navbar.jsx CHANGED
@@ -1,5 +1,4 @@
1
  import { useState } from 'react'
2
- import { Button } from './primitives'
3
 
4
  function NavLink({ active, onClick, children }) {
5
  const [hover, setHover] = useState(false)
@@ -37,6 +36,7 @@ export default function Navbar({ active, onNavigate }) {
37
  padding: '0 80px',
38
  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
39
  }}>
 
40
  <div style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}
41
  onClick={() => onNavigate('analyze')}>
42
  <svg width="28" height="28" viewBox="0 0 32 32" fill="none">
@@ -47,6 +47,8 @@ export default function Navbar({ active, onNavigate }) {
47
  Code<span style={{ color: '#00D4FF' }}>Sentinel</span>
48
  </div>
49
  </div>
 
 
50
  <nav style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
51
  {tabs.map(t => (
52
  <NavLink key={t.id} active={active === t.id} onClick={() => onNavigate(t.id)}>
@@ -54,14 +56,9 @@ export default function Navbar({ active, onNavigate }) {
54
  </NavLink>
55
  ))}
56
  </nav>
57
- <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
58
- <div style={{
59
- width: 32, height: 32, borderRadius: '50%',
60
- background: 'linear-gradient(135deg, #00D4FF, #06B6D4)',
61
- display: 'flex', alignItems: 'center', justifyContent: 'center',
62
- color: '#0A0F1C', fontWeight: 700, fontSize: 12,
63
- }}>CS</div>
64
- </div>
65
  </div>
66
  </header>
67
  )
 
1
  import { useState } from 'react'
 
2
 
3
  function NavLink({ active, onClick, children }) {
4
  const [hover, setHover] = useState(false)
 
36
  padding: '0 80px',
37
  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
38
  }}>
39
+ {/* Logo */}
40
  <div style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}
41
  onClick={() => onNavigate('analyze')}>
42
  <svg width="28" height="28" viewBox="0 0 32 32" fill="none">
 
47
  Code<span style={{ color: '#00D4FF' }}>Sentinel</span>
48
  </div>
49
  </div>
50
+
51
+ {/* Nav links */}
52
  <nav style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
53
  {tabs.map(t => (
54
  <NavLink key={t.id} active={active === t.id} onClick={() => onNavigate(t.id)}>
 
56
  </NavLink>
57
  ))}
58
  </nav>
59
+
60
+ {/* Desna strana — prazna, CS avatar uklonjen */}
61
+ <div style={{ width: 44 }}/>
 
 
 
 
 
62
  </div>
63
  </header>
64
  )
frontend/src/screens/BatchScreen.jsx CHANGED
@@ -1,40 +1,58 @@
1
  import { useState } from 'react'
2
- import { Button, Card, Label, Icon, Spinner, Input } from '../components/primitives'
3
  import Dropzone from '../components/Dropzone'
4
  import ResultsTable from '../components/ResultsTable'
5
  import { StatCard } from '../components/FeatureCard'
6
  import { analyzeBatch } from '../api/client'
7
 
8
  export default function BatchScreen({ onOpenRow }) {
9
- const [files, setFiles] = useState([])
10
- const [results, setResults] = useState([])
11
- const [summary, setSummary] = useState(null)
12
- const [loading, setLoading] = useState(false)
13
- const [progress, setProgress] = useState(0)
14
- const [error, setError] = useState(null)
15
- const [search, setSearch] = useState('')
 
16
 
17
  const handleFiles = (fileList) => {
18
  const arr = Array.from(fileList)
19
- setFiles(arr); setResults([]); setSummary(null); setError(null)
20
  }
21
 
22
  const runBatch = async () => {
23
  if (!files.length) return
24
- setLoading(true); setError(null); setProgress(0)
25
 
 
26
  const submissions = await Promise.all(files.map(async (f) => ({
27
- id: f.name.replace(/\.[^.]+$/, ''),
28
  file: f.name,
29
  code: await f.text(),
30
  })))
31
 
32
  try {
33
- const data = await analyzeBatch(submissions)
34
- const withFile = data.results.map((r, i) => ({ ...r, file: submissions[i]?.file || r.id }))
35
- setResults(withFile)
36
- setSummary(data.summary)
37
- setProgress(100)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  } catch (e) {
39
  setError(e.message)
40
  } finally {
@@ -44,13 +62,35 @@ export default function BatchScreen({ onOpenRow }) {
44
 
45
  const exportCSV = () => {
46
  if (!results.length) return
47
- const headers = ['id', 'file', 'detected_language', 'ai_probability', 'verdict']
48
- const rows = results.map(r => headers.map(h => {
49
- const v = r[h]
50
- return typeof v === 'number' ? (h === 'ai_probability' ? Math.round(v * 100) + '%' : v) : (v || '')
 
 
 
 
 
 
 
 
 
 
 
51
  }))
52
- const csv = [headers, ...rows].map(r => r.join(',')).join('\n')
53
- const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(new Blob([csv])), download: 'codesentinel_results.csv' })
 
 
 
 
 
 
 
 
 
 
 
54
  a.click()
55
  }
56
 
@@ -58,6 +98,8 @@ export default function BatchScreen({ onOpenRow }) {
58
  !search || r.id?.toLowerCase().includes(search.toLowerCase()) || r.file?.toLowerCase().includes(search.toLowerCase())
59
  )
60
 
 
 
61
  return (
62
  <div style={{ padding: '40px 80px 80px', maxWidth: 1280, margin: '0 auto' }}>
63
  <div style={{ marginBottom: 32 }}>
@@ -66,31 +108,54 @@ export default function BatchScreen({ onOpenRow }) {
66
  Class overview
67
  </h1>
68
  <p style={{ fontSize: 15, color: '#94A3B8', marginTop: 12, marginBottom: 0, maxWidth: 600 }}>
69
- Drop a folder of submissions, then sort by AI probability to triage your grading queue.
70
  </p>
71
  </div>
72
 
73
- {/* Upload zone */}
74
- {!results.length && (
75
  <div style={{ marginBottom: 24 }}>
76
  <Dropzone files={files} onUpload={handleFiles}/>
77
  {files.length > 0 && (
78
  <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
79
- <Button variant="primary" icon="play" onClick={runBatch} disabled={loading}>
80
- {loading ? 'Analyzing…' : `Analyze ${files.length} file${files.length !== 1 ? 's' : ''}`}
81
  </Button>
82
  </div>
83
  )}
84
  </div>
85
  )}
86
 
 
87
  {loading && (
88
- <Card style={{ padding: 40, textAlign: 'center', marginBottom: 24 }}>
89
- <Spinner size={40} style={{ margin: '0 auto 16px' }}/>
90
- <div style={{ fontSize: 14, color: '#94A3B8' }}>Analyzing {files.length} files…</div>
91
- <div style={{ width: 240, height: 4, background: 'rgba(148,163,184,0.10)', borderRadius: 2, margin: '16px auto 0', overflow: 'hidden' }}>
92
- <div style={{ width: '60%', height: '100%', background: '#00D4FF', animation: 'pulse 1.2s ease-in-out infinite' }}/>
 
 
 
 
 
 
93
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  </Card>
95
  )}
96
 
@@ -103,30 +168,46 @@ export default function BatchScreen({ onOpenRow }) {
103
  </Card>
104
  )}
105
 
106
- {summary && (
 
107
  <>
108
- {/* Stat cards */}
109
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
110
- <StatCard label="Total submissions" value={summary.total} delta="files analyzed" icon="users" iconColor="#00D4FF"/>
111
- <StatCard label="High risk" value={summary.high_risk} delta="≥ 70% AI probability" deltaColor="#EF4444" icon="alert" iconColor="#EF4444"/>
112
- <StatCard label="Medium risk" value={summary.medium_risk} delta="40–69% probability" deltaColor="#F59E0B" icon="alert" iconColor="#F59E0B"/>
113
- <StatCard label="Low risk" value={summary.low_risk} delta="< 40% probability" deltaColor="#10B981" icon="check" iconColor="#10B981"/>
114
- </div>
 
 
115
 
116
- {/* Success bar */}
117
- <div style={{ marginBottom: 24, padding: '14px 18px', background: 'rgba(16,185,129,0.06)', border: '1px solid rgba(16,185,129,0.20)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
118
  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
119
- <Icon name="check" size={16} color="#10B981"/>
120
- <span style={{ fontSize: 13, color: '#CBD5E1' }}>Analyzed <strong style={{ color: '#F8FAFC' }}>{summary.total} files</strong> — avg. AI probability: <strong style={{ color: '#F8FAFC' }}>{Math.round(summary.avg_ai_probability * 100)}%</strong></span>
 
 
 
 
 
121
  </div>
122
  <div style={{ display: 'flex', gap: 8 }}>
123
- <Button variant="secondary" size="sm" icon="upload" onClick={() => { setResults([]); setSummary(null); setFiles([]) }}>Re-upload</Button>
124
- <Button variant="primary" size="sm" icon="download" onClick={exportCSV}>Export CSV</Button>
 
 
 
 
 
 
 
 
125
  </div>
126
  </div>
127
 
128
- {/* Toolbar */}
129
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
130
  <Input icon="search" placeholder="Search by student ID or filename…" value={search} onChange={setSearch} style={{ width: 320 }}/>
131
  </div>
132
 
 
1
  import { useState } from 'react'
2
+ import { Button, Card, Label, Icon, Input } from '../components/primitives'
3
  import Dropzone from '../components/Dropzone'
4
  import ResultsTable from '../components/ResultsTable'
5
  import { StatCard } from '../components/FeatureCard'
6
  import { analyzeBatch } from '../api/client'
7
 
8
  export default function BatchScreen({ onOpenRow }) {
9
+ const [files, setFiles] = useState([])
10
+ const [results, setResults] = useState([])
11
+ const [summary, setSummary] = useState(null)
12
+ const [loading, setLoading] = useState(false)
13
+ const [progress, setProgress] = useState(0) // 0-100
14
+ const [done, setDone] = useState(0) // koliko fajlova završilo
15
+ const [error, setError] = useState(null)
16
+ const [search, setSearch] = useState('')
17
 
18
  const handleFiles = (fileList) => {
19
  const arr = Array.from(fileList)
20
+ setFiles(arr); setResults([]); setSummary(null); setError(null); setProgress(0); setDone(0)
21
  }
22
 
23
  const runBatch = async () => {
24
  if (!files.length) return
25
+ setLoading(true); setError(null); setResults([]); setSummary(null); setProgress(0); setDone(0)
26
 
27
+ // Učitamo sve fajlove unaprijed da znamo kod za svaki
28
  const submissions = await Promise.all(files.map(async (f) => ({
29
+ id: f.name.replace(/\.[^.]+$/, ''),
30
  file: f.name,
31
  code: await f.text(),
32
  })))
33
 
34
  try {
35
+ // Streaming — onResult se zove za svaki fajl čim stigne s backenda
36
+ const finalSummary = await analyzeBatch(
37
+ submissions,
38
+
39
+ // Callback za svaki gotov rezultat — odmah ga dodajemo u tablicu
40
+ (result, index, total) => {
41
+ const sub = submissions[index - 1]
42
+ const enriched = {
43
+ ...result,
44
+ file: sub?.file || result.id,
45
+ code: sub?.code || '',
46
+ }
47
+ setResults(prev => [...prev, enriched])
48
+ setDone(index)
49
+ },
50
+
51
+ // Callback za napredak (0-100%)
52
+ (pct) => setProgress(pct),
53
+ )
54
+
55
+ setSummary(finalSummary)
56
  } catch (e) {
57
  setError(e.message)
58
  } finally {
 
62
 
63
  const exportCSV = () => {
64
  if (!results.length) return
65
+
66
+ const headers = ['ID', 'Datoteka', 'Jezik', 'AI vjerojatnost (%)', 'Zakljucak']
67
+ const keys = ['id', 'file', 'detected_language', 'ai_probability', 'verdict']
68
+
69
+ const escapeCell = (val) => {
70
+ const s = String(val ?? '')
71
+ if (s.includes(';') || s.includes('"') || s.includes('\n')) {
72
+ return '"' + s.replace(/"/g, '""') + '"'
73
+ }
74
+ return s
75
+ }
76
+
77
+ const rows = results.map(r => keys.map(h => {
78
+ if (h === 'ai_probability') return escapeCell(Math.round((r[h] || 0) * 100) + '%')
79
+ return escapeCell(r[h] || '')
80
  }))
81
+
82
+ const sep = ';'
83
+ const csvContent = [
84
+ headers.map(escapeCell).join(sep),
85
+ ...rows.map(r => r.join(sep)),
86
+ ].join('\r\n')
87
+
88
+ const BOM = '\uFEFF'
89
+ const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
90
+ const a = Object.assign(document.createElement('a'), {
91
+ href: URL.createObjectURL(blob),
92
+ download: 'codesentinel_rezultati.csv',
93
+ })
94
  a.click()
95
  }
96
 
 
98
  !search || r.id?.toLowerCase().includes(search.toLowerCase()) || r.file?.toLowerCase().includes(search.toLowerCase())
99
  )
100
 
101
+ const total = files.length
102
+
103
  return (
104
  <div style={{ padding: '40px 80px 80px', maxWidth: 1280, margin: '0 auto' }}>
105
  <div style={{ marginBottom: 32 }}>
 
108
  Class overview
109
  </h1>
110
  <p style={{ fontSize: 15, color: '#94A3B8', marginTop: 12, marginBottom: 0, maxWidth: 600 }}>
111
+ Rezultati se prikazuju u realnom vremenu čim svaki fajl bude analiziran.
112
  </p>
113
  </div>
114
 
115
+ {/* Upload zona — prikazuje se samo na početku */}
116
+ {!loading && !results.length && !summary && (
117
  <div style={{ marginBottom: 24 }}>
118
  <Dropzone files={files} onUpload={handleFiles}/>
119
  {files.length > 0 && (
120
  <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
121
+ <Button variant="primary" icon="play" onClick={runBatch}>
122
+ Analyze {files.length} submission{files.length !== 1 ? 's' : ''}
123
  </Button>
124
  </div>
125
  )}
126
  </div>
127
  )}
128
 
129
+ {/* Progress bar — prikazuje se za vrijeme analize */}
130
  {loading && (
131
+ <Card style={{ padding: 24, marginBottom: 24 }}>
132
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
133
+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
134
+ <div style={{ width: 10, height: 10, borderRadius: '50%', background: '#00D4FF', boxShadow: '0 0 8px #00D4FF', animation: 'pulse 1s ease infinite' }}/>
135
+ <span style={{ fontSize: 14, color: '#CBD5E1' }}>
136
+ Analyzing… <strong style={{ color: '#F8FAFC', fontFamily: 'JetBrains Mono, monospace' }}>{done}</strong> / {total} files
137
+ </span>
138
+ </div>
139
+ <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 14, color: '#00D4FF', fontWeight: 700 }}>
140
+ {progress}%
141
+ </span>
142
  </div>
143
+ {/* Progress bar */}
144
+ <div style={{ height: 6, background: 'rgba(148,163,184,0.10)', borderRadius: 3, overflow: 'hidden' }}>
145
+ <div style={{
146
+ width: `${progress}%`, height: '100%',
147
+ background: 'linear-gradient(90deg, #00D4FF, #06B6D4)',
148
+ borderRadius: 3,
149
+ transition: 'width .3s cubic-bezier(0.22,1,0.36,1)',
150
+ boxShadow: '0 0 8px rgba(0,212,255,0.4)',
151
+ }}/>
152
+ </div>
153
+ {/* Tablica se popunjava ispod progress bara u realnom vremenu */}
154
+ {results.length > 0 && (
155
+ <div style={{ marginTop: 8, fontSize: 12, color: '#64748B' }}>
156
+ {results.length} result{results.length !== 1 ? 's' : ''} so far — scroll down to see them
157
+ </div>
158
+ )}
159
  </Card>
160
  )}
161
 
 
168
  </Card>
169
  )}
170
 
171
+ {/* Rezultati — prikazuju se čim prvi stignu, i rastu za vrijeme analize */}
172
+ {results.length > 0 && (
173
  <>
174
+ {/* Stat kartice — vidljive tek kad je sve gotovo */}
175
+ {summary && (
176
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
177
+ <StatCard label="Total submissions" value={summary.total} delta="files analyzed" icon="users" iconColor="#00D4FF"/>
178
+ <StatCard label="High risk" value={summary.high_risk} delta="≥ 70% AI probability" deltaColor="#EF4444" icon="alert" iconColor="#EF4444"/>
179
+ <StatCard label="Medium risk" value={summary.medium_risk} delta="40–69% probability" deltaColor="#F59E0B" icon="alert" iconColor="#F59E0B"/>
180
+ <StatCard label="Low risk" value={summary.low_risk} delta="< 40% probability" deltaColor="#10B981" icon="check" iconColor="#10B981"/>
181
+ </div>
182
+ )}
183
 
184
+ {/* Action bar */}
185
+ <div style={{ marginBottom: 16, padding: '12px 18px', background: summary ? 'rgba(16,185,129,0.06)' : 'rgba(0,212,255,0.04)', border: `1px solid ${summary ? 'rgba(16,185,129,0.20)' : 'rgba(0,212,255,0.15)'}`, borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
186
  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
187
+ <Icon name={summary ? 'check' : 'chart'} size={16} color={summary ? '#10B981' : '#00D4FF'}/>
188
+ <span style={{ fontSize: 13, color: '#CBD5E1' }}>
189
+ {summary
190
+ ? <><strong style={{ color: '#F8FAFC' }}>{summary.total} files</strong> analyzed — avg. AI probability: <strong style={{ color: '#F8FAFC' }}>{Math.round((summary.avg_ai_probability || 0) * 100)}%</ strong></>
191
+ : <><strong style={{ color: '#F8FAFC' }}>{results.length}</strong> of {total} analyzed…</>
192
+ }
193
+ </span>
194
  </div>
195
  <div style={{ display: 'flex', gap: 8 }}>
196
+ {summary && (
197
+ <>
198
+ <Button variant="secondary" size="sm" icon="upload" onClick={() => { setResults([]); setSummary(null); setFiles([]); setProgress(0); setDone(0) }}>
199
+ Re-upload
200
+ </Button>
201
+ <Button variant="primary" size="sm" icon="download" onClick={exportCSV}>
202
+ Export CSV
203
+ </Button>
204
+ </>
205
+ )}
206
  </div>
207
  </div>
208
 
209
+ {/* Search */}
210
+ <div style={{ marginBottom: 16 }}>
211
  <Input icon="search" placeholder="Search by student ID or filename…" value={search} onChange={setSearch} style={{ width: 320 }}/>
212
  </div>
213
 
frontend/src/screens/BatchScreen2.jsx ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react'
2
+ import { Button, Card, Label, Icon, Spinner, Input } from '../components/primitives'
3
+ import Dropzone from '../components/Dropzone'
4
+ import ResultsTable from '../components/ResultsTable'
5
+ import { StatCard } from '../components/FeatureCard'
6
+ import { analyzeBatch } from '../api/client'
7
+
8
+ export default function BatchScreen({ onOpenRow }) {
9
+ const [files, setFiles] = useState([])
10
+ const [results, setResults] = useState([])
11
+ const [summary, setSummary] = useState(null)
12
+ const [loading, setLoading] = useState(false)
13
+ const [progress, setProgress] = useState(0)
14
+ const [error, setError] = useState(null)
15
+ const [search, setSearch] = useState('')
16
+
17
+ const handleFiles = (fileList) => {
18
+ const arr = Array.from(fileList)
19
+ setFiles(arr); setResults([]); setSummary(null); setError(null)
20
+ }
21
+
22
+ const runBatch = async () => {
23
+ if (!files.length) return
24
+ setLoading(true); setError(null); setProgress(0)
25
+
26
+ const submissions = await Promise.all(files.map(async (f) => ({
27
+ id: f.name.replace(/\.[^.]+$/, ''),
28
+ file: f.name,
29
+ code: await f.text(),
30
+ })))
31
+
32
+ try {
33
+ const data = await analyzeBatch(submissions)
34
+
35
+ // Uz file naziv priložimo i originalni kod da ga DetailScreen može prikazati
36
+ const withFile = data.results.map((r, i) => ({
37
+ ...r,
38
+ file: submissions[i]?.file || r.id,
39
+ code: submissions[i]?.code || '', // ← ovo je bio problem, nedostajalo
40
+ }))
41
+
42
+ setResults(withFile)
43
+ setSummary(data.summary)
44
+ setProgress(100)
45
+ } catch (e) {
46
+ setError(e.message)
47
+ } finally {
48
+ setLoading(false)
49
+ }
50
+ }
51
+
52
+ const exportCSV = () => {
53
+ if (!results.length) return
54
+
55
+ const headers = ['ID', 'Datoteka', 'Jezik', 'AI vjerojatnost (%)', 'Zakljucak']
56
+ const keys = ['id', 'file', 'detected_language', 'ai_probability', 'verdict']
57
+
58
+ // Escapiranje polja — ako polje sadrži točku-zarez, navodnike ili novi red,
59
+ // omotamo ga navodnicima i udvostručimo unutarnje navodnike
60
+ const escapeCell = (val) => {
61
+ const s = String(val ?? '')
62
+ if (s.includes(';') || s.includes('"') || s.includes('\n')) {
63
+ return '"' + s.replace(/"/g, '""') + '"'
64
+ }
65
+ return s
66
+ }
67
+
68
+ const rows = results.map(r => keys.map(h => {
69
+ if (h === 'ai_probability') return escapeCell(Math.round((r[h] || 0) * 100) + '%')
70
+ return escapeCell(r[h] || '')
71
+ }))
72
+
73
+ // Točka-zarez (;) kao separator — Excel u europskim regijama koristi ; ne ,
74
+ // UTF-8 BOM (\ufeff) na početku — Excel tada ispravno čita čšćžđ i sl.
75
+ const sep = ';'
76
+ const csvContent = [
77
+ headers.map(escapeCell).join(sep),
78
+ ...rows.map(r => r.join(sep)),
79
+ ].join('\r\n')
80
+
81
+ const BOM = '\uFEFF'
82
+ const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
83
+ const a = Object.assign(document.createElement('a'), {
84
+ href: URL.createObjectURL(blob),
85
+ download: 'codesentinel_rezultati.csv',
86
+ })
87
+ a.click()
88
+ }
89
+
90
+ const filtered = results.filter(r =>
91
+ !search || r.id?.toLowerCase().includes(search.toLowerCase()) || r.file?.toLowerCase().includes(search.toLowerCase())
92
+ )
93
+
94
+ return (
95
+ <div style={{ padding: '40px 80px 80px', maxWidth: 1280, margin: '0 auto' }}>
96
+ <div style={{ marginBottom: 32 }}>
97
+ <Label style={{ marginBottom: 8 }}>Batch analysis</Label>
98
+ <h1 style={{ fontSize: 40, fontWeight: 700, letterSpacing: '-0.02em', color: '#F8FAFC', margin: 0, lineHeight: 1.1 }}>
99
+ Class overview
100
+ </h1>
101
+ <p style={{ fontSize: 15, color: '#94A3B8', marginTop: 12, marginBottom: 0, maxWidth: 600 }}>
102
+ Drop a folder of submissions, then sort by AI probability to triage your grading queue.
103
+ </p>
104
+ </div>
105
+
106
+ {/* Upload zone */}
107
+ {!results.length && (
108
+ <div style={{ marginBottom: 24 }}>
109
+ <Dropzone files={files} onUpload={handleFiles}/>
110
+ {files.length > 0 && (
111
+ <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
112
+ <Button variant="primary" icon="play" onClick={runBatch} disabled={loading}>
113
+ {loading ? 'Analyzing…' : `Analyze ${files.length} submission${files.length !== 1 ? 's' : ''}`}
114
+ </Button>
115
+ </div>
116
+ )}
117
+ </div>
118
+ )}
119
+
120
+ {loading && (
121
+ <Card style={{ padding: 40, textAlign: 'center', marginBottom: 24 }}>
122
+ <Spinner size={40} style={{ margin: '0 auto 16px' }}/>
123
+ <div style={{ fontSize: 14, color: '#94A3B8' }}>Analyzing {files.length} files…</div>
124
+ <div style={{ width: 240, height: 4, background: 'rgba(148,163,184,0.10)', borderRadius: 2, margin: '16px auto 0', overflow: 'hidden' }}>
125
+ <div style={{ width: '60%', height: '100%', background: '#00D4FF', animation: 'pulse 1.2s ease-in-out infinite' }}/>
126
+ </div>
127
+ </Card>
128
+ )}
129
+
130
+ {error && (
131
+ <Card style={{ padding: 20, marginBottom: 24, borderColor: 'rgba(239,68,68,0.35)', background: 'rgba(239,68,68,0.06)' }}>
132
+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
133
+ <Icon name="alert" size={16} color="#EF4444"/>
134
+ <span style={{ fontSize: 14, color: '#EF4444' }}>{error}</span>
135
+ </div>
136
+ </Card>
137
+ )}
138
+
139
+ {summary && (
140
+ <>
141
+ {/* Stat cards */}
142
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
143
+ <StatCard label="Total submissions" value={summary.total} delta="files analyzed" icon="users" iconColor="#00D4FF"/>
144
+ <StatCard label="High risk" value={summary.high_risk} delta="≥ 70% AI probability" deltaColor="#EF4444" icon="alert" iconColor="#EF4444"/>
145
+ <StatCard label="Medium risk" value={summary.medium_risk} delta="40–69% probability" deltaColor="#F59E0B" icon="alert" iconColor="#F59E0B"/>
146
+ <StatCard label="Low risk" value={summary.low_risk} delta="< 40% probability" deltaColor="#10B981" icon="check" iconColor="#10B981"/>
147
+ </div>
148
+
149
+ {/* Success bar */}
150
+ <div style={{ marginBottom: 24, padding: '14px 18px', background: 'rgba(16,185,129,0.06)', border: '1px solid rgba(16,185,129,0.20)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
151
+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
152
+ <Icon name="check" size={16} color="#10B981"/>
153
+ <span style={{ fontSize: 13, color: '#CBD5E1' }}>
154
+ Analyzed <strong style={{ color: '#F8FAFC' }}>{summary.total} files</strong> — avg. AI probability:{' '}
155
+ <strong style={{ color: '#F8FAFC' }}>{Math.round(summary.avg_ai_probability * 100)}%</strong>
156
+ </span>
157
+ </div>
158
+ <div style={{ display: 'flex', gap: 8 }}>
159
+ <Button variant="secondary" size="sm" icon="upload" onClick={() => { setResults([]); setSummary(null); setFiles([]) }}>
160
+ Re-upload
161
+ </Button>
162
+ <Button variant="primary" size="sm" icon="download" onClick={exportCSV}>
163
+ Export CSV
164
+ </Button>
165
+ </div>
166
+ </div>
167
+
168
+ {/* Search toolbar */}
169
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
170
+ <Input
171
+ icon="search"
172
+ placeholder="Search by student ID or filename…"
173
+ value={search}
174
+ onChange={setSearch}
175
+ style={{ width: 320 }}
176
+ />
177
+ </div>
178
+
179
+ <ResultsTable rows={filtered} onOpen={onOpenRow}/>
180
+ </>
181
+ )}
182
+ </div>
183
+ )
184
+ }
frontend/src/screens/DetailScreen.jsx CHANGED
@@ -32,13 +32,16 @@ function buildFeatures(allFeatures) {
32
  ].filter(Boolean)
33
  }
34
 
35
- function buildAnnotations(topFeatures) {
36
- if (!topFeatures?.length) return []
37
- return topFeatures.slice(0, 2).map((f, i) => ({
38
- line: (i + 1) * 2,
39
- tone: f.importance > 0.06 ? 'red' : 'amber',
40
- note: `Suspicious: ${f.name.replace(/_/g, ' ')}`,
41
- }))
 
 
 
42
  }
43
 
44
  export default function DetailScreen({ row, onBack }) {
@@ -51,7 +54,7 @@ export default function DetailScreen({ row, onBack }) {
51
  const langDisplay = lang.charAt(0).toUpperCase() + lang.slice(1)
52
 
53
  const features = buildFeatures(row.all_features)
54
- const annotations = buildAnnotations(row.top_features)
55
  const code = row.code || '// Code not available'
56
 
57
  return (
 
32
  ].filter(Boolean)
33
  }
34
 
35
+ // Anotacije sada dolaze direktno s backenda (analyze_lines funkcija)
36
+ // Backend analizira svaku liniju i detektira konkretne AI signale:
37
+ // "red" = jak signal (docstringovi, dugački identifikatori)
38
+ // "amber" = umjeren signal (komentari, type anotacije, exception handling)
39
+ function buildAnnotations(row) {
40
+ if (row?.line_annotations?.length) {
41
+ return row.line_annotations
42
+ }
43
+ // Fallback: ako nema backendskih anotacija (stariji model), vraćamo prazno
44
+ return []
45
  }
46
 
47
  export default function DetailScreen({ row, onBack }) {
 
54
  const langDisplay = lang.charAt(0).toUpperCase() + lang.slice(1)
55
 
56
  const features = buildFeatures(row.all_features)
57
+ const annotations = buildAnnotations(row)
58
  const code = row.code || '// Code not available'
59
 
60
  return (
frontend/src/screens/DetailScreen2.jsx ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Button, Card, Badge, Label, Icon, LangBadge } from '../components/primitives'
2
+ import CodeEditor from '../components/CodeEditor'
3
+ import ResultGauge from '../components/ResultGauge'
4
+ import DetailSidebar from '../components/DetailSidebar'
5
+ import ExplanationPanel from '../components/ExplanationPanel'
6
+
7
+ function buildFeatures(allFeatures) {
8
+ if (!allFeatures) return []
9
+
10
+ const styleKeys = ['avg_identifier_length', 'avg_function_name_length', 'single_char_name_ratio', 'naming_consistency', 'comment_ratio', 'num_docstrings', 'lexical_diversity', 'trailing_whitespace_ratio']
11
+ const structKeys = ['num_functions', 'avg_function_length', 'max_nesting_depth', 'cyclomatic_complexity_approx', 'if_density', 'for_density', 'ast_depth']
12
+ const statKeys = ['char_entropy', 'token_entropy', 'perplexity']
13
+
14
+ const toFeature = (key, category) => {
15
+ const val = allFeatures[key]
16
+ if (val === undefined || val === null) return null
17
+ const fmtVal = typeof val === 'number'
18
+ ? (key.includes('ratio') || key.includes('density') ? (val * 100).toFixed(1) + '%' : val.toFixed ? val.toFixed(2) : String(val))
19
+ : String(val)
20
+ const severity = key.includes('length') && val > 6 ? 'high'
21
+ : key === 'naming_consistency' && val > 0.7 ? 'high'
22
+ : key === 'comment_ratio' && val > 0.2 ? 'high'
23
+ : key.includes('entropy') ? 'medium'
24
+ : 'low'
25
+ return { name: key.replace(/_/g, ' '), value: fmtVal, severity, category }
26
+ }
27
+
28
+ return [
29
+ ...styleKeys.map(k => toFeature(k, 'Style')),
30
+ ...structKeys.map(k => toFeature(k, 'Structure')),
31
+ ...statKeys.map(k => toFeature(k, 'Statistical')),
32
+ ].filter(Boolean)
33
+ }
34
+
35
+ function buildAnnotations(topFeatures) {
36
+ if (!topFeatures?.length) return []
37
+ return topFeatures.slice(0, 2).map((f, i) => ({
38
+ line: (i + 1) * 2,
39
+ tone: f.importance > 0.06 ? 'red' : 'amber',
40
+ note: `Suspicious: ${f.name.replace(/_/g, ' ')}`,
41
+ }))
42
+ }
43
+
44
+ export default function DetailScreen({ row, onBack }) {
45
+ if (!row) return null
46
+
47
+ const prob = Math.round((row.ai_probability || 0) * 100)
48
+ const tone = prob >= 70 ? 'red' : prob >= 40 ? 'amber' : 'green'
49
+ const label = prob >= 70 ? 'LIKELY AI' : prob >= 40 ? 'POSSIBLY AI' : 'LIKELY HUMAN'
50
+ const lang = row.detected_language || 'python'
51
+ const langDisplay = lang.charAt(0).toUpperCase() + lang.slice(1)
52
+
53
+ const features = buildFeatures(row.all_features)
54
+ const annotations = buildAnnotations(row.top_features)
55
+ const code = row.code || '// Code not available'
56
+
57
+ return (
58
+ <div style={{ padding: '32px 80px 80px', maxWidth: 1280, margin: '0 auto' }}>
59
+ <button onClick={onBack} style={{
60
+ background: 'transparent', border: 'none', color: '#94A3B8', cursor: 'pointer',
61
+ display: 'inline-flex', alignItems: 'center', gap: 6, padding: 0, marginBottom: 20, fontSize: 13,
62
+ }}>
63
+ <Icon name="arrowLeft" size={14}/> Back to batch
64
+ </button>
65
+
66
+ {/* Header */}
67
+ <Card style={{ marginBottom: 24, padding: 24 }}>
68
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 32 }}>
69
+ <div>
70
+ <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
71
+ <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 24, fontWeight: 700, color: '#F8FAFC' }}>{row.id}</span>
72
+ <LangBadge lang={langDisplay}/>
73
+ <Badge tone={tone}>{label}</Badge>
74
+ </div>
75
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: '#94A3B8', fontSize: 13 }}>
76
+ <Icon name="fileCode" size={14}/>
77
+ <span style={{ fontFamily: 'JetBrains Mono, monospace' }}>{row.file || row.id}</span>
78
+ </div>
79
+ </div>
80
+ <ResultGauge value={prob} size={140} animate={false}/>
81
+ </div>
82
+ </Card>
83
+
84
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 24, alignItems: 'start' }}>
85
+ <div>
86
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
87
+ <Label style={{ marginBottom: 0 }}>Annotated source</Label>
88
+ {annotations.length > 0 && (
89
+ <span style={{ fontSize: 11, color: '#64748B' }}>{annotations.length} suspicious lines flagged</span>
90
+ )}
91
+ </div>
92
+ <CodeEditor code={code} readOnly lang={langDisplay} height={420} annotations={annotations} filename={row.file}/>
93
+
94
+ <ExplanationPanel
95
+ explanations={row.explanations}
96
+ verdict={row.verdict}
97
+ aiProbability={row.ai_probability}
98
+ />
99
+ </div>
100
+
101
+ <DetailSidebar features={features}/>
102
+ </div>
103
+ </div>
104
+ )
105
+ }
frontend/src/screens/SimilarityScreen.jsx CHANGED
@@ -1,27 +1,35 @@
1
- import { useState } from 'react'
2
- import { Button, Card, Label, Icon, Input, Spinner } from '../components/primitives'
3
  import Heatmap from '../components/Heatmap'
4
  import { SuspiciousPair } from '../components/DetailSidebar'
5
  import Dropzone from '../components/Dropzone'
 
6
  import { computeSimilarity } from '../api/client'
7
 
8
  export default function SimilarityScreen() {
9
- const [files, setFiles] = useState([])
10
- const [result, setResult] = useState(null)
11
- const [loading, setLoading] = useState(false)
12
- const [error, setError] = useState(null)
13
- const [threshold, setThreshold] = useState(0.70)
 
 
 
14
 
15
  const run = async () => {
16
- if (files.length < 2) { setError('Need at least 2 files to compare.'); return }
17
- setLoading(true); setError(null)
18
- const submissions = await Promise.all(files.map(async f => ({
19
- id: f.name.replace(/\.[^.]+$/, ''),
 
 
20
  code: await f.text(),
21
  })))
 
22
  try {
23
- const data = await computeSimilarity(submissions)
24
  setResult(data)
 
25
  } catch (e) {
26
  setError(e.message)
27
  } finally {
@@ -29,8 +37,23 @@ export default function SimilarityScreen() {
29
  }
30
  }
31
 
 
 
 
 
 
 
 
 
 
32
  const suspiciousPairs = result?.suspicious_pairs?.filter(p => p.similarity >= threshold) || []
33
 
 
 
 
 
 
 
34
  return (
35
  <div style={{ padding: '40px 80px 80px', maxWidth: 1280, margin: '0 auto' }}>
36
  <div style={{ marginBottom: 32 }}>
@@ -39,7 +62,8 @@ export default function SimilarityScreen() {
39
  Submission similarity
40
  </h1>
41
  <p style={{ fontSize: 15, color: '#94A3B8', marginTop: 12, marginBottom: 0, maxWidth: 640 }}>
42
- High similarity between submissions may indicate shared AI prompts. Pairs above the threshold are surfaced below the heatmap.
 
43
  </p>
44
  </div>
45
 
@@ -65,15 +89,24 @@ export default function SimilarityScreen() {
65
 
66
  {error && (
67
  <Card style={{ padding: 20, marginBottom: 24, borderColor: 'rgba(239,68,68,0.35)' }}>
68
- <div style={{ display: 'flex', gap: 10 }}><Icon name="alert" size={16} color="#EF4444"/><span style={{ color: '#EF4444', fontSize: 14 }}>{error}</span></div>
 
 
 
69
  </Card>
70
  )}
71
 
72
  {result && (
73
  <>
74
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gap: 24, alignItems: 'start', marginBottom: 40 }}>
 
75
  <Card style={{ padding: 24 }}>
76
- <Heatmap ids={result.ids} data={result.matrix}/>
 
 
 
 
 
77
  </Card>
78
 
79
  <Card style={{ padding: 18 }}>
@@ -94,13 +127,81 @@ export default function SimilarityScreen() {
94
  </div>
95
  </div>
96
  <div style={{ marginTop: 14 }}>
97
- <Button variant="secondary" size="sm" icon="upload" onClick={() => { setResult(null); setFiles([]) }} style={{ width: '100%' }}>
98
  Re-upload
99
  </Button>
100
  </div>
101
  </Card>
102
  </div>
103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  <div>
105
  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 18 }}>
106
  <h2 style={{ fontSize: 24, fontWeight: 600, color: '#F8FAFC', margin: 0, letterSpacing: '-0.01em' }}>Suspicious pairs</h2>
@@ -108,12 +209,20 @@ export default function SimilarityScreen() {
108
  </div>
109
  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
110
  {suspiciousPairs.map((p, i) => (
111
- <SuspiciousPair key={i} a={p.id_a} b={p.id_b} similarity={Math.round(p.similarity * 100)}/>
 
 
 
 
 
 
112
  ))}
113
  {suspiciousPairs.length === 0 && (
114
  <Card style={{ padding: 40, textAlign: 'center' }}>
115
  <Icon name="check" size={32} color="#10B981"/>
116
- <div style={{ fontSize: 14, color: '#94A3B8', marginTop: 10 }}>No pairs exceed the {Math.round(threshold * 100)}% threshold</div>
 
 
117
  </Card>
118
  )}
119
  </div>
 
1
+ import { useState, useRef } from 'react'
2
+ import { Button, Card, Label, Icon, Spinner } from '../components/primitives'
3
  import Heatmap from '../components/Heatmap'
4
  import { SuspiciousPair } from '../components/DetailSidebar'
5
  import Dropzone from '../components/Dropzone'
6
+ import CodeEditor from '../components/CodeEditor'
7
  import { computeSimilarity } from '../api/client'
8
 
9
  export default function SimilarityScreen() {
10
+ const [files, setFiles] = useState([])
11
+ const [result, setResult] = useState(null)
12
+ const [submissions, setSubmissions] = useState([]) // čuvamo kod za usporedbu
13
+ const [loading, setLoading] = useState(false)
14
+ const [error, setError] = useState(null)
15
+ const [threshold, setThreshold] = useState(0.70)
16
+ const [selectedPair, setSelectedPair] = useState(null) // { i, j, idA, idB, similarity }
17
+ const compareRef = useRef(null)
18
 
19
  const run = async () => {
20
+ if (files.length < 2) { setError('Potrebne su najmanje 2 datoteke.'); return }
21
+ setLoading(true); setError(null); setSelectedPair(null)
22
+
23
+ const subs = await Promise.all(files.map(async f => ({
24
+ id: f.name.replace(/\.[^.]+$/, ''),
25
+ file: f.name,
26
  code: await f.text(),
27
  })))
28
+
29
  try {
30
+ const data = await computeSimilarity(subs)
31
  setResult(data)
32
+ setSubmissions(subs) // sačuvamo kod da ga možemo prikazati
33
  } catch (e) {
34
  setError(e.message)
35
  } finally {
 
37
  }
38
  }
39
 
40
+ // Kad korisnik klikne na ćeliju heatmape
41
+ const handleSelectPair = (pair) => {
42
+ setSelectedPair(pair)
43
+ // Scroll do usporedbe
44
+ if (pair) {
45
+ setTimeout(() => compareRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }), 100)
46
+ }
47
+ }
48
+
49
  const suspiciousPairs = result?.suspicious_pairs?.filter(p => p.similarity >= threshold) || []
50
 
51
+ // Pronađi kod za odabrani par
52
+ const codeA = selectedPair ? submissions.find(s => s.id === selectedPair.idA)?.code || '' : ''
53
+ const codeB = selectedPair ? submissions.find(s => s.id === selectedPair.idB)?.code || '' : ''
54
+ const fileA = selectedPair ? submissions.find(s => s.id === selectedPair.idA)?.file : ''
55
+ const fileB = selectedPair ? submissions.find(s => s.id === selectedPair.idB)?.file : ''
56
+
57
  return (
58
  <div style={{ padding: '40px 80px 80px', maxWidth: 1280, margin: '0 auto' }}>
59
  <div style={{ marginBottom: 32 }}>
 
62
  Submission similarity
63
  </h1>
64
  <p style={{ fontSize: 15, color: '#94A3B8', marginTop: 12, marginBottom: 0, maxWidth: 640 }}>
65
+ Klikni na ćeliju heatmape za prikaz i usporedbu dvaju kodova.
66
+ Visoka sličnost može upućivati na korištenje istog AI prompta.
67
  </p>
68
  </div>
69
 
 
89
 
90
  {error && (
91
  <Card style={{ padding: 20, marginBottom: 24, borderColor: 'rgba(239,68,68,0.35)' }}>
92
+ <div style={{ display: 'flex', gap: 10 }}>
93
+ <Icon name="alert" size={16} color="#EF4444"/>
94
+ <span style={{ color: '#EF4444', fontSize: 14 }}>{error}</span>
95
+ </div>
96
  </Card>
97
  )}
98
 
99
  {result && (
100
  <>
101
+ {/* Heatmap + filter */}
102
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gap: 24, alignItems: 'start', marginBottom: 32 }}>
103
  <Card style={{ padding: 24 }}>
104
+ <Label style={{ marginBottom: 16 }}>Similarity matrix — klikni ćeliju za usporedbu</Label>
105
+ <Heatmap
106
+ ids={result.ids}
107
+ data={result.matrix}
108
+ onSelectPair={handleSelectPair}
109
+ />
110
  </Card>
111
 
112
  <Card style={{ padding: 18 }}>
 
127
  </div>
128
  </div>
129
  <div style={{ marginTop: 14 }}>
130
+ <Button variant="secondary" size="sm" icon="upload" onClick={() => { setResult(null); setFiles([]); setSelectedPair(null) }} style={{ width: '100%' }}>
131
  Re-upload
132
  </Button>
133
  </div>
134
  </Card>
135
  </div>
136
 
137
+ {/* ── Usporedba kodova (prikazuje se kad kliknemo na ćeliju) ── */}
138
+ {selectedPair && (
139
+ <div ref={compareRef} style={{ marginBottom: 40, animation: 'fadeIn .25s ease' }}>
140
+ <Card style={{ padding: 24 }}>
141
+ {/* Header usporedbe */}
142
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
143
+ <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
144
+ <Label style={{ marginBottom: 0 }}>Code comparison</Label>
145
+ <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12, color: '#94A3B8' }}>
146
+ {selectedPair.idA} ↔ {selectedPair.idB}
147
+ </span>
148
+ <span style={{
149
+ fontFamily: 'JetBrains Mono, monospace', fontSize: 14, fontWeight: 700,
150
+ color: selectedPair.similarity >= 80 ? '#EF4444' : selectedPair.similarity >= 60 ? '#F59E0B' : '#10B981',
151
+ }}>
152
+ {selectedPair.similarity}% similar
153
+ </span>
154
+ </div>
155
+ <button
156
+ onClick={() => setSelectedPair(null)}
157
+ style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#64748B', fontSize: 18, lineHeight: 1 }}>
158
+ ✕
159
+ </button>
160
+ </div>
161
+
162
+ {/* Dva editora side by side */}
163
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
164
+ <div>
165
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
166
+ <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#00D4FF', display: 'inline-block' }}/>
167
+ <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12, color: '#CBD5E1', fontWeight: 600 }}>
168
+ {selectedPair.idA}
169
+ </span>
170
+ <span style={{ fontSize: 11, color: '#64748B' }}>{fileA}</span>
171
+ </div>
172
+ <CodeEditor
173
+ code={codeA}
174
+ readOnly
175
+ lang="C"
176
+ filename={fileA}
177
+ height={440}
178
+ annotations={[]}
179
+ />
180
+ </div>
181
+
182
+ <div>
183
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
184
+ <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#F59E0B', display: 'inline-block' }}/>
185
+ <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12, color: '#CBD5E1', fontWeight: 600 }}>
186
+ {selectedPair.idB}
187
+ </span>
188
+ <span style={{ fontSize: 11, color: '#64748B' }}>{fileB}</span>
189
+ </div>
190
+ <CodeEditor
191
+ code={codeB}
192
+ readOnly
193
+ lang="C"
194
+ filename={fileB}
195
+ height={440}
196
+ annotations={[]}
197
+ />
198
+ </div>
199
+ </div>
200
+ </Card>
201
+ </div>
202
+ )}
203
+
204
+ {/* Suspicious pairs lista */}
205
  <div>
206
  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 18 }}>
207
  <h2 style={{ fontSize: 24, fontWeight: 600, color: '#F8FAFC', margin: 0, letterSpacing: '-0.01em' }}>Suspicious pairs</h2>
 
209
  </div>
210
  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
211
  {suspiciousPairs.map((p, i) => (
212
+ <div key={i} onClick={() => {
213
+ const idxA = result.ids.indexOf(p.id_a)
214
+ const idxB = result.ids.indexOf(p.id_b)
215
+ handleSelectPair({ i: idxA, j: idxB, idA: p.id_a, idB: p.id_b, similarity: Math.round(p.similarity * 100) })
216
+ }} style={{ cursor: 'pointer' }}>
217
+ <SuspiciousPair a={p.id_a} b={p.id_b} similarity={Math.round(p.similarity * 100)}/>
218
+ </div>
219
  ))}
220
  {suspiciousPairs.length === 0 && (
221
  <Card style={{ padding: 40, textAlign: 'center' }}>
222
  <Icon name="check" size={32} color="#10B981"/>
223
+ <div style={{ fontSize: 14, color: '#94A3B8', marginTop: 10 }}>
224
+ No pairs exceed the {Math.round(threshold * 100)}% threshold
225
+ </div>
226
  </Card>
227
  )}
228
  </div>
frontend/vite.config.js CHANGED
@@ -9,6 +9,8 @@ export default defineConfig({
9
  '/api': {
10
  target: 'http://localhost:5000',
11
  changeOrigin: true,
 
 
12
  }
13
  }
14
  }
 
9
  '/api': {
10
  target: 'http://localhost:5000',
11
  changeOrigin: true,
12
+ proxyTimeout: 600000, // 10 minuta — za batch od 1000+ fajlova
13
+ timeout: 600000, // isto za socket timeout
14
  }
15
  }
16
  }
model/classifier.pkl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:bdc3f94bdbe63a0d8bd55c7d3372d270c324bf0f62d786bddac83bb3d07fef3d
3
- size 1218635
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3cf637b2ee32d98a72697a8e3101058df2f49dc153406895a262c26eea3287b9
3
+ size 192284979
model/scaler.pkl CHANGED
Binary files a/model/scaler.pkl and b/model/scaler.pkl differ
 
model/threshold.pkl ADDED
Binary file (21 Bytes). View file