-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
983 lines (794 loc) · 43.3 KB
/
app.py
File metadata and controls
983 lines (794 loc) · 43.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
import streamlit as st
import joblib
import numpy as np
import re
import requests
import base64
import traceback
from typing import Dict, List, Tuple, Optional
from dataclasses import dataclass
from pathlib import Path
@dataclass
class ModelResult:
"""Data class for storing model prediction results"""
name: str
prediction: str
confidence: float
@dataclass
class LineAnalysis:
"""Data class for storing line-by-line analysis results"""
line_number: int
content: str
prediction: str
confidence: float
patterns: List[str]
@dataclass
class FileAnalysisResult:
"""Data class for storing file analysis results"""
file_path: str
prediction: str
confidence: float
line_count: int
ai_lines: int
human_lines: int
model_results: List[ModelResult]
class GitHubRepoAnalyzer:
"""Class for analyzing GitHub repositories"""
@staticmethod
def parse_github_url(url: str) -> Tuple[Optional[str], Optional[str]]:
"""Parse GitHub URL to extract owner and repo name"""
patterns = [
r'github\.com/([^/]+)/([^/]+?)(?:\.git)?$',
r'github\.com/([^/]+)/([^/]+)/tree/',
r'github\.com/([^/]+)/([^/]+)/?$'
]
for pattern in patterns:
match = re.search(pattern, url)
if match:
return match.group(1), match.group(2).replace('.git', '')
return None, None
@staticmethod
def get_repo_contents(owner: str, repo: str, path: str = "") -> List[Dict]:
"""Get contents of a GitHub repository"""
url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}"
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()
except Exception as e:
st.error(f"Error fetching repo contents: {str(e)}")
return []
@staticmethod
def get_all_python_files(owner: str, repo: str, path: str = "") -> List[Dict]:
"""Recursively get all Python files from repository"""
python_files = []
contents = GitHubRepoAnalyzer.get_repo_contents(owner, repo, path)
if not contents:
return python_files
for item in contents:
if item['type'] == 'file' and item['name'].endswith('.py'):
python_files.append(item)
elif item['type'] == 'dir':
# Recursively get files from subdirectories
subdir_files = GitHubRepoAnalyzer.get_all_python_files(owner, repo, item['path'])
python_files.extend(subdir_files)
return python_files
@staticmethod
def get_file_content(download_url: str) -> Optional[str]:
"""Download and decode file content"""
try:
response = requests.get(download_url, timeout=10)
response.raise_for_status()
return response.text
except Exception as e:
st.warning(f"Error downloading file: {str(e)}")
return None
class CodeAnalyzer:
"""Main class for analyzing code with multiple ML models"""
def __init__(self):
self.models = {}
self.vectorizer = None
self.label_encoder = None
self.load_models()
def load_models(self):
"""Load all required models and encoders"""
try:
model_files = {
'logistic': 'model/logisticregression.pkl',
'random_forest': 'model/randomforest.pkl',
'gradient_boost': 'model/gradientboosting.pkl',
'xgboost': 'model/xgboost.pkl'
}
for name, path in model_files.items():
if Path(path).exists():
self.models[name] = joblib.load(path)
else:
st.warning(f"Model {name} not found at {path}")
if Path('model/vectorizer.pkl').exists():
self.vectorizer = joblib.load('model/vectorizer.pkl')
else:
st.error("Vectorizer not found!")
return
if Path('model/labelencoder.pkl').exists():
self.label_encoder = joblib.load('model/labelencoder.pkl')
except Exception as e:
st.error(f"Error loading models: {str(e)}")
def predict_with_model(self, X: np.ndarray, model_name: str) -> Optional[ModelResult]:
"""Make prediction with a specific model"""
if model_name not in self.models:
return None
try:
model = self.models[model_name]
if model_name == 'xgboost':
y_pred = model.predict(X)
if self.label_encoder:
prediction = self.label_encoder.inverse_transform(y_pred)[0]
else:
prediction = "ai" if y_pred[0] == 0 else "human"
else:
prediction = model.predict(X)[0]
confidence = model.predict_proba(X).max()
return ModelResult(
name=model_name.replace('_', ' ').title(),
prediction=prediction,
confidence=confidence
)
except Exception as e:
st.warning(f"Error with {model_name}: {str(e)}")
return None
def analyze_code(self, code: str) -> Tuple[List[ModelResult], str, float]:
"""Analyze code with all available models"""
if not self.vectorizer:
return [], "Error", 0.0
X = self.vectorizer.transform([code])
results = []
for model_name in self.models.keys():
result = self.predict_with_model(X, model_name)
if result:
results.append(result)
final_prediction, final_confidence = self.ensemble_vote(results)
return results, final_prediction, final_confidence
def ensemble_vote(self, results: List[ModelResult]) -> Tuple[str, float]:
"""Calculate ensemble prediction using improved voting logic"""
if not results:
return "unknown", 0.0
# Simple majority vote with confidence weighting
ai_votes = []
human_votes = []
for result in results:
if result.prediction == "ai":
ai_votes.append(result.confidence)
else:
human_votes.append(result.confidence)
# Calculate weighted scores
ai_count = len(ai_votes)
human_count = len(human_votes)
# If we have a clear majority (3+ out of 4 models), use that
if ai_count >= 3:
return "ai", np.mean(ai_votes)
elif human_count >= 3:
return "human", np.mean(human_votes)
else:
# Use confidence-weighted average for ties or 2-2 splits
total_ai_confidence = sum(ai_votes)
total_human_confidence = sum(human_votes)
if total_ai_confidence > total_human_confidence:
return "ai", total_ai_confidence / len(results)
else:
return "human", total_human_confidence / len(results)
def analyze_lines(self, code: str, model_name: str = 'gradient_boost') -> List[LineAnalysis]:
"""Perform line-by-line analysis with improved accuracy"""
if model_name not in self.models or not self.vectorizer:
return []
lines = code.split('\n')
line_analyses = []
for i, line in enumerate(lines):
line_stripped = line.strip()
# Skip empty lines, comments, and very short lines
if not line_stripped or len(line_stripped) < 10:
continue
# Skip pure comments, imports, and simple assignments
if (line_stripped.startswith('#') or
line_stripped.startswith('import ') or
line_stripped.startswith('from ') or
re.match(r'^\w+\s*=\s*\w+$', line_stripped)):
continue
try:
# Use ensemble for line analysis too, but only with top 2 models
results, prediction, confidence = self.analyze_code_snippet(line_stripped)
# Only include lines with high confidence predictions
if confidence > 0.6:
patterns = self.detect_patterns(line_stripped)
line_analyses.append(LineAnalysis(
line_number=i + 1,
content=line_stripped,
prediction=prediction,
confidence=confidence,
patterns=patterns
))
except Exception as e:
continue
return line_analyses
def analyze_code_snippet(self, code_snippet: str) -> Tuple[List[ModelResult], str, float]:
"""Analyze small code snippet with top models only"""
if not self.vectorizer:
return [], "unknown", 0.0
X = self.vectorizer.transform([code_snippet])
results = []
# Use only the two best performing models for line analysis
top_models = ['gradient_boost', 'random_forest']
for model_name in top_models:
if model_name in self.models:
result = self.predict_with_model(X, model_name)
if result:
results.append(result)
if not results:
return [], "unknown", 0.0
# Simple voting for snippets
ai_votes = [r for r in results if r.prediction == "ai"]
human_votes = [r for r in results if r.prediction == "human"]
if len(ai_votes) > len(human_votes):
avg_confidence = np.mean([r.confidence for r in ai_votes])
return results, "ai", avg_confidence
elif len(human_votes) > len(ai_votes):
avg_confidence = np.mean([r.confidence for r in human_votes])
return results, "human", avg_confidence
else:
# Tie - use highest confidence
all_confidences = [r.confidence for r in results]
max_conf_result = max(results, key=lambda x: x.confidence)
return results, max_conf_result.prediction, max_conf_result.confidence
def analyze_file(self, file_path: str, code: str) -> FileAnalysisResult:
"""Analyze a single file and return results with improved metrics"""
results, final_pred, final_conf = self.analyze_code(code)
line_analyses = self.analyze_lines(code)
# Count only significant lines (exclude comments, imports, empty lines)
significant_lines = [l for l in code.split('\n')
if l.strip() and not l.strip().startswith('#')
and not l.strip().startswith('import ')
and not l.strip().startswith('from ')
and len(l.strip()) > 5]
ai_lines = sum(1 for a in line_analyses if a.prediction == "ai")
human_lines = sum(1 for a in line_analyses if a.prediction == "human")
# Apply intelligent correction based on line analysis
corrected_pred, corrected_conf = self.intelligent_prediction_correction(
final_pred, final_conf, ai_lines, human_lines, results
)
return FileAnalysisResult(
file_path=file_path,
prediction=corrected_pred,
confidence=corrected_conf,
line_count=len(significant_lines),
ai_lines=ai_lines,
human_lines=human_lines,
model_results=results
)
def intelligent_prediction_correction(self, file_pred: str, file_conf: float,
ai_lines: int, human_lines: int,
model_results: List[ModelResult]) -> Tuple[str, float]:
"""Apply intelligent correction based on line analysis consistency"""
total_analyzed_lines = ai_lines + human_lines
# If we don't have enough line data, trust the file prediction
if total_analyzed_lines < 10:
return file_pred, file_conf
line_ai_ratio = ai_lines / total_analyzed_lines
line_human_ratio = human_lines / total_analyzed_lines
# Check for major contradictions
major_contradiction = False
if file_pred == "ai" and line_human_ratio > 0.7:
major_contradiction = True
corrected_pred = "human"
# Reduce confidence due to contradiction
corrected_conf = max(0.5, file_conf * 0.7)
elif file_pred == "human" and line_ai_ratio > 0.7:
major_contradiction = True
corrected_pred = "ai"
# Reduce confidence due to contradiction
corrected_conf = max(0.5, file_conf * 0.7)
else:
corrected_pred = file_pred
corrected_conf = file_conf
# Check model confidence spread - if models disagree significantly, be more conservative
confidences = [m.confidence for m in model_results]
confidence_std = np.std(confidences)
# If there's high variance in model confidence, reduce overall confidence
if confidence_std > 0.2:
corrected_conf *= 0.85
# If we have very strong line evidence (>80% in one direction), give it more weight
if line_ai_ratio > 0.8 and file_pred != "ai":
corrected_pred = "ai"
corrected_conf = min(0.8, 0.6 + (line_ai_ratio - 0.8) * 2)
elif line_human_ratio > 0.8 and file_pred != "human":
corrected_pred = "human"
corrected_conf = min(0.8, 0.6 + (line_human_ratio - 0.8) * 2)
return corrected_pred, corrected_conf
def get_analysis_interpretation(self, result: FileAnalysisResult) -> Dict[str, str]:
"""Provide interpretation of analysis results with correction explanations"""
interpretation = {}
# Overall assessment
if result.confidence > 0.8:
certainty = "High confidence"
elif result.confidence > 0.6:
certainty = "Moderate confidence"
else:
certainty = "Low confidence - results may be unreliable"
interpretation['certainty'] = certainty
# Model agreement (check original model results)
ai_models = sum(1 for m in result.model_results if m.prediction == "ai")
total_models = len(result.model_results)
if ai_models == total_models:
agreement = "All file-level models agree (AI)"
elif ai_models == 0:
agreement = "All file-level models agree (Human)"
elif ai_models > total_models / 2:
agreement = f"Majority file-level vote AI ({ai_models}/{total_models})"
else:
agreement = f"Majority file-level vote Human ({total_models - ai_models}/{total_models})"
interpretation['agreement'] = agreement
# Enhanced consistency analysis with correction detection
total_analyzed_lines = result.ai_lines + result.human_lines
if total_analyzed_lines > 0:
line_ai_ratio = result.ai_lines / total_analyzed_lines
line_human_ratio = result.human_lines / total_analyzed_lines
# Check if prediction was likely corrected
original_file_prediction = None
if ai_models == total_models:
original_file_prediction = "ai"
elif ai_models == 0:
original_file_prediction = "human"
elif ai_models > total_models / 2:
original_file_prediction = "ai"
else:
original_file_prediction = "human"
# Determine consistency and corrections
if result.prediction == "ai":
if line_ai_ratio > 0.7:
consistency = "✅ Line analysis strongly supports AI prediction"
elif line_ai_ratio > 0.5:
consistency = "📊 Line analysis moderately supports AI prediction"
elif line_ai_ratio > 0.3:
consistency = "⚠️ Mixed signals - file seems AI but many human-like lines"
else:
if original_file_prediction == "human":
consistency = f"🔄 Corrected to HUMAN based on line analysis ({line_human_ratio:.0%} human lines)"
else:
consistency = f"❌ Major contradiction - models say AI but {line_human_ratio:.0%} lines appear human"
else: # human prediction
if line_human_ratio > 0.7:
consistency = "✅ Line analysis strongly supports Human prediction"
elif line_human_ratio > 0.5:
consistency = "📊 Line analysis moderately supports Human prediction"
elif line_human_ratio > 0.3:
consistency = "⚠️ Mixed signals - file seems Human but many AI-like lines"
else:
if original_file_prediction == "ai":
consistency = f"🔄 Corrected to HUMAN based on line analysis ({line_human_ratio:.0%} human lines)"
else:
consistency = f"❌ Major contradiction - models say Human but {line_ai_ratio:.0%} lines appear AI"
# Special case: detect when correction occurred
if (original_file_prediction != result.prediction and
total_analyzed_lines > 20):
consistency += f" [PREDICTION CORRECTED: {original_file_prediction.upper()} → {result.prediction.upper()}]"
else:
consistency = "Insufficient line data for comparison"
interpretation['consistency'] = consistency
# Add recommendation
if result.confidence < 0.6 or "contradiction" in consistency.lower():
interpretation['recommendation'] = "⚠️ Manual review recommended due to inconsistent signals"
elif "corrected" in consistency.lower():
interpretation['recommendation'] = "📋 Prediction corrected based on line-level analysis"
else:
interpretation['recommendation'] = "✅ Prediction appears reliable"
return interpretation
def detect_patterns(self, line: str) -> List[str]:
"""Detect coding patterns in a line"""
patterns = []
line = line.strip()
pattern_checks = {
'function_def': r'^def\s+\w+\s*\(',
'class_def': r'^class\s+\w+',
'import_statement': r'^(import|from)\s+',
'comment': r'^\s*#',
'loop': r'^\s*(for|while)\s+',
'conditional': r'^\s*if\s+',
'print_statement': r'print\s*\(',
'input_statement': r'input\s*\(',
'list_comprehension': r'\[.*for.*in.*\]',
'lambda': r'lambda\s+',
'exception_handling': r'^\s*(try|except|finally):',
'docstring': r'""".*"""',
'f_string': r'f["\'].*\{.*\}.*["\']',
}
for pattern_name, regex in pattern_checks.items():
if re.search(regex, line, re.IGNORECASE):
patterns.append(pattern_name.replace('_', ' ').title())
return patterns
class SummarizationEngine:
"""Class for summarizing analysis results with improved interpretation"""
@staticmethod
def summarize_file_analysis(results: List[FileAnalysisResult]) -> Dict:
"""Summarize results from multiple files with analysis quality metrics"""
if not results:
return {"error": "No results to summarize"}
total_files = len(results)
ai_files = sum(1 for r in results if r.prediction == "ai")
human_files = sum(1 for r in results if r.prediction == "human")
# Confidence analysis
avg_confidence = np.mean([r.confidence for r in results])
high_confidence_files = sum(1 for r in results if r.confidence > 0.8)
low_confidence_files = sum(1 for r in results if r.confidence < 0.6)
# Line analysis
total_lines = sum(r.line_count for r in results)
total_ai_lines = sum(r.ai_lines for r in results)
total_human_lines = sum(r.human_lines for r in results)
total_analyzed_lines = total_ai_lines + total_human_lines
# Model agreement analysis
unanimous_ai = sum(1 for r in results if all(m.prediction == "ai" for m in r.model_results))
unanimous_human = sum(1 for r in results if all(m.prediction == "human" for m in r.model_results))
split_decisions = total_files - unanimous_ai - unanimous_human
# Consistency warnings
warnings = []
# Check if all files are predicted as AI (suspicious)
if ai_files == total_files and total_files > 3:
warnings.append("⚠️ All files predicted as AI - this may indicate model bias or unusual repository")
# Check line vs file prediction consistency
if total_analyzed_lines > 0:
line_ai_ratio = total_ai_lines / total_analyzed_lines
file_ai_ratio = ai_files / total_files
if abs(line_ai_ratio - file_ai_ratio) > 0.3:
warnings.append("⚠️ Significant discrepancy between file-level and line-level predictions")
# Check confidence levels
if avg_confidence < 0.6:
warnings.append("⚠️ Low average confidence - results may be unreliable")
if split_decisions > total_files * 0.5:
warnings.append("⚠️ Many split decisions between models - mixed coding patterns detected")
return {
"total_files": total_files,
"ai_files": ai_files,
"human_files": human_files,
"ai_percentage": (ai_files / total_files) * 100,
"human_percentage": (human_files / total_files) * 100,
"average_confidence": avg_confidence,
"high_confidence_files": high_confidence_files,
"low_confidence_files": low_confidence_files,
"total_lines": total_lines,
"ai_lines": total_ai_lines,
"human_lines": total_human_lines,
"total_analyzed_lines": total_analyzed_lines,
"ai_lines_percentage": (total_ai_lines / total_analyzed_lines) * 100 if total_analyzed_lines > 0 else 0,
"human_lines_percentage": (total_human_lines / total_analyzed_lines) * 100 if total_analyzed_lines > 0 else 0,
"unanimous_ai": unanimous_ai,
"unanimous_human": unanimous_human,
"split_decisions": split_decisions,
"warnings": warnings,
"interpretation": SummarizationEngine.get_overall_interpretation(ai_files, total_files, avg_confidence, warnings)
}
@staticmethod
def get_overall_interpretation(ai_files: int, total_files: int, avg_confidence: float, warnings: List[str]) -> str:
"""Generate overall interpretation of the analysis"""
ai_ratio = ai_files / total_files
if len(warnings) > 0:
reliability = "⚠️ Results should be interpreted with caution due to noted warnings."
elif avg_confidence > 0.8:
reliability = "✅ High confidence results - analysis is likely reliable."
elif avg_confidence > 0.6:
reliability = "📊 Moderate confidence results - generally reliable with some uncertainty."
else:
reliability = "❓ Low confidence results - analysis may be unreliable."
if ai_ratio == 1.0:
prediction_summary = "All files appear to be AI-generated."
elif ai_ratio == 0.0:
prediction_summary = "All files appear to be human-written."
elif ai_ratio > 0.7:
prediction_summary = f"Repository is predominantly AI-generated ({ai_ratio:.1%})."
elif ai_ratio > 0.3:
prediction_summary = f"Repository shows mixed AI/human content ({ai_ratio:.1%} AI)."
else:
prediction_summary = f"Repository is predominantly human-written ({ai_ratio:.1%} AI)."
return f"{prediction_summary} {reliability}"
@staticmethod
def generate_report(summary: Dict, results: List[FileAnalysisResult]) -> str:
"""Generate a comprehensive text report"""
report = []
report.append("# AI vs Human Code Detection Analysis Report")
report.append("=" * 50)
# Overall summary
report.append(f"Total Files Analyzed: {summary['total_files']}")
report.append(f"AI-Generated Files: {summary['ai_files']} ({summary['ai_percentage']:.1f}%)")
report.append(f"Human-Written Files: {summary['human_files']} ({summary['human_percentage']:.1f}%)")
report.append(f"Average Confidence: {summary['average_confidence']:.3f}")
report.append("")
# Line analysis
report.append("## Line-by-Line Analysis")
report.append(f"Total Code Lines: {summary['total_lines']}")
report.append(f"AI Lines: {summary['ai_lines']} ({summary['ai_lines_percentage']:.1f}%)")
report.append(f"Human Lines: {summary['human_lines']} ({summary['human_lines_percentage']:.1f}%)")
report.append("")
# File details
report.append("## File Details")
for result in sorted(results, key=lambda x: x.confidence, reverse=True):
report.append(f"File: {result.file_path}")
report.append(f" Prediction: {result.prediction.upper()}")
report.append(f" Confidence: {result.confidence:.3f}")
report.append(f" Lines: {result.line_count} (AI: {result.ai_lines}, Human: {result.human_lines})")
report.append("")
return "\n".join(report)
def main():
"""Main Streamlit application"""
st.set_page_config(
page_title="AI vs Human Code Detector",
page_icon="🔍",
layout="wide"
)
st.title("🔍 AI vs Human Code Detection System")
st.markdown("Advanced ensemble model for detecting AI-generated vs human-written code")
# Initialize analyzer
if 'analyzer' not in st.session_state:
st.session_state.analyzer = CodeAnalyzer()
analyzer = st.session_state.analyzer
# Check if models are loaded
if not analyzer.models or not analyzer.vectorizer:
st.error("❌ Models not loaded properly. Please ensure model files are available.")
st.stop()
# Sidebar for navigation
st.sidebar.title("Navigation")
mode = st.sidebar.selectbox(
"Choose Analysis Mode",
["Single Code Analysis", "GitHub Repository Analysis", "Batch File Analysis"]
)
if mode == "Single Code Analysis":
st.header("📝 Single Code Analysis")
# Code input
code_input = st.text_area(
"Enter Python code to analyze:",
height=300,
placeholder="def hello_world():\n print('Hello, World!')"
)
if st.button("🔍 Analyze Code", key="analyze_single"):
if code_input.strip():
with st.spinner("Analyzing code..."):
try:
results, final_pred, final_conf = analyzer.analyze_code(code_input)
# Display results
st.subheader("📊 Analysis Results")
# Overall result
col1, col2 = st.columns(2)
with col1:
if final_pred == "ai":
st.error(f"🤖 **AI-Generated Code**")
else:
st.success(f"👨💻 **Human-Written Code**")
with col2:
st.metric("Confidence Score", f"{final_conf:.3f}")
# Model breakdown
st.subheader("🔧 Model Breakdown")
for result in results:
col1, col2, col3 = st.columns(3)
with col1:
st.write(f"**{result.name}**")
with col2:
if result.prediction == "ai":
st.write("🤖 AI")
else:
st.write("👨💻 Human")
with col3:
st.write(f"{result.confidence:.3f}")
# Line-by-line analysis
if st.checkbox("Show Line-by-Line Analysis"):
st.subheader("📋 Line-by-Line Analysis")
line_analyses = analyzer.analyze_lines(code_input)
for analysis in line_analyses:
with st.expander(f"Line {analysis.line_number}: {analysis.content[:50]}..."):
col1, col2 = st.columns(2)
with col1:
st.code(analysis.content)
with col2:
if analysis.prediction == "ai":
st.write("🤖 **Prediction:** AI")
else:
st.write("👨💻 **Prediction:** Human")
st.write(f"**Confidence:** {analysis.confidence:.3f}")
if analysis.patterns:
st.write("**Patterns:**")
for pattern in analysis.patterns:
st.write(f"- {pattern}")
except Exception as e:
st.error(f"Error during analysis: {str(e)}")
else:
st.warning("Please enter some code to analyze.")
elif mode == "GitHub Repository Analysis":
st.header("🐙 GitHub Repository Analysis")
# GitHub URL input
github_url = st.text_input(
"Enter GitHub Repository URL:",
placeholder="https://github.com/user/repository"
)
if st.button("🔍 Analyze Repository", key="analyze_repo"):
if github_url.strip():
owner, repo = GitHubRepoAnalyzer.parse_github_url(github_url)
if not owner or not repo:
st.error("❌ Invalid GitHub URL format")
st.stop()
st.info(f"Analyzing repository: {owner}/{repo}")
# Get all Python files
with st.spinner("Fetching repository files..."):
python_files = GitHubRepoAnalyzer.get_all_python_files(owner, repo)
if not python_files:
st.warning("No Python files found in the repository")
st.stop()
st.success(f"Found {len(python_files)} Python files")
# Analysis container
analysis_results = []
progress_bar = st.progress(0)
status_text = st.empty()
for i, file_info in enumerate(python_files):
status_text.text(f"Analyzing {file_info['name']} ({i+1}/{len(python_files)})")
# Get file content
content = GitHubRepoAnalyzer.get_file_content(file_info['download_url'])
if content:
try:
file_result = analyzer.analyze_file(file_info['path'], content)
analysis_results.append(file_result)
except Exception as e:
st.warning(f"Error analyzing {file_info['name']}: {str(e)}")
progress_bar.progress((i + 1) / len(python_files))
status_text.text("Analysis complete!")
if analysis_results:
# Generate summary
summary = SummarizationEngine.summarize_file_analysis(analysis_results)
# Display interpretation first
if 'interpretation' in summary:
st.info(f"**Analysis Interpretation:** {summary['interpretation']}")
# Display warnings if any
if 'warnings' in summary and summary['warnings']:
st.warning("**Analysis Warnings:**")
for warning in summary['warnings']:
st.write(f"• {warning}")
# Display summary
st.subheader("📊 Repository Analysis Summary")
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Files", summary['total_files'])
with col2:
if summary['ai_percentage'] == 100:
st.metric("AI Files", f"{summary['ai_files']} ({summary['ai_percentage']:.0f}%)", delta="⚠️ All AI")
else:
st.metric("AI Files", f"{summary['ai_files']} ({summary['ai_percentage']:.1f}%)")
with col3:
st.metric("Human Files", f"{summary['human_files']} ({summary['human_percentage']:.1f}%)")
with col4:
confidence_color = "normal"
if summary['average_confidence'] < 0.6:
confidence_color = "inverse"
st.metric("Avg Confidence", f"{summary['average_confidence']:.3f}")
# Model agreement analysis
if 'unanimous_ai' in summary:
st.subheader("🤖 Model Agreement Analysis")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Unanimous AI", summary['unanimous_ai'])
with col2:
st.metric("Unanimous Human", summary['unanimous_human'])
with col3:
st.metric("Split Decisions", summary['split_decisions'])
# Line analysis
st.subheader("📈 Line-by-Line Summary")
st.write(f"*Based on {summary['total_analyzed_lines']} analyzed lines (excluding comments, imports, etc.)*")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Significant Lines", summary['total_lines'])
with col2:
if summary['total_analyzed_lines'] > 0:
st.metric("AI Lines", f"{summary['ai_lines']} ({summary['ai_lines_percentage']:.1f}%)")
else:
st.metric("AI Lines", "N/A")
with col3:
if summary['total_analyzed_lines'] > 0:
st.metric("Human Lines", f"{summary['human_lines']} ({summary['human_lines_percentage']:.1f}%)")
else:
st.metric("Human Lines", "N/A")
# File results
st.subheader("📁 File Analysis Results")
for result in sorted(analysis_results, key=lambda x: x.confidence, reverse=True):
# Get interpretation for this file
interpretation = analyzer.get_analysis_interpretation(result)
# Create title with confidence indicator
confidence_indicator = ""
if result.confidence > 0.8:
confidence_indicator = "🔵" # High confidence
elif result.confidence > 0.6:
confidence_indicator = "🟡" # Medium confidence
else:
confidence_indicator = "🔴" # Low confidence
title = f"{confidence_indicator} {result.file_path} - {result.prediction.upper()} ({result.confidence:.3f})"
with st.expander(title):
# Interpretation section
st.write("**Analysis Interpretation:**")
st.write(f"• **Certainty:** {interpretation['certainty']}")
st.write(f"• **Model Agreement:** {interpretation['agreement']}")
st.write(f"• **Consistency:** {interpretation['consistency']}")
if 'recommendation' in interpretation:
st.write(f"• **Recommendation:** {interpretation['recommendation']}")
st.divider()
col1, col2 = st.columns(2)
with col1:
st.write(f"**Prediction:** {result.prediction.upper()}")
st.write(f"**Confidence:** {result.confidence:.3f}")
st.write(f"**Significant Lines:** {result.line_count}")
# Line analysis breakdown
total_analyzed = result.ai_lines + result.human_lines
if total_analyzed > 0:
st.write(f"**Line Analysis:** {total_analyzed} lines analyzed")
st.write(f" - AI: {result.ai_lines} ({result.ai_lines/total_analyzed*100:.1f}%)")
st.write(f" - Human: {result.human_lines} ({result.human_lines/total_analyzed*100:.1f}%)")
else:
st.write("**Line Analysis:** Insufficient data")
with col2:
# Model breakdown
st.write("**Individual Model Results:**")
for model_result in result.model_results:
emoji = "🤖" if model_result.prediction == "ai" else "👨💻"
st.write(f" {emoji} {model_result.name}: {model_result.prediction} ({model_result.confidence:.3f})")
# Generate report
if st.button("📄 Generate Report", key="generate_report"):
report = SummarizationEngine.generate_report(summary, analysis_results)
st.text_area("Analysis Report", report, height=400)
# Download report
st.download_button(
label="💾 Download Report",
data=report,
file_name=f"{owner}_{repo}_analysis_report.txt",
mime="text/plain"
)
else:
st.warning("Please enter a GitHub repository URL.")
elif mode == "Batch File Analysis":
st.header("📂 Batch File Analysis")
st.info("Upload multiple Python files for batch analysis")
uploaded_files = st.file_uploader(
"Choose Python files",
accept_multiple_files=True,
type=['py']
)
if uploaded_files and st.button("🔍 Analyze Files", key="analyze_batch"):
analysis_results = []
progress_bar = st.progress(0)
status_text = st.empty()
for i, uploaded_file in enumerate(uploaded_files):
status_text.text(f"Analyzing {uploaded_file.name} ({i+1}/{len(uploaded_files)})")
try:
content = uploaded_file.getvalue().decode('utf-8')
file_result = analyzer.analyze_file(uploaded_file.name, content)
analysis_results.append(file_result)
except Exception as e:
st.warning(f"Error analyzing {uploaded_file.name}: {str(e)}")
progress_bar.progress((i + 1) / len(uploaded_files))
status_text.text("Analysis complete!")
if analysis_results:
# Generate summary
summary = SummarizationEngine.summarize_file_analysis(analysis_results)
# Display summary (similar to repository analysis)
st.subheader("📊 Batch Analysis Summary")
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Files", summary['total_files'])
with col2:
st.metric("AI Files", f"{summary['ai_files']} ({summary['ai_percentage']:.1f}%)")
with col3:
st.metric("Human Files", f"{summary['human_files']} ({summary['human_percentage']:.1f}%)")
with col4:
st.metric("Avg Confidence", f"{summary['average_confidence']:.3f}")
# File results
st.subheader("📁 File Analysis Results")
for result in sorted(analysis_results, key=lambda x: x.confidence, reverse=True):
with st.expander(f"{result.file_path} - {result.prediction.upper()} ({result.confidence:.3f})"):
col1, col2 = st.columns(2)
with col1:
st.write(f"**Prediction:** {result.prediction.upper()}")
st.write(f"**Confidence:** {result.confidence:.3f}")
st.write(f"**Lines:** {result.line_count}")
with col2:
st.write(f"**AI Lines:** {result.ai_lines}")
st.write(f"**Human Lines:** {result.human_lines}")
if __name__ == "__main__":
main()