-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
277 lines (235 loc) · 11.2 KB
/
Copy pathapp.py
File metadata and controls
277 lines (235 loc) · 11.2 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
import json
import streamlit as st
from reviewer import review_code, ReviewError
st.set_page_config(
page_title="Smart Code Reviewer",
page_icon="🔍",
layout="wide",
initial_sidebar_state="collapsed",
)
st.markdown("""
<style>
.stProgress > div > div > div > div { border-radius: 4px; }
.badge-critical { background:#fee2e2; color:#dc2626; padding:2px 8px; border-radius:12px; font-size:12px; font-weight:600; }
.badge-warning { background:#fef3c7; color:#d97706; padding:2px 8px; border-radius:12px; font-size:12px; font-weight:600; }
.badge-suggestion { background:#dbeafe; color:#2563eb; padding:2px 8px; border-radius:12px; font-size:12px; font-weight:600; }
.positive-box {
background: #f0fdf4;
border-left: 4px solid #16a34a;
padding: 14px 16px;
border-radius: 6px;
margin-top: 8px;
}
</style>
""", unsafe_allow_html=True)
# ── Helpers ───────────────────────────────────────────────────────────────────
def score_color(score: float) -> str:
"""Hex color for a 0-10 score: green / amber / red."""
if score >= 8:
return "#16a34a"
if score >= 6:
return "#d97706"
return "#dc2626"
def grade_for(score: float):
"""Return a (label, color) badge for the overall score."""
if score >= 8:
return "Excellent", "#16a34a"
if score >= 6:
return "Good", "#16a34a"
if score >= 4:
return "Needs work", "#d97706"
return "Critical issues", "#dc2626"
def build_markdown_report(r: dict, lines) -> str:
"""Render the review as a portable Markdown report for download."""
icon = {"critical": "🔴", "warning": "🟡", "suggestion": "🔵"}
out = [
"# 🔍 Smart Code Review Report",
"",
f"**Language:** {r.get('language', 'Unknown')} ",
f"**Overall score:** {r.get('overall_score', 0):.1f} / 10 ",
f"**Lines reviewed:** {lines}",
"",
f"> {r.get('summary', '')}",
"",
"## Dimension scores",
"",
]
for key, label in (("readability", "Readability"),
("structure", "Structure"),
("maintainability", "Maintainability")):
d = r.get("dimensions", {}).get(key, {})
out.append(f"- **{label}:** {d.get('score', 0):.1f}/10 — {d.get('summary', '')}")
out += ["", "## Issues", ""]
issues = r.get("issues", [])
if not issues:
out.append("_No issues found._")
else:
for issue in issues:
sev = issue.get("severity", "suggestion")
loc = f" (line {issue['line']})" if issue.get("line") else ""
out.append(f"- {icon.get(sev, '🔵')} **{sev.capitalize()}**{loc} — {issue.get('description', '')}")
out.append(f" - _Fix:_ {issue.get('suggestion', '')}")
out += ["", "## What's done well", "", r.get("positive", "") or "_—_", "",
"---", "_Generated by Smart Code Reviewer · Powered by Claude_"]
return "\n".join(out)
# ── Header ────────────────────────────────────────────────────────────────────
st.title("🔍 Smart Code Reviewer")
st.caption(
"AI-powered review for **readability**, **structure**, and **maintainability** "
"— catch issues before human review."
)
st.divider()
col_left, col_right = st.columns([2, 3], gap="large")
# ── Left column: Input ────────────────────────────────────────────────────────
with col_left:
st.subheader("Code Input")
tab_paste, tab_upload = st.tabs(["📋 Paste Code", "📁 Upload File"])
with tab_paste:
pasted = st.text_area(
"code_paste",
height=340,
placeholder="# Paste your code here…\ndef greet(name):\n print('Hello, ' + name)",
label_visibility="collapsed",
)
with tab_upload:
uploaded = st.file_uploader(
"Upload a source file",
type=["py", "js", "ts", "jsx", "tsx", "java", "cpp", "c",
"go", "rb", "php", "cs", "rs", "swift", "kt", "r", "sh"],
label_visibility="collapsed",
)
file_code = ""
if uploaded is not None:
file_code = uploaded.getvalue().decode("utf-8", errors="replace")
preview = file_code[:3000] + ("…" if len(file_code) > 3000 else "")
st.code(preview, language="text")
# An uploaded file takes precedence; otherwise use pasted text.
if uploaded is not None and file_code.strip():
code = file_code
else:
code = pasted
if uploaded is not None and file_code.strip() and pasted.strip():
st.caption("ℹ️ Both inputs present — reviewing the **uploaded file**. Remove it to use pasted code.")
language = st.selectbox(
"Language",
["Auto-detect", "Python", "JavaScript", "TypeScript", "Java",
"C++", "C", "Go", "Ruby", "PHP", "C#", "Rust", "Swift", "Kotlin", "R", "Bash"],
index=0,
help="Leave on Auto-detect unless the model misidentifies the language.",
)
lang = "auto" if language == "Auto-detect" else language.lower()
review_clicked = st.button(
"🔍 Review Code",
type="primary",
use_container_width=True,
disabled=not code.strip(),
)
if not code.strip():
st.caption("Paste code or upload a file to enable the review.")
# ── Right column: Results ─────────────────────────────────────────────────────
with col_right:
st.subheader("Review Results")
if review_clicked and code.strip():
with st.spinner("Analyzing your code…"):
try:
st.session_state["result"] = review_code(code, lang)
st.session_state["code_len"] = len(code.splitlines())
except ReviewError as e:
st.session_state.pop("result", None)
st.error(str(e))
except Exception as e: # noqa: BLE001 — last-resort guard for the UI
st.session_state.pop("result", None)
st.error(f"Unexpected error: {e}")
if "result" not in st.session_state:
st.info("Your review will appear here once you submit code.", icon="💡")
else:
r = st.session_state["result"]
lines = st.session_state.get("code_len", "—")
# ── Overall score ─────────────────────────────────────────────────────
score = float(r.get("overall_score", 0))
grade, gcolor = grade_for(score)
mc1, mc2, mc3 = st.columns(3)
mc1.metric("Overall Score", f"{score:.1f} / 10")
mc2.metric("Language", r.get("language", "Unknown"))
mc3.metric("Lines reviewed", lines)
st.markdown(
f"<span style='background:{gcolor}1a;color:{gcolor};padding:3px 12px;"
f"border-radius:12px;font-weight:600;font-size:13px'>{grade}</span>",
unsafe_allow_html=True,
)
if r.get("summary"):
st.write(r["summary"])
st.divider()
# ── Dimension scores ──────────────────────────────────────────────────
st.markdown("**Dimension Scores**")
dims = r.get("dimensions", {})
dc1, dc2, dc3 = st.columns(3)
for col, key, label in [
(dc1, "readability", "Readability"),
(dc2, "structure", "Structure"),
(dc3, "maintainability", "Maintainability"),
]:
d = dims.get(key, {})
s = float(d.get("score", 0))
with col:
st.markdown(f"**{label}**")
st.progress(s / 10)
st.markdown(
f"<span style='color:{score_color(s)};font-size:20px;font-weight:700'>{s:.1f}</span>/10",
unsafe_allow_html=True,
)
st.caption(d.get("summary", ""))
st.divider()
# ── Issues ────────────────────────────────────────────────────────────
issues = r.get("issues", [])
counts = {sev: sum(1 for i in issues if i.get("severity") == sev)
for sev in ("critical", "warning", "suggestion")}
st.markdown(
f"**Issues** "
f"<span class='badge-critical'>🔴 {counts['critical']} critical</span> "
f"<span class='badge-warning'>🟡 {counts['warning']} warning</span> "
f"<span class='badge-suggestion'>🔵 {counts['suggestion']} suggestion</span>",
unsafe_allow_html=True,
)
st.write("")
if not issues:
st.success("No issues found — great code!", icon="✅")
else:
sev_icon = {"critical": "🔴", "warning": "🟡", "suggestion": "🔵"}
for issue in issues: # already sorted critical → suggestion
sev = issue.get("severity", "suggestion")
line_ref = issue.get("line")
line_str = f"Line {line_ref} — " if line_ref else ""
label = f"{sev_icon.get(sev, '🔵')} {line_str}{issue.get('description', '')}"
with st.expander(label[:100]):
st.markdown(f"**Issue:** {issue.get('description', '')}")
st.markdown(f"**Suggestion:** {issue.get('suggestion', '')}")
st.caption(f"Category: {issue.get('category', '—')} | Severity: {sev}")
st.divider()
# ── Positive highlight ────────────────────────────────────────────────
if r.get("positive"):
st.markdown(
f"<div class='positive-box'>✅ <strong>What's done well</strong><br>{r['positive']}</div>",
unsafe_allow_html=True,
)
# ── Export + clear ────────────────────────────────────────────────────
st.write("")
ec1, ec2, ec3 = st.columns([2, 2, 1])
ec1.download_button(
"⬇️ Markdown report",
build_markdown_report(r, lines),
file_name="code-review.md",
mime="text/markdown",
use_container_width=True,
)
ec2.download_button(
"⬇️ JSON data",
json.dumps(r, indent=2),
file_name="code-review.json",
mime="application/json",
use_container_width=True,
)
if ec3.button("Clear", use_container_width=True):
st.session_state.pop("result", None)
st.session_state.pop("code_len", None)
st.rerun()