Spaces:
Sleeping
Sleeping
Download app.py from Anaceu/poketest-lab-api: direct link, hf CLI and curl.
- Browser
- Download file 5.62 kB
-
https://huggingface.co/spaces/Anaceu/poketest-lab-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/Anaceu/poketest-lab-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Anaceu/poketest-lab-api/resolve/main/app.py
5.62 kB
| from transformers import pipeline | |
| import gradio as gr | |
| import re | |
| # Inicializar o pipeline de geração de texto | |
| pipe = pipeline( | |
| "text-generation", | |
| model="Salesforce/codegen-350M-mono", | |
| device="cpu", | |
| max_length=300 | |
| ) | |
| def generate_test_and_explanation(javascript_code, error_message=None): | |
| """ | |
| Se apenas javascript_code for fornecido, gere e retorne um arquivo de teste Jest. | |
| Se error_message também for fornecido, gere e retorne uma explicação amigável. | |
| """ | |
| try: | |
| # Missão 1: gerar teste Jest | |
| if error_message is None or error_message.strip() == "": | |
| # Extrai nome da função | |
| func_match = re.search(r'function\s+(\w+)', javascript_code) | |
| func_name = func_match.group(1) if func_match else "myFunction" | |
| # Prompt detalhado que força a IA a analisar o código | |
| prompt = f"""Analyze this JavaScript function and write comprehensive Jest tests: | |
| {javascript_code} | |
| Write Jest tests that: | |
| 1. Test the actual behavior of this specific function | |
| 2. Use realistic input data based on what the function expects | |
| 3. Test edge cases and error conditions | |
| 4. Verify the correct return values | |
| const {{ {func_name} }} = require('./module'); | |
| describe('{func_name}', () => {{""" | |
| out = pipe(prompt, max_new_tokens=200, num_return_sequences=1, temperature=0.4, do_sample=True, pad_token_id=50256) | |
| generated_text = out[0]["generated_text"] | |
| # Extrai apenas a parte dos testes | |
| if "describe(" in generated_text: | |
| test_part = generated_text.split("describe(")[1] if generated_text.count("describe(") > 1 else generated_text.split("describe(")[-1] | |
| # Reconstrói o teste completo | |
| full_test = f"""const {{ {func_name} }} = require('./module'); | |
| describe('{func_name}', () => {{{test_part}""" | |
| return full_test | |
| # Se não conseguiu extrair, tenta uma segunda abordagem | |
| prompt2 = f"""Generate Jest test for this function: | |
| {javascript_code} | |
| Test should use proper parameters and expectations: | |
| test('works correctly', () => {{ | |
| const result = {func_name}(""" | |
| out2 = pipe(prompt2, max_new_tokens=150, temperature=0.3) | |
| generated_text2 = out2[0]["generated_text"] | |
| # Extrai o teste | |
| if "test(" in generated_text2: | |
| test_content = generated_text2.split("test(")[1] if generated_text2.count("test(") > 1 else generated_text2.split("test(")[-1] | |
| return f"""const {{ {func_name} }} = require('./module'); | |
| describe('{func_name}', () => {{ | |
| test({test_content} | |
| }});""" | |
| # Fallback apenas se tudo falhar | |
| return f"""const {{ {func_name} }} = require('./module'); | |
| describe('{func_name}', () => {{ | |
| test('should work correctly', () => {{ | |
| // TODO: Add proper test implementation | |
| const result = {func_name}(); | |
| expect(result).toBeDefined(); | |
| }}); | |
| }});""" | |
| # Missão 2: explicar o teste reprovado | |
| prompt = f"Professor Carvalho explica erro JavaScript:\nCódigo: {javascript_code}\nErro: {error_message}\nExplicação:" | |
| out = pipe(prompt, max_length=200, num_return_sequences=1, temperature=0.7) | |
| explanation = out[0]["generated_text"].replace(prompt, "").strip() | |
| # Se a explicação estiver muito curta, usar fallback | |
| if len(explanation) < 15: | |
| explanation = "Olá, jovem treinador! Parece que seu código tem um problema de escopo. Tente usar 'let' ao invés de 'var' no loop. Como um Pokémon que precisa evoluir, seu código só precisa de um pequeno ajuste!" | |
| else: | |
| explanation = f"Professor Carvalho diz: {explanation}" | |
| return explanation | |
| except Exception as e: | |
| print(f"Erro interno do pipeline: {e}") | |
| if error_message: | |
| return "Desculpe, o laboratório do Professor Carvalho está temporariamente indisponível." | |
| else: | |
| return "// Erro ao gerar teste - tente novamente" | |
| # Interface Gradio | |
| with gr.Blocks(css=".gradio-container {background-color: #252526;}") as demo: | |
| gr.Markdown("# PokéTest Lab: Núcleo de IA", elem_classes="titulo") | |
| with gr.Tabs(): | |
| # Aba: Gerar teste Jest | |
| with gr.TabItem("Gerador de Testes"): | |
| js_input = gr.Code(label="Código JavaScript", language="javascript", lines=10) | |
| jest_output = gr.Code(label="Teste Jest gerado", language="javascript", lines=10, interactive=False) | |
| gen_btn = gr.Button("Gerar Teste") | |
| gen_btn.click( | |
| fn=generate_test_and_explanation, | |
| inputs=[js_input], | |
| outputs=[jest_output], | |
| api_name="gerar_teste" | |
| ) | |
| # Aba: Explicar erro | |
| with gr.TabItem("Explicador de erro"): | |
| js_input_err = gr.Code(label="Código JavaScript com bugs", language="javascript", lines=8) | |
| err_input = gr.Textbox(label="Mensagem de erro de teste", lines=4) | |
| explanation_output = gr.Textbox(label="Conselho do Professor Carvalho", lines=5, interactive=False) | |
| exp_btn = gr.Button("Obter Ajuda") | |
| exp_btn.click( | |
| fn=generate_test_and_explanation, | |
| inputs=[js_input_err, err_input], | |
| outputs=[explanation_output], | |
| api_name="explicar_erro" | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |