Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
model_id = "answerdotai/ModernBERT-base"
|
| 11 |
+
path = "DanGalt/modernbert-code-comrel-synthetic"
|
| 12 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 13 |
+
model = AutoModelForSequenceClassification.from_pretrained(path)
|
| 14 |
+
sep = "[SEP]"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def prepare_input(example):
|
| 18 |
+
tokens = tokenizer(
|
| 19 |
+
example["function_definition"] + sep + example["code"] + sep + example["comment"],
|
| 20 |
+
truncation=True,
|
| 21 |
+
max_length=1024,
|
| 22 |
+
return_tensors="pt"
|
| 23 |
+
)
|
| 24 |
+
return tokens
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def parse_text(text):
|
| 28 |
+
# NOTE: Doesn't collect comments and function definitions correctly
|
| 29 |
+
inputs = []
|
| 30 |
+
defs = []
|
| 31 |
+
tree = ast.parse(text)
|
| 32 |
+
for el in tree.body:
|
| 33 |
+
if isinstance(el, ast.FunctionDef):
|
| 34 |
+
defs.append((el.lineno - 1, el.end_lineno - 1, el.col_offset))
|
| 35 |
+
|
| 36 |
+
inputs = []
|
| 37 |
+
lines = text.split('\n')
|
| 38 |
+
for lineno, line in enumerate(lines):
|
| 39 |
+
if (offset := line.find('#')) != -1:
|
| 40 |
+
corresponding_def = None
|
| 41 |
+
for (def_l, def_el, def_off) in defs:
|
| 42 |
+
if def_l <= lineno and def_off <= offset:
|
| 43 |
+
corresponding_def = (def_l, def_el, def_off)
|
| 44 |
+
|
| 45 |
+
comment = line[offset:]
|
| 46 |
+
code = '\n'.join(lines[lineno - 4:lineno + 4])
|
| 47 |
+
fdef = "None"
|
| 48 |
+
if corresponding_def is not None:
|
| 49 |
+
fdef = [lines[corresponding_def[0]][corresponding_def[2]:]]
|
| 50 |
+
cur_lineno = corresponding_def[0]
|
| 51 |
+
while cur_lineno <= corresponding_def[1]:
|
| 52 |
+
if lines[cur_lineno].find("):") != -1 or lines[cur_lineno].find("->") != -1:
|
| 53 |
+
fdef += lines[corresponding_def[0] + 1:cur_lineno + 1]
|
| 54 |
+
break
|
| 55 |
+
cur_lineno += 1
|
| 56 |
+
|
| 57 |
+
fdef = '\n'.join(fdef).strip()
|
| 58 |
+
|
| 59 |
+
inputs.append({
|
| 60 |
+
"function_definition": fdef,
|
| 61 |
+
"code": code,
|
| 62 |
+
"comment": comment,
|
| 63 |
+
"lineno": lineno
|
| 64 |
+
})
|
| 65 |
+
return inputs
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def predict(inp, model=model):
|
| 69 |
+
with torch.no_grad():
|
| 70 |
+
out = model(**inp)
|
| 71 |
+
return nn.functional.softmax(out.logits, dim=-1)[0, 1].item()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def parse_and_predict(text, thrd=0.0):
|
| 75 |
+
parsed = parse_text(text)
|
| 76 |
+
preds = [predict(prepare_input(p)) for p in parsed]
|
| 77 |
+
result = []
|
| 78 |
+
for i, p in enumerate(preds):
|
| 79 |
+
if thrd > 0:
|
| 80 |
+
p = thrd > p
|
| 81 |
+
result.append((parsed[i]["lineno"], p))
|
| 82 |
+
|
| 83 |
+
return result
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def parse_and_predict_file(path, thrd=0.0):
|
| 87 |
+
text = Path(path).open("r").read()
|
| 88 |
+
return parse_and_predict(text, thrd)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def parse_and_predict_pretty_out(text, thrd=0.0):
|
| 92 |
+
results = parse_and_predict(text, thrd=thrd)
|
| 93 |
+
lines = text.split('\n')
|
| 94 |
+
output = []
|
| 95 |
+
if thrd > 0:
|
| 96 |
+
for lineno, do_warn in results:
|
| 97 |
+
if do_warn:
|
| 98 |
+
output.append(f"The comment on line {lineno} is incorrect: '{lines[lineno]}'.")
|
| 99 |
+
else:
|
| 100 |
+
for lineno, p in results:
|
| 101 |
+
output.append(f"The comment on line {lineno} is estimated to be correct with probability {p:.2f}: '{lines[lineno]}'.")
|
| 102 |
+
return '\n'.join(output)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
example_text = """a = 3
|
| 106 |
+
b = 2
|
| 107 |
+
# The code below does some calculations based on a predefined rule that is very important
|
| 108 |
+
c = a - b # Calculate and store the sum of a and b in c
|
| 109 |
+
d = a + b # Calculate and store the sum of a and b in d
|
| 110 |
+
e = c * b # Calculate and store the product of c and d in e
|
| 111 |
+
print(f"Wow, maths: {[a, b, c, d, e]}")"""
|
| 112 |
+
|
| 113 |
+
gradio_app = gr.Interface(
|
| 114 |
+
fn=parse_and_predict_pretty_out,
|
| 115 |
+
inputs=[
|
| 116 |
+
gr.Textbox(label="Input", lines=7),
|
| 117 |
+
gr.Slider(value=0.8, minimum=0.0, maximum=1.0, step=0.05)],
|
| 118 |
+
outputs=[gr.Textbox(label="Predictions", lines=7)],
|
| 119 |
+
examples=[[example_text, 0.0], [example_text, 0.53]],
|
| 120 |
+
title="Comment \"Correctness\" Classifier",
|
| 121 |
+
description='Calculates probabilities for each comment in text to be "correct"/"relevant". If the threshold is 0, outputs raw predictions. Otherwise, will report only "incorrect" comments.'
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
gradio_app.launch()
|