rmayormartins commited on
Commit
17afc90
·
1 Parent(s): c4165bb

JAVA-Inspector

Browse files
Files changed (6) hide show
  1. Classe1.java +17 -0
  2. Classe2.java +16 -0
  3. Principal.java +22 -0
  4. README.md +48 -8
  5. app.py +173 -0
  6. requirements.txt +3 -0
Classe1.java ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ public class Classe1 {
4
+ private String mensagem;
5
+
6
+ public Classe1() {
7
+ this.mensagem = "Olá da Classe 1!";
8
+ }
9
+
10
+ public String getMensagem() {
11
+ return mensagem;
12
+ }
13
+
14
+ public void setMensagem(String mensagem) {
15
+ this.mensagem = mensagem;
16
+ }
17
+ }
Classe2.java ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ public class Classe2 {
2
+ private int numero;
3
+
4
+ public Classe2() {
5
+ this.numero = 42;
6
+ }
7
+
8
+ public int getNumero() {
9
+ return numero;
10
+ }
11
+
12
+ public void setNumero(int numero) {
13
+ this.numero = numero;
14
+ }
15
+ }
16
+
Principal.java ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //nao preciso importar, tudo no mesmo diretorio
2
+
3
+ public class Principal {
4
+ public static void main(String[] args) {
5
+ // Criando instâncias das classes
6
+ Classe1 obj1 = new Classe1();
7
+ Classe2 obj2 = new Classe2();
8
+
9
+ // Acessando e mostrando os valores
10
+ System.out.println(obj1.getMensagem());
11
+ System.out.println("Número da Classe 2: " + obj2.getNumero());
12
+
13
+ // Modificando os valores
14
+ obj1.setMensagem("Mensagem modificada!");
15
+ obj2.setNumero(100);
16
+
17
+ // Mostrando os valores modificados
18
+ System.out.println("\nApós modificação:");
19
+ System.out.println(obj1.getMensagem());
20
+ System.out.println("Número da Classe 2: " + obj2.getNumero());
21
+ }
22
+ }
README.md CHANGED
@@ -1,14 +1,54 @@
1
  ---
2
- title: Java Inspector
3
- emoji: 🐠
4
- colorFrom: yellow
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 5.9.1
8
  app_file: app.py
9
  pinned: false
10
- license: ecl-2.0
11
- short_description: 'JAVA-Inspector: OO Paradigm and Syntax Inspector for Java Co'
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Java Syntax and OO Paradigm Inspector
3
+ emoji: 🔍️☕♨️💻
4
+ colorFrom: blue
5
+ colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 4.7.1
8
  app_file: app.py
9
  pinned: false
10
+ license: mit
 
11
  ---
12
 
13
+ # Java Syntax and OO Paradigm Inspector
14
+
15
+ This project analyzes Java code to extract insights about syntax elements and Object-Oriented (OO) paradigm usage. The tool identifies primitive types, constants, variable declarations, control structures, and more, helping developers understand and improve their Java code.
16
+
17
+ ## Developer
18
+
19
+ Developed by Ramon Mayor Martins (2024)
20
+
21
+ - Email: [email protected]
22
+ - Homepage: https://rmayormartins.github.io/
23
+ - Twitter: @rmayormartins
24
+ - GitHub: https://github.com/rmayormartins
25
+ - Space: https://huggingface.co/rmayormartins
26
+
27
+ ## Key Features
28
+
29
+ - **Syntax Analysis**:
30
+ - Detects primitive types and constants.
31
+ - Identifies control structures like `if/else`, `switch/case`, loops, and operators.
32
+ - Tracks input/output operations (e.g., `System.out.print`, `Scanner`).
33
+
34
+ - **OO Analysis**:
35
+ - Counts classes, objects, and methods.
36
+ - Examines encapsulation, inheritance, polymorphism, abstraction.
37
+
38
+ - **User-Friendly Interface**:
39
+ - Upload multiple Java files for analysis.
40
+ - Displays results in an easy-to-read table.
41
+
42
+ ## How to Use
43
+
44
+ 1. Open the application interface.
45
+ 2. Upload one or more `.java` files.
46
+ 3. View detailed syntax and OO paradigm statistics for each file.
47
+
48
+ ## Local Development
49
+
50
+ To run locally:
51
+
52
+ ```bash
53
+ pip install -r requirements.txt
54
+ python app.py
app.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import javalang
3
+ from collections import Counter
4
+ from typing import Dict, List
5
+
6
+ class JavaSyntaxAnalyzer:
7
+ """JAVA-Inspector: OO Paradigm and Syntax Inspector for Java Code """
8
+
9
+ def analyze_syntax(self, code: str) -> Dict[str, int]:
10
+ """Analisa sintaticamente o código em diferentes categorias"""
11
+ results = Counter()
12
+
13
+ try:
14
+ tree = javalang.parse.parse(code)
15
+
16
+ # Declarações
17
+ results["Tipos Primitivos"] = len([
18
+ node.type.name for _, node in tree.filter(javalang.tree.LocalVariableDeclaration)
19
+ if node.type.name in {"int", "double", "boolean", "char", "float", "long", "byte", "short"}
20
+ ])
21
+ results["Constantes (final)"] = sum(
22
+ 1 for _, node in tree.filter(javalang.tree.FieldDeclaration) if "final" in node.modifiers
23
+ )
24
+ results["Variáveis Declaradas"] = len(list(tree.filter(javalang.tree.LocalVariableDeclaration)))
25
+
26
+ # Estruturas de Controle
27
+ results["If/Else"] = len(list(tree.filter(javalang.tree.IfStatement)))
28
+ results["Switch/Case"] = len(list(tree.filter(javalang.tree.SwitchStatement)))
29
+ results["For Loops"] = len(list(tree.filter(javalang.tree.ForStatement)))
30
+ results["While Loops"] = len(list(tree.filter(javalang.tree.WhileStatement)))
31
+ results["Do-While Loops"] = len(list(tree.filter(javalang.tree.DoStatement)))
32
+
33
+ # Operadores
34
+ code_snippet = code
35
+ operators = {
36
+ "Aritméticos": ["+", "-", "*", "/", "%"],
37
+ "Comparação": ["==", "!=", ">", "<", ">=", "<="],
38
+ "Lógicos": ["&&", "||", "!"],
39
+ "Atribuição": ["+=", "-=", "*=", "/="],
40
+ }
41
+ for category, ops in operators.items():
42
+ results[category] = sum(code_snippet.count(op) for op in ops)
43
+
44
+ # Entrada/Saída e Strings
45
+ results["System.out.print"] = code_snippet.count("System.out.print")
46
+ results["Scanner"] = code_snippet.count("Scanner")
47
+ results["Concatenação de Strings"] = code_snippet.count("+")
48
+ string_methods = ["concat", "substring", "length", "equals", "compareTo"]
49
+ results["Métodos de String"] = sum(code_snippet.count(f".{method}(") for method in string_methods)
50
+
51
+ except Exception as e:
52
+ results["Erro"] = str(e)
53
+
54
+ return dict(results)
55
+
56
+ def analyze_oo(self, code: str) -> Dict[str, int]:
57
+ """Analisa elementos do paradigma OO"""
58
+ results = Counter()
59
+
60
+ try:
61
+ tree = javalang.parse.parse(code)
62
+
63
+ # Classes e Objetos
64
+ results["Classes"] = len(list(tree.filter(javalang.tree.ClassDeclaration)))
65
+ results["Objetos"] = len([
66
+ node for _, node in tree.filter(javalang.tree.VariableDeclarator)
67
+ if node.initializer and "new" in str(node.initializer)
68
+ ])
69
+
70
+ # Métodos
71
+ results["Métodos"] = len(list(tree.filter(javalang.tree.MethodDeclaration)))
72
+
73
+ # Atributos e Encapsulamento
74
+ fields = list(tree.filter(javalang.tree.FieldDeclaration))
75
+ results["Atributos"] = len(fields)
76
+ results["Encapsulamento"] = sum(
77
+ 1 for _, field in fields if "private" in field.modifiers
78
+ )
79
+
80
+ # Herança
81
+ results["Herança"] = len([
82
+ node for _, node in tree.filter(javalang.tree.ClassDeclaration) if node.extends
83
+ ])
84
+
85
+ # Polimorfismo
86
+ results["Polimorfismo"] = len([
87
+ node for _, node in tree.filter(javalang.tree.MethodDeclaration)
88
+ if "Override" in (node.annotations or [])
89
+ ])
90
+
91
+ except Exception as e:
92
+ results["Erro"] = str(e)
93
+
94
+ return dict(results)
95
+
96
+ def process_files(files) -> List[Dict]:
97
+ """Processa múltiplos arquivos e analisa sintaxe e OO"""
98
+ analyzer = JavaSyntaxAnalyzer()
99
+ file_results = []
100
+
101
+ for file in files:
102
+ with open(file.name, 'r', encoding='utf-8') as f:
103
+ code = f.read()
104
+ syntax_results = analyzer.analyze_syntax(code)
105
+ oo_results = analyzer.analyze_oo(code)
106
+
107
+ combined_results = {**syntax_results, **oo_results}
108
+ combined_results["Arquivo"] = file.name
109
+ file_results.append(combined_results)
110
+
111
+ return file_results
112
+
113
+ # Interface Gradio
114
+ with gr.Blocks(title="JAVA-Inspector") as demo:
115
+ gr.Markdown("# OO Paradigm and Syntax Inspector for Java Code")
116
+ gr.Markdown("Suba os arquivos Java para destrinchar as estruturas sintáticas e orientadas a objetos.")
117
+
118
+ with gr.Row():
119
+ example_file_1 = gr.Button("Exemplo: Principal.java")
120
+ example_file_2 = gr.Button("Exemplo: Classe1.java")
121
+ example_file_3 = gr.Button("Exemplo: Classe2.java")
122
+
123
+ file_input = gr.File(label="Arquivos Java", file_types=[".java"], file_count="multiple")
124
+ output_table = gr.Dataframe(
125
+ label="Resultados",
126
+ headers=[
127
+ "Arquivo",
128
+ "Tipos Primitivos", "Constantes", "Variáveis Declaradas", "If/Else", "Switch/Case",
129
+ "For Loops", "While Loops", "Do-While Loops", "Aritméticos", "Comparação",
130
+ "Lógicos", "Atribuição", "System.out", "Scanner", "Concatenação", "Métodos de String",
131
+ "Classes", "Objetos", "Métodos", "Atributos", "Encapsulamento", "Herança", "Polimorfismo"
132
+ ]
133
+ )
134
+
135
+ def analyze_files(files):
136
+ results = process_files(files)
137
+ # Converte os resultados para uma lista de listas para exibição na tabela
138
+ formatted_results = [
139
+ [
140
+ result["Arquivo"],
141
+ result.get("Tipos Primitivos", 0),
142
+ result.get("Constantes (final)", 0),
143
+ result.get("Variáveis Declaradas", 0),
144
+ result.get("If/Else", 0),
145
+ result.get("Switch/Case", 0),
146
+ result.get("For Loops", 0),
147
+ result.get("While Loops", 0),
148
+ result.get("Do-While Loops", 0),
149
+ result.get("Aritméticos", 0),
150
+ result.get("Comparação", 0),
151
+ result.get("Lógicos", 0),
152
+ result.get("Atribuição", 0),
153
+ result.get("System.out.print", 0),
154
+ result.get("Scanner", 0),
155
+ result.get("Concatenação de Strings", 0),
156
+ result.get("Métodos de String", 0),
157
+ result.get("Classes", 0),
158
+ result.get("Objetos", 0),
159
+ result.get("Métodos", 0),
160
+ result.get("Atributos", 0),
161
+ result.get("Encapsulamento", 0),
162
+ result.get("Herança", 0),
163
+ result.get("Polimorfismo", 0),
164
+ ]
165
+ for result in results
166
+ ]
167
+ return formatted_results
168
+
169
+ analyze_button = gr.Button("Analisar Arquivos")
170
+ analyze_button.click(fn=analyze_files, inputs=file_input, outputs=output_table)
171
+
172
+ if __name__ == "__main__":
173
+ demo.launch(share=True)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio
2
+ javalang==0.13.0
3
+