File size: 4,514 Bytes
0006ea4
b101761
0006ea4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd8445d
0006ea4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5e3ff8
 
 
 
 
 
dd8445d
c5e3ff8
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import PlainTextResponse
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware 
from fastapi import Request
import joblib
import PyPDF2
import re
import logging
import tempfile
import os

app = FastAPI()


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

logging.basicConfig(level=logging.INFO)

try:
    model = joblib.load("react_classifier.joblib")
except Exception as e:
    logging.error(f"Erro ao carregar o modelo: {e}")
    raise

def clean_text(text):
    text = text.lower()
    text = re.sub(r'[^\w\s]', ' ', text)
    text = re.sub(r'\s+', ' ', text)
    return text.strip()

def extract_text_from_pdf(file_path):
    text = ""
    try:
        with open(file_path, 'rb') as f:
            reader = PyPDF2.PdfReader(f)
            for page in reader.pages:
                page_text = page.extract_text()
                if page_text:
                    text += page_text + "\n"
    except Exception as e:
        raise Exception(f"Erro ao extrair texto do PDF: {e}")
    return text

def avaliar_candidato(
    anosEstudoTecnologia: int,
    tempoDesenvolvedor: int,
    tempoExperiencia: int,
    nivelIngles: int,
    graduacao: int
) -> dict:
    score_estudo = anosEstudoTecnologia / 6
    score_desenvolv = tempoDesenvolvedor / 6
    score_experiencia = tempoExperiencia / 6
    score_ingles = nivelIngles / 4
    score_graduacao = graduacao / 7

    peso_estudo = 0.15
    peso_desenvolv = 0.2
    peso_experiencia = 0.3
    peso_ingles = 0.25
    peso_graduacao = 0.1

    score_final = (
        score_estudo * peso_estudo +
        score_desenvolv * peso_desenvolv +
        score_experiencia * peso_experiencia +
        score_ingles * peso_ingles +
        score_graduacao * peso_graduacao
    )

    score_percentual = round(score_final * 100, 2)
    aprovado = score_percentual >= 70.0

    return {
        "score": score_percentual,
        "aprovado": aprovado
    }


@app.post("/classificar")
async def classify_resume(file: UploadFile = File(...)):
    try:
        suffix = os.path.splitext(file.filename)[-1]
        with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp:
            temp.write(await file.read())
            temp_path = temp.name

        raw_text = extract_text_from_pdf(temp_path)
        cleaned = clean_text(raw_text)

        proba = model.predict_proba([cleaned])[0]
        prediction = model.predict([cleaned])[0]

        result = {
            "classificacao": "React Developer" if prediction == 1 else "Outra Área",
            "probabilidade": f"{proba[1]*100:.2f}%",
            "trecho_texto": cleaned[:500] + "..." if len(cleaned) > 500 else cleaned
        }

        return JSONResponse(content=result)

    except Exception as e:
        logging.error(f"Erro no processamento: {e}")
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        if 'temp_path' in locals() and os.path.exists(temp_path):
            os.remove(temp_path)

@app.post("/avaliar")
async def avaliar_formulario(request: Request):
    try:
        data = await request.json()

        resultado = avaliar_candidato(
            anosEstudoTecnologia=int(data.get("anosEstudoTecnologia", 0)),
            tempoDesenvolvedor=int(data.get("tempoDesenvolvedor", 0)),
            tempoExperiencia=int(data.get("tempoExperiencia", 0)),
            nivelIngles=int(data.get("nivelIngles", 0)),
            graduacao=int(data.get("graduacao", 0))
        )

        return JSONResponse(
            status_code=200,
            content={
                "avaliacao": "Aprovado" if resultado["aprovado"] else "Reprovado",
                "score": resultado["score"]
            }
        )
    except Exception as e:
        logging.error(f"Erro na avaliação do formulário: {e}")
        raise HTTPException(status_code=500, detail="Erro ao processar os dados.")

@app.get("/", response_class=PlainTextResponse)
async def root():
    return (
        "Esta API possui duas rotas POST:\n"
        " /classificar → espera um arquivo PDF de currículo\n"
        " /avaliar → espera um JSON como este:\n"
        '{\n'
        '  "anosEstudoTecnologia": 6,\n'
        '  "tempoDesenvolvedor": 6,\n'
        '  "tempoExperiencia": 6,\n'
        '  "nivelIngles": 3,\n'
        '  "graduacao": 7\n'
        '}\n'
    )