Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- README.md +46 -12
- app.py +446 -0
- requirements.txt +3 -0
README.md
CHANGED
|
@@ -1,12 +1,46 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# App Generator - Aplicação com IA Real
|
| 2 |
+
|
| 3 |
+
Esta aplicação permite gerar estruturas de aplicações e analisar código usando IA real através da API HuggingFace.
|
| 4 |
+
|
| 5 |
+
## Funcionalidades
|
| 6 |
+
|
| 7 |
+
### Gerador de Aplicações
|
| 8 |
+
- Crie estruturas de aplicações a partir de descrições em texto
|
| 9 |
+
- Obtenha sugestões de componentes frontend e backend
|
| 10 |
+
- Receba uma estrutura completa baseada na sua descrição
|
| 11 |
+
|
| 12 |
+
### Análise de Código
|
| 13 |
+
- Analise código em várias linguagens (Python, JavaScript, Java, etc.)
|
| 14 |
+
- Receba feedback sobre qualidade, problemas e sugestões de melhoria
|
| 15 |
+
- Escolha entre diferentes modelos de IA para análise
|
| 16 |
+
|
| 17 |
+
## Configuração
|
| 18 |
+
|
| 19 |
+
### Token HuggingFace (Opcional mas Recomendado)
|
| 20 |
+
|
| 21 |
+
Para obter resultados melhores, é recomendado configurar um token HuggingFace:
|
| 22 |
+
|
| 23 |
+
1. Crie uma conta em [huggingface.co](https://huggingface.co) se ainda não tiver
|
| 24 |
+
2. Aceda a [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) para gerar um token
|
| 25 |
+
3. Nas configurações do Space, adicione o token como uma variável secreta chamada `HF_TOKEN`
|
| 26 |
+
|
| 27 |
+
### Modelos Utilizados
|
| 28 |
+
|
| 29 |
+
Esta aplicação utiliza os seguintes modelos da HuggingFace:
|
| 30 |
+
- StarCoder 2 (15B) - `bigcode/starcoder2-15b`
|
| 31 |
+
- StarCoder 2 (7B) - `bigcode/starcoder2-7b`
|
| 32 |
+
- CodeBERT - `microsoft/codebert-base`
|
| 33 |
+
|
| 34 |
+
## Tecnologias
|
| 35 |
+
|
| 36 |
+
- Gradio: Interface de utilizador
|
| 37 |
+
- HuggingFace API: Modelos de IA para análise de código e geração de aplicações
|
| 38 |
+
- Python: Linguagem de programação principal
|
| 39 |
+
|
| 40 |
+
## Licença
|
| 41 |
+
|
| 42 |
+
Este projeto é open source e está disponível sob a licença MIT.
|
| 43 |
+
|
| 44 |
+
## Autor
|
| 45 |
+
|
| 46 |
+
Criado por JimmyNewton
|
app.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import requests
|
| 5 |
+
from huggingface_hub import InferenceClient
|
| 6 |
+
|
| 7 |
+
# Configuração da API HuggingFace
|
| 8 |
+
HF_TOKEN = os.environ.get('HF_TOKEN', '') # Token pode ser configurado como variável de ambiente
|
| 9 |
+
DEFAULT_CODE_MODEL = "bigcode/starcoder2-15b" # Modelo padrão para análise de código
|
| 10 |
+
|
| 11 |
+
def get_hf_client():
|
| 12 |
+
"""
|
| 13 |
+
Cria e retorna um cliente de inferência HuggingFace
|
| 14 |
+
"""
|
| 15 |
+
try:
|
| 16 |
+
client = InferenceClient(
|
| 17 |
+
model=DEFAULT_CODE_MODEL,
|
| 18 |
+
token=HF_TOKEN
|
| 19 |
+
)
|
| 20 |
+
return client
|
| 21 |
+
except Exception as e:
|
| 22 |
+
print(f"Erro ao criar cliente HuggingFace: {str(e)}")
|
| 23 |
+
return None
|
| 24 |
+
|
| 25 |
+
def analyze_code(code, language="python", model_id=DEFAULT_CODE_MODEL):
|
| 26 |
+
"""
|
| 27 |
+
Analisa código usando a API HuggingFace
|
| 28 |
+
"""
|
| 29 |
+
if not code:
|
| 30 |
+
return {
|
| 31 |
+
'success': False,
|
| 32 |
+
'message': 'É necessário fornecer o código para análise',
|
| 33 |
+
'analysis': None,
|
| 34 |
+
'language': language
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
# Criar prompt para análise de código
|
| 39 |
+
prompt = f"""
|
| 40 |
+
Analise o seguinte código {language}:
|
| 41 |
+
|
| 42 |
+
```{language}
|
| 43 |
+
{code}
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
Por favor, forneça:
|
| 47 |
+
1. Uma análise geral da qualidade do código
|
| 48 |
+
2. Identificação de possíveis bugs ou problemas
|
| 49 |
+
3. Sugestões de melhoria e boas práticas
|
| 50 |
+
4. Avaliação de segurança (se aplicável)
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
# Usar cliente HuggingFace para análise
|
| 54 |
+
client = get_hf_client()
|
| 55 |
+
|
| 56 |
+
if not client:
|
| 57 |
+
# Fallback para análise simulada se o cliente não estiver disponível
|
| 58 |
+
return {
|
| 59 |
+
'success': True,
|
| 60 |
+
'message': 'Análise de código realizada localmente (API HuggingFace não disponível)',
|
| 61 |
+
'analysis': {
|
| 62 |
+
'quality': 'Não foi possível conectar à API HuggingFace. Esta é uma análise simulada.',
|
| 63 |
+
'issues': ['API HuggingFace não disponível - token não configurado ou serviço indisponível'],
|
| 64 |
+
'suggestions': ['Configure o token HuggingFace como variável de ambiente para análise completa'],
|
| 65 |
+
'security': 'Não avaliado'
|
| 66 |
+
},
|
| 67 |
+
'language': language
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
# Fazer a chamada à API
|
| 71 |
+
response = client.text_generation(
|
| 72 |
+
prompt,
|
| 73 |
+
max_new_tokens=500,
|
| 74 |
+
temperature=0.3,
|
| 75 |
+
top_p=0.95,
|
| 76 |
+
repetition_penalty=1.2
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# Processar a resposta
|
| 80 |
+
analysis_text = response
|
| 81 |
+
|
| 82 |
+
# Tentar extrair seções da resposta
|
| 83 |
+
quality = "Análise realizada com sucesso"
|
| 84 |
+
issues = []
|
| 85 |
+
suggestions = []
|
| 86 |
+
security = "Verificado"
|
| 87 |
+
|
| 88 |
+
# Análise básica do texto para extrair seções
|
| 89 |
+
if "qualidade" in analysis_text.lower():
|
| 90 |
+
quality_section = analysis_text.lower().split("qualidade")[1].split("\n")[0]
|
| 91 |
+
quality = quality_section[:100] + "..." if len(quality_section) > 100 else quality_section
|
| 92 |
+
|
| 93 |
+
if "problemas" in analysis_text.lower() or "bugs" in analysis_text.lower():
|
| 94 |
+
issues_text = analysis_text.lower().split("problemas")[1].split("sugestões")[0] if "problemas" in analysis_text.lower() else analysis_text.lower().split("bugs")[1].split("sugestões")[0]
|
| 95 |
+
issues = [issue.strip() for issue in issues_text.split("-") if issue.strip()]
|
| 96 |
+
|
| 97 |
+
if "sugestões" in analysis_text.lower():
|
| 98 |
+
suggestions_text = analysis_text.lower().split("sugestões")[1].split("segurança")[0] if "segurança" in analysis_text.lower() else analysis_text.lower().split("sugestões")[1]
|
| 99 |
+
suggestions = [suggestion.strip() for suggestion in suggestions_text.split("-") if suggestion.strip()]
|
| 100 |
+
|
| 101 |
+
if "segurança" in analysis_text.lower():
|
| 102 |
+
security_section = analysis_text.lower().split("segurança")[1].split("\n")[0]
|
| 103 |
+
security = security_section[:100] + "..." if len(security_section) > 100 else security_section
|
| 104 |
+
|
| 105 |
+
analysis = {
|
| 106 |
+
'raw_response': analysis_text,
|
| 107 |
+
'quality': quality,
|
| 108 |
+
'issues': issues[:5], # Limitar a 5 issues
|
| 109 |
+
'suggestions': suggestions[:5], # Limitar a 5 sugestões
|
| 110 |
+
'security': security
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
return {
|
| 114 |
+
'success': True,
|
| 115 |
+
'message': 'Código analisado com sucesso',
|
| 116 |
+
'analysis': analysis,
|
| 117 |
+
'language': language
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
except Exception as e:
|
| 121 |
+
return {
|
| 122 |
+
'success': False,
|
| 123 |
+
'message': f'Erro ao analisar código: {str(e)}',
|
| 124 |
+
'analysis': None,
|
| 125 |
+
'language': language
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
def get_supported_models():
|
| 129 |
+
"""
|
| 130 |
+
Retorna lista de modelos suportados para análise de código
|
| 131 |
+
"""
|
| 132 |
+
# Lista de modelos recomendados para análise de código
|
| 133 |
+
models = [
|
| 134 |
+
{
|
| 135 |
+
"id": "bigcode/starcoder2-15b",
|
| 136 |
+
"name": "StarCoder 2 (15B)",
|
| 137 |
+
"description": "Modelo especializado em código com 15B de parâmetros",
|
| 138 |
+
"languages": ["python", "javascript", "java", "c++", "php", "ruby", "go", "rust"]
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"id": "bigcode/starcoder2-7b",
|
| 142 |
+
"name": "StarCoder 2 (7B)",
|
| 143 |
+
"description": "Versão mais leve do StarCoder com 7B de parâmetros",
|
| 144 |
+
"languages": ["python", "javascript", "java", "c++", "php", "ruby", "go", "rust"]
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"id": "microsoft/codebert-base",
|
| 148 |
+
"name": "CodeBERT",
|
| 149 |
+
"description": "Modelo pré-treinado para compreensão de código",
|
| 150 |
+
"languages": ["python", "javascript", "java", "c#", "php", "go"]
|
| 151 |
+
}
|
| 152 |
+
]
|
| 153 |
+
|
| 154 |
+
return models
|
| 155 |
+
|
| 156 |
+
def generate_app_structure(prompt):
|
| 157 |
+
"""
|
| 158 |
+
Gera estrutura de aplicação com base no prompt usando a API HuggingFace
|
| 159 |
+
"""
|
| 160 |
+
try:
|
| 161 |
+
client = get_hf_client()
|
| 162 |
+
|
| 163 |
+
if not client:
|
| 164 |
+
# Fallback para geração simulada
|
| 165 |
+
return {
|
| 166 |
+
"type": "web_application",
|
| 167 |
+
"components": [
|
| 168 |
+
{
|
| 169 |
+
"type": "frontend",
|
| 170 |
+
"framework": "React",
|
| 171 |
+
"pages": [
|
| 172 |
+
{"name": "Home", "path": "/"},
|
| 173 |
+
{"name": "About", "path": "/about"},
|
| 174 |
+
{"name": "Contact", "path": "/contact"}
|
| 175 |
+
]
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"type": "backend",
|
| 179 |
+
"framework": "Flask",
|
| 180 |
+
"endpoints": [
|
| 181 |
+
{"path": "/api/data", "method": "GET"},
|
| 182 |
+
{"path": "/api/submit", "method": "POST"}
|
| 183 |
+
]
|
| 184 |
+
}
|
| 185 |
+
],
|
| 186 |
+
"description": f"Aplicação gerada com base no prompt: {prompt}"
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
# Criar prompt para geração de estrutura
|
| 190 |
+
generation_prompt = f"""
|
| 191 |
+
Crie uma estrutura de aplicação web com base na seguinte descrição:
|
| 192 |
+
|
| 193 |
+
"{prompt}"
|
| 194 |
+
|
| 195 |
+
Responda apenas com um objeto JSON válido com a seguinte estrutura:
|
| 196 |
+
{{
|
| 197 |
+
"type": "web_application",
|
| 198 |
+
"components": [
|
| 199 |
+
{{
|
| 200 |
+
"type": "frontend",
|
| 201 |
+
"framework": "string",
|
| 202 |
+
"pages": [
|
| 203 |
+
{{"name": "string", "path": "string"}}
|
| 204 |
+
]
|
| 205 |
+
}},
|
| 206 |
+
{{
|
| 207 |
+
"type": "backend",
|
| 208 |
+
"framework": "string",
|
| 209 |
+
"endpoints": [
|
| 210 |
+
{{"path": "string", "method": "string"}}
|
| 211 |
+
]
|
| 212 |
+
}}
|
| 213 |
+
],
|
| 214 |
+
"description": "string"
|
| 215 |
+
}}
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
# Fazer a chamada à API
|
| 219 |
+
response = client.text_generation(
|
| 220 |
+
generation_prompt,
|
| 221 |
+
max_new_tokens=800,
|
| 222 |
+
temperature=0.7,
|
| 223 |
+
top_p=0.95
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
# Tentar extrair JSON da resposta
|
| 227 |
+
try:
|
| 228 |
+
# Encontrar o início e fim do JSON na resposta
|
| 229 |
+
start_idx = response.find('{')
|
| 230 |
+
end_idx = response.rfind('}') + 1
|
| 231 |
+
|
| 232 |
+
if start_idx >= 0 and end_idx > start_idx:
|
| 233 |
+
json_str = response[start_idx:end_idx]
|
| 234 |
+
app_structure = json.loads(json_str)
|
| 235 |
+
return app_structure
|
| 236 |
+
else:
|
| 237 |
+
# Fallback para estrutura padrão
|
| 238 |
+
return {
|
| 239 |
+
"type": "web_application",
|
| 240 |
+
"components": [
|
| 241 |
+
{
|
| 242 |
+
"type": "frontend",
|
| 243 |
+
"framework": "React",
|
| 244 |
+
"pages": [
|
| 245 |
+
{"name": "Home", "path": "/"},
|
| 246 |
+
{"name": "Dashboard", "path": "/dashboard"}
|
| 247 |
+
]
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"type": "backend",
|
| 251 |
+
"framework": "Flask",
|
| 252 |
+
"endpoints": [
|
| 253 |
+
{"path": "/api/data", "method": "GET"},
|
| 254 |
+
{"path": "/api/submit", "method": "POST"}
|
| 255 |
+
]
|
| 256 |
+
}
|
| 257 |
+
],
|
| 258 |
+
"description": f"Aplicação gerada com base no prompt: {prompt}"
|
| 259 |
+
}
|
| 260 |
+
except:
|
| 261 |
+
# Fallback para estrutura padrão em caso de erro no parsing
|
| 262 |
+
return {
|
| 263 |
+
"type": "web_application",
|
| 264 |
+
"components": [
|
| 265 |
+
{
|
| 266 |
+
"type": "frontend",
|
| 267 |
+
"framework": "React",
|
| 268 |
+
"pages": [
|
| 269 |
+
{"name": "Home", "path": "/"},
|
| 270 |
+
{"name": "Features", "path": "/features"}
|
| 271 |
+
]
|
| 272 |
+
},
|
| 273 |
+
{
|
| 274 |
+
"type": "backend",
|
| 275 |
+
"framework": "Flask",
|
| 276 |
+
"endpoints": [
|
| 277 |
+
{"path": "/api/data", "method": "GET"}
|
| 278 |
+
]
|
| 279 |
+
}
|
| 280 |
+
],
|
| 281 |
+
"description": f"Aplicação gerada com base no prompt: {prompt}"
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
except Exception as e:
|
| 285 |
+
# Estrutura padrão em caso de erro
|
| 286 |
+
return {
|
| 287 |
+
"type": "web_application",
|
| 288 |
+
"components": [
|
| 289 |
+
{
|
| 290 |
+
"type": "frontend",
|
| 291 |
+
"framework": "React",
|
| 292 |
+
"pages": [
|
| 293 |
+
{"name": "Home", "path": "/"}
|
| 294 |
+
]
|
| 295 |
+
},
|
| 296 |
+
{
|
| 297 |
+
"type": "backend",
|
| 298 |
+
"framework": "Flask",
|
| 299 |
+
"endpoints": [
|
| 300 |
+
{"path": "/api/data", "method": "GET"}
|
| 301 |
+
]
|
| 302 |
+
}
|
| 303 |
+
],
|
| 304 |
+
"description": f"Erro na geração: {str(e)}"
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
# Interface Gradio para análise de código
|
| 308 |
+
def code_analysis_interface(code, language, model_id):
|
| 309 |
+
result = analyze_code(code, language, model_id)
|
| 310 |
+
|
| 311 |
+
if not result['success']:
|
| 312 |
+
return f"Erro: {result['message']}"
|
| 313 |
+
|
| 314 |
+
analysis = result['analysis']
|
| 315 |
+
|
| 316 |
+
output = f"## Análise de Código ({language})\n\n"
|
| 317 |
+
output += f"### Qualidade Geral\n{analysis['quality']}\n\n"
|
| 318 |
+
|
| 319 |
+
if analysis['issues']:
|
| 320 |
+
output += "### Problemas Identificados\n"
|
| 321 |
+
for issue in analysis['issues']:
|
| 322 |
+
output += f"- {issue}\n"
|
| 323 |
+
output += "\n"
|
| 324 |
+
|
| 325 |
+
if analysis['suggestions']:
|
| 326 |
+
output += "### Sugestões de Melhoria\n"
|
| 327 |
+
for suggestion in analysis['suggestions']:
|
| 328 |
+
output += f"- {suggestion}\n"
|
| 329 |
+
output += "\n"
|
| 330 |
+
|
| 331 |
+
output += f"### Segurança\n{analysis['security']}\n\n"
|
| 332 |
+
|
| 333 |
+
return output
|
| 334 |
+
|
| 335 |
+
# Interface Gradio para geração de aplicação
|
| 336 |
+
def app_generation_interface(prompt):
|
| 337 |
+
app_structure = generate_app_structure(prompt)
|
| 338 |
+
|
| 339 |
+
output = f"## Aplicação Gerada\n\n"
|
| 340 |
+
output += f"### Descrição\n{app_structure['description']}\n\n"
|
| 341 |
+
|
| 342 |
+
output += "### Estrutura\n"
|
| 343 |
+
output += f"Tipo: {app_structure['type']}\n\n"
|
| 344 |
+
|
| 345 |
+
for component in app_structure['components']:
|
| 346 |
+
output += f"#### {component['type'].capitalize()}\n"
|
| 347 |
+
output += f"Framework: {component['framework']}\n\n"
|
| 348 |
+
|
| 349 |
+
if component['type'] == 'frontend':
|
| 350 |
+
output += "Páginas:\n"
|
| 351 |
+
for page in component['pages']:
|
| 352 |
+
output += f"- {page['name']}: {page['path']}\n"
|
| 353 |
+
output += "\n"
|
| 354 |
+
|
| 355 |
+
if component['type'] == 'backend':
|
| 356 |
+
output += "Endpoints:\n"
|
| 357 |
+
for endpoint in component['endpoints']:
|
| 358 |
+
output += f"- {endpoint['path']} ({endpoint['method']})\n"
|
| 359 |
+
output += "\n"
|
| 360 |
+
|
| 361 |
+
return output
|
| 362 |
+
|
| 363 |
+
# Interface principal
|
| 364 |
+
with gr.Blocks(title="App Generator - IA Real") as demo:
|
| 365 |
+
gr.Markdown("# App Generator - Crie aplicações com IA")
|
| 366 |
+
gr.Markdown("Crie aplicações incríveis com IA, a partir de prompts, imagens ou ficheiros")
|
| 367 |
+
|
| 368 |
+
with gr.Tabs():
|
| 369 |
+
with gr.TabItem("Gerador de Aplicações"):
|
| 370 |
+
with gr.Row():
|
| 371 |
+
with gr.Column():
|
| 372 |
+
prompt_input = gr.Textbox(
|
| 373 |
+
label="Descrição da Aplicação",
|
| 374 |
+
placeholder="Ex: Uma aplicação de lista de tarefas com autenticação de utilizadores",
|
| 375 |
+
lines=5
|
| 376 |
+
)
|
| 377 |
+
generate_btn = gr.Button("Gerar Aplicação")
|
| 378 |
+
app_output = gr.Markdown(label="Resultado")
|
| 379 |
+
|
| 380 |
+
generate_btn.click(
|
| 381 |
+
fn=app_generation_interface,
|
| 382 |
+
inputs=[prompt_input],
|
| 383 |
+
outputs=[app_output]
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
with gr.TabItem("Análise de Código"):
|
| 387 |
+
with gr.Row():
|
| 388 |
+
with gr.Column(scale=2):
|
| 389 |
+
language_select = gr.Dropdown(
|
| 390 |
+
choices=["python", "javascript", "java", "c++", "php", "ruby", "go", "rust"],
|
| 391 |
+
value="python",
|
| 392 |
+
label="Linguagem"
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
code_input = gr.Textbox(
|
| 396 |
+
label="Código para Análise",
|
| 397 |
+
placeholder="Cole seu código aqui para análise...",
|
| 398 |
+
lines=10
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
model_select = gr.Dropdown(
|
| 402 |
+
choices=[
|
| 403 |
+
"bigcode/starcoder2-15b",
|
| 404 |
+
"bigcode/starcoder2-7b",
|
| 405 |
+
"microsoft/codebert-base"
|
| 406 |
+
],
|
| 407 |
+
value="bigcode/starcoder2-15b",
|
| 408 |
+
label="Modelo de IA"
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
analyze_btn = gr.Button("Analisar Código")
|
| 412 |
+
analysis_output = gr.Markdown(label="Resultado da Análise")
|
| 413 |
+
|
| 414 |
+
analyze_btn.click(
|
| 415 |
+
fn=code_analysis_interface,
|
| 416 |
+
inputs=[code_input, language_select, model_select],
|
| 417 |
+
outputs=[analysis_output]
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
with gr.Column(scale=1):
|
| 421 |
+
gr.Markdown("### Sobre a Análise de Código")
|
| 422 |
+
gr.Markdown("""
|
| 423 |
+
Esta funcionalidade utiliza a API HuggingFace para analisar código em tempo real.
|
| 424 |
+
|
| 425 |
+
**Modelos disponíveis:**
|
| 426 |
+
- StarCoder 2 (15B): Modelo especializado em código com 15B de parâmetros
|
| 427 |
+
- StarCoder 2 (7B): Versão mais leve do StarCoder
|
| 428 |
+
- CodeBERT: Modelo pré-treinado para compreensão de código
|
| 429 |
+
|
| 430 |
+
**Linguagens suportadas:**
|
| 431 |
+
Python, JavaScript, Java, C++, PHP, Ruby, Go, Rust
|
| 432 |
+
|
| 433 |
+
Para resultados mais precisos, configure um token HuggingFace nas variáveis de ambiente.
|
| 434 |
+
""")
|
| 435 |
+
|
| 436 |
+
gr.Markdown("### Sobre o App Generator")
|
| 437 |
+
gr.Markdown("""
|
| 438 |
+
App Generator é uma aplicação open source que utiliza IA para gerar estruturas de aplicações e analisar código.
|
| 439 |
+
|
| 440 |
+
Desenvolvido com Gradio e HuggingFace, este projeto é totalmente gratuito e open source.
|
| 441 |
+
|
| 442 |
+
© 2025 App Generator - Licenciado sob MIT License
|
| 443 |
+
""")
|
| 444 |
+
|
| 445 |
+
# Iniciar a aplicação
|
| 446 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==4.12.0
|
| 2 |
+
huggingface_hub==0.20.3
|
| 3 |
+
requests==2.31.0
|