java-judge-oo / app.py
rmayormartins's picture
JAVA-Judge
11aa4b5
raw
history blame
4.71 kB
import gradio as gr
import javalang
from typing import Dict, List, Tuple
class JavaPOOEvaluator:
"""Java-Judge: Evaluate POO in Java Code"""
def __init__(self):
self.rubric = {
"classes": 20,
"objetos": 20,
"metodos": 20,
"atributos": 20,
"encapsulamento": 10,
"heranca": 10,
"polimorfismo": 10,
"abstracao": 10,
}
def analyze_classes_and_objects(self, code: str) -> Tuple[float, List[str]]:
"""Avalia a definição e o uso de classes e objetos"""
score = 0
feedback = []
try:
tree = javalang.parse.parse(code)
classes = list(tree.filter(javalang.tree.ClassDeclaration))
if classes:
score += 15
feedback.append(f"✓ {len(classes)} classe(s) declarada(s) corretamente.")
else:
feedback.append("⚠ Nenhuma classe declarada encontrada.")
objects = [node for _, node in tree.filter(javalang.tree.VariableDeclarator) if 'new' in str(node.initializer)]
if objects:
score += 5
feedback.append(f"✓ {len(objects)} objeto(s) criado(s) corretamente.")
else:
feedback.append("⚠ Nenhuma instância de objeto criada.")
except Exception as e:
feedback.append("⚠ Erro ao analisar classes e objetos.")
return score, feedback
# Métodos de análise para outros critérios continuam iguais ao seu código anterior...
def evaluate_code(self, code: str) -> Dict:
"""Avalia o código Java"""
# Avaliações essenciais e bonificadas
cls_score, cls_feedback = self.analyze_classes_and_objects(code)
meth_score, meth_feedback = self.analyze_methods(code)
enc_score, enc_feedback = self.analyze_encapsulation(code)
inh_score, inh_feedback = self.analyze_inheritance(code)
poly_score, poly_feedback = self.analyze_polymorphism(code)
abs_score, abs_feedback = self.analyze_abstraction(code)
# Pontuações
essential_score = cls_score + meth_score
bonus_score = enc_score + inh_score + poly_score + abs_score
total_score = essential_score + bonus_score
total_score = min(100, total_score)
proficiency = "Necessita Melhorias"
if total_score >= 90:
proficiency = "Excelente"
elif total_score >= 75:
proficiency = "Bom"
elif total_score >= 60:
proficiency = "Satisfatório"
return {
"total_score": total_score,
"essential_score": essential_score,
"bonus_score": bonus_score,
"proficiency": proficiency,
"feedback": {
"classes_objetos": cls_feedback,
"metodos": meth_feedback,
"encapsulamento": enc_feedback,
"heranca": inh_feedback,
"polimorfismo": poly_feedback,
"abstracao": abs_feedback
}
}
# Interface Gradio
with gr.Blocks(title="Java-Judge: Evaluate POO in Java Code") as demo:
gr.Markdown("# Avaliador de POO em Java")
gr.Markdown("### [Visualizar a Rubrica em PDF](rubric.pdf)")
gr.Markdown("Ou confira a tabela resumida abaixo.")
gr.Image("rubric_table.png", label="Tabela Resumida da Rubrica")
upload = gr.File(label="Carregue arquivos Java para avaliação", file_types=[".java"], file_count="multiple")
evaluate_button = gr.Button("Avaliar Código")
output = gr.Textbox(label="Resultado da Avaliação", lines=25)
def evaluate_code_files(files) -> str:
"""Função para avaliar múltiplos arquivos Java"""
evaluator = JavaPOOEvaluator()
results = []
for file in files:
with open(file.name, 'r', encoding='utf-8') as f:
code = f.read()
evaluation = evaluator.evaluate_code(code)
result = f"\nArquivo: {file.name}\n"
result += f"Pontuação Total: {evaluation['total_score']:.1f}/100\n"
result += f"Nível: {evaluation['proficiency']}\n\n"
result += "Feedback Detalhado:\n"
for category, comments in evaluation['feedback'].items():
result += f"\n{category.replace('_', ' ').title()}:\n"
for comment in comments:
result += f" {comment}\n"
results.append(result)
return "\n".join(results)
evaluate_button.click(fn=evaluate_code_files, inputs=upload, outputs=output)
if __name__ == "__main__":
demo.launch(share=True)