From ac695c9d14d8c4c830d978aae33ab02385ce6ff4 Mon Sep 17 00:00:00 2001 From: admtracksteel Date: Tue, 23 Jun 2026 19:51:32 +0000 Subject: [PATCH] feat: inject local standards database context into main certificate analysis prompt --- App.tsx | 17 ++- services/aiService.ts | 265 ++++++++++++++---------------------------- 2 files changed, 101 insertions(+), 181 deletions(-) diff --git a/App.tsx b/App.tsx index 9342aab..feba76c 100644 --- a/App.tsx +++ b/App.tsx @@ -146,12 +146,27 @@ const App: React.FC = () => { setError(null); setReportsData(null); try { + // Load local standards database + let standardsContext = undefined; + try { + const stdRes = await fetch('/api/standards'); + if (stdRes.ok) { + const standards = await stdRes.json(); + if (standards && standards.length > 0) { + standardsContext = standards; + } + } + } catch (err) { + console.warn("Could not load local standards database:", err); + } + const data = await analyzeCertificate({ provider, apiKey, model, file, - endpoint: provider === 'ollama' ? endpoint : undefined + endpoint: provider === 'ollama' ? endpoint : undefined, + standardsContext }); setReportsData(data); } catch (err) { diff --git a/services/aiService.ts b/services/aiService.ts index 1418e56..8629561 100644 --- a/services/aiService.ts +++ b/services/aiService.ts @@ -8,6 +8,7 @@ interface AnalyzeOptions { model: string; file: File; endpoint?: string; + standardsContext?: any[]; } const fileToGenerativePart = async (file: File) => { @@ -24,12 +25,10 @@ const fileToGenerativePart = async (file: File) => { const cleanAndParseJson = (jsonString: string): any => { let cleanedString = jsonString.trim(); - // Tenta encontrar um bloco markdown com json const jsonMatch = cleanedString.match(/```(?:json)?\s*([\s\S]*?)\s*```/i); if (jsonMatch) { cleanedString = jsonMatch[1].trim(); } else { - // Se não tiver crases, tenta encontrar o primeiro { e o último } const startIndex = cleanedString.indexOf('{'); const endIndex = cleanedString.lastIndexOf('}'); if (startIndex !== -1 && endIndex !== -1) { @@ -40,7 +39,6 @@ const cleanAndParseJson = (jsonString: string): any => { try { const parsed = JSON.parse(cleanedString); let finalData = parsed; - // Se o modelo aninhou os dados dentro de uma chave "report" ou "reports" if (parsed.reports) { finalData = parsed.reports; } else if (parsed.report && !parsed.identification) { @@ -60,32 +58,32 @@ const reportSchema = { identification: { type: Type.OBJECT, properties: { - product: { type: Type.STRING, description: "Nome do produto/material (ex: Chapa de Aço)." }, - standards: { type: Type.STRING, description: "Norma(s) principal(is) citada(s) no certificado." }, - manufacturer: { type: Type.STRING, description: "Nome do fabricante ou revendedor." }, - certificateNumber: { type: Type.STRING, description: "Número do certificado." }, - certificateDate: { type: Type.STRING, description: "Data do certificado." }, - batches: { type: Type.STRING, description: "Lista de lotes (batches)." }, - heats: { type: Type.STRING, description: "Lista de corridas (heats)." }, - quantity: { type: Type.STRING, description: "Volume, peso ou medida do material." }, + product: { type: Type.STRING }, + standards: { type: Type.STRING }, + manufacturer: { type: Type.STRING }, + certificateNumber: { type: Type.STRING }, + certificateDate: { type: Type.STRING }, + batches: { type: Type.STRING }, + heats: { type: Type.STRING }, + quantity: { type: Type.STRING } }, required: ["product", "standards", "manufacturer", "certificateNumber", "certificateDate", "batches", "heats", "quantity"] }, compliance: { type: Type.OBJECT, properties: { - status: { type: Type.STRING, enum: ["CONFORME", "NÃO CONFORME"], description: "Status geral de conformidade." }, - nonComplianceReason: { type: Type.STRING, description: "Se o status for 'NÃO CONFORME', explique detalhadamente o motivo da não conformidade, citando quais propriedades ou elementos químicos falharam e quais eram os limites da norma técnica analisada. Se for 'CONFORME', retorne uma string vazia." }, + status: { type: Type.STRING, description: "'CONFORME' ou 'NÃO CONFORME'" }, + nonComplianceReason: { type: Type.STRING }, mechanical: { type: Type.ARRAY, items: { type: Type.OBJECT, properties: { - property: { type: Type.STRING, description: "Propriedade mecânica (ex: Limite de Escoamento)." }, - norm: { type: Type.STRING, description: "Valor exigido pela norma (ex: Mín: 350 MPa)." }, - certificate: { type: Type.STRING, description: "Valor encontrado no certificado." }, - status: { type: Type.STRING, enum: ["OK", "FALHA"], description: "Status da propriedade." }, - differencePercentage: { type: Type.STRING, description: "Calculated percentage difference. MUST use strict formula: ((Certificate_Value - Norm_Value) / Norm_Value) * 100. E.g., if Norm=345 and Cert=404 -> '+17.1%'" } + property: { type: Type.STRING }, + norm: { type: Type.STRING }, + certificate: { type: Type.STRING }, + status: { type: Type.STRING, description: "'OK' ou 'REPROVADO'" }, + differencePercentage: { type: Type.STRING } }, required: ["property", "norm", "certificate", "status", "differencePercentage"] } @@ -95,10 +93,10 @@ const reportSchema = { items: { type: Type.OBJECT, properties: { - element: { type: Type.STRING, description: "Elemento químico (ex: Carbono (C))." }, - norm: { type: Type.STRING, description: "Valor exigido pela norma (ex: Máx: 0.25%)." }, - certificate: { type: Type.STRING, description: "Valor encontrado no certificado." }, - status: { type: Type.STRING, enum: ["OK", "FALHA"], description: "Status do elemento." }, + element: { type: Type.STRING }, + norm: { type: Type.STRING }, + certificate: { type: Type.STRING }, + status: { type: Type.STRING, description: "'OK' ou 'REPROVADO'" } }, required: ["element", "norm", "certificate", "status"] } @@ -108,36 +106,35 @@ const reportSchema = { items: { type: Type.OBJECT, properties: { - test: { type: Type.STRING, description: "Outro teste relevante (ex: Teste de Impacto Charpy)." }, - norm: { type: Type.STRING, description: "Valor exigido pela norma." }, - certificate: { type: Type.STRING, description: "Valor encontrado no certificado." }, - status: { type: Type.STRING, enum: ["OK", "FALHA"], description: "Status do teste." }, + test: { type: Type.STRING }, + result: { type: Type.STRING }, + status: { type: Type.STRING } }, - required: ["test", "norm", "certificate", "status"] + required: ["test", "result", "status"] } } }, - required: ["status", "mechanical", "chemical", "otherTests"] + required: ["status", "nonComplianceReason", "mechanical", "chemical", "otherTests"] }, overPerformance: { type: Type.ARRAY, items: { type: Type.OBJECT, properties: { - property: { type: Type.STRING, description: "Ponto-chave de superdesempenho." }, - value: { type: Type.STRING, description: "Percentual acima do mínimo normativo (ex: 12.5%)." }, + property: { type: Type.STRING }, + performance: { type: Type.STRING } }, - required: ["property", "value"] + required: ["property", "performance"] }, - description: "Lista de pontos onde o material excede os requisitos mínimos. Preencher apenas se o status for 'CONFORME'." + description: "Propriedades que superam os mínimos da norma em mais de 10%." }, equivalents: { type: Type.ARRAY, items: { type: Type.OBJECT, properties: { - system: { type: Type.STRING, description: "Sistema da norma (ex: EN (Europa))." }, - norm: { type: Type.STRING, description: "Norma equivalente (ex: S355J2)." }, + system: { type: Type.STRING, description: "ex: ISO, SAE, DIN" }, + norm: { type: Type.STRING } }, required: ["system", "norm"] }, @@ -152,29 +149,31 @@ const arraySchema = { items: reportSchema }; -const PROMPT_BASE = `Você é o "SteelCheck", um especialista sênior em engenharia de materiais, metalurgia, calibração e controle de qualidade industrial. +export const buildAnalysisPrompt = (standardsContext?: any[]) => { + let prompt = `Você é o "SteelCheck", um especialista sênior em engenharia de materiais, metalurgia, calibração e controle de qualidade industrial. Sua tarefa principal é transcrever com precisão matemática e zero alucinação os dados de um Certificado de Qualidade (Mill Test Report) e gerar um "Relatório de Análise Técnica" em formato JSON. ### DIRETRIZES RÍGIDAS DE TRANSCRIÇÃO (OCR DE ALTA PRECISÃO): -1. **Zero Alucinação de Normas:** No campo "standards", extraia APENAS e EXATAMENTE o que estiver escrito na imagem (ex: no campo "NORMA - ESPECIFICAÇAO - QUALIDADE / NORM - SPECIFICATION - GRADE"). Se o certificado diz "ASTM A572 GR50 / NBR7007 AR350", transcreva exatamente isso. NUNCA adicione normas equivalentes (como "ASTM A992") se elas não estiverem impressas explicitamente no papel do certificado. -2. **Extração de Identificação:** - - **Número do Certificado (certificateNumber):** Procure atentamente por campos como "NUMERO / NUMBER" ou "CERTIFICADO Nº". No certificado exemplo, o número é "8183321347/000010". Não confunda com Nota Fiscal ("NF") ou Pedido ("Customer Order"). Nunca retorne "N/A" ou "#N/A" se houver um número legível no topo. - - **Peso / Quantidade (quantity):** Transcreva exatamente a quantidade total (ex: "8,560 T" no campo "QTD / QUANT"). Não confunda dígitos (ex: "8" com "0", resultando em "0,960"). - - **Corrida / Lote (heats / batches):** Transcreva o número exato do Lote/Corrida (ex: "2715275435"). Verifique cada dígito duas vezes para não confundir "7" com "1", "5" com "6", etc. -3. **Mapeamento Preciso de Colunas (Tabela Lateral/Horizontal):** - - Certificados metalúrgicos costumam ter tabelas muito largas (muitas colunas). Faça um rastreamento visual preciso de cada linha, coluna por coluna, da esquerda para a direita. - - **Composição Química (chemical):** Mapeie cada elemento à sua respectiva coluna (C, Mn, Si, P, S, Cu, Cr, Nb, Ni, V, etc.). Não pule colunas nem misture a ordem (ex: se a coluna do Enxofre "S" vem antes de Fósforo "P", certifique-se de associar o valor correto de cada um). - - **Propriedades Mecânicas (mechanical):** - - "LE" significa Limite de Escoamento (Yield Strength). - - "LR" significa Limite de Resistência / Tração (Tensile Strength). - - "Along" significa Alongamento (Elongation). - - Transcreva os valores reais do certificado (ex: LE "415", LR "547"). Não chute valores médios ou mínimos da norma (como 368 ou 505) se no papel estão escritos outros números. -4. **Múltiplas Linhas de Teste por Lote/Corrida:** Se houver múltiplas linhas de testes mecânicos ou químicos independentes para o mesmo lote/corrida, gere um objeto de relatório independente no array JSON para CADA linha de teste, copiando os dados de identificação e cabeçalho para ambos. Isso garante que nenhum resultado de ensaio seja perdido. -5. **Orientação da Imagem:** A imagem pode estar rotacionada. Rotacione mentalmente e leia na direção correta. +1. **Zero Alucinação de Normas:** No campo "standards", extraia APENAS e EXATAMENTE o que estiver escrito na imagem. +2. **Extração de Identificação:** Transcreva números de certificado, lotes, corridas e quantidades exatamente como aparecem. +3. **Mapeamento Preciso de Colunas:** Mapeie composição química e propriedades mecânicas com precisão absoluta. +4. **Múltiplas Linhas:** Se houver múltiplas linhas de teste, gere um objeto para cada uma. +5. **Orientação:** Rotacione mentalmente a imagem para ler corretamente. ### ANÁLISE DE CONFORMIDADE: -- Compare os valores reais extraídos com os requisitos mínimos/máximos da norma técnica declarada no certificado (ex: para o ASTM A572 Grau 50, o limite de escoamento LE mínimo é 345 MPa e o limite de resistência LR mínimo é 450 MPa; para NBR 7007 AR350, o LE mínimo é 350 MPa e o LR mínimo é 450 MPa). +- Compare os valores reais extraídos com os requisitos mínimos/máximos da norma técnica declarada no certificado.`; + + if (standardsContext && standardsContext.length > 0) { + prompt += `\n\n=== BANCO DE NORMAS LOCAL (USO OBRIGATÓRIO) ===\n`; + prompt += `Você DEVE utilizar as regras rígidas do seguinte banco de dados local para confrontar e validar os resultados do certificado. SE a norma citada no laudo estiver presente na lista abaixo, USE ESTRITAMENTE os valores desta lista para verificar o "status" (CONFORME / REPROVADO):\n\n`; + prompt += JSON.stringify(standardsContext, null, 2); + prompt += `\n=================================================\n`; + } else { + prompt += `\n- Utilize o seu conhecimento paramétrico interno de engenharia de materiais para aplicar os limites corretos da norma encontrada no laudo.\n`; + } + + prompt += ` - **Fórmula de Variação (differencePercentage):** Calcule a variação percentual do valor do certificado em relação ao mínimo exigido pela norma. USE ESTRITAMENTE A FÓRMULA: ((Valor_Certificado - Valor_Norma) / Valor_Norma) * 100. Exemplo: Se a Norma exige Mínimo 345, e o Certificado acusa 415, o resultado é ((415-345)/345)*100 = +20.3%. @@ -211,17 +210,21 @@ FORMATO DO RETORNO: } ]`; -export const analyzeWithGemini = async (file: File, apiKey: string, model: string = 'gemini-2.5-flash'): Promise => { + return prompt; +}; + +export const analyzeWithGemini = async (file: File, apiKey: string, model: string = 'gemini-2.5-flash', standardsContext?: any[]): Promise => { if (!apiKey) { throw new Error("A chave de API do Gemini não foi fornecida."); } const ai = new GoogleGenAI({ apiKey: apiKey }); const imagePart = await fileToGenerativePart(file); + const prompt = buildAnalysisPrompt(standardsContext); const response = await ai.models.generateContent({ model, - contents: { parts: [imagePart, { text: PROMPT_BASE }] }, + contents: { parts: [imagePart, { text: prompt }] }, config: { responseMimeType: "application/json", responseSchema: arraySchema, @@ -241,7 +244,7 @@ export const analyzeWithGemini = async (file: File, apiKey: string, model: strin } }; -export const analyzeWithOpenAI = async (file: File, apiKey: string, model: string = 'gpt-4o'): Promise => { +export const analyzeWithOpenAI = async (file: File, apiKey: string, model: string = 'gpt-4o', standardsContext?: any[]): Promise => { if (!apiKey) { throw new Error("A chave de API da OpenAI não foi fornecida."); } @@ -252,6 +255,8 @@ export const analyzeWithOpenAI = async (file: File, apiKey: string, model: strin reader.readAsDataURL(file); }); + const prompt = buildAnalysisPrompt(standardsContext); + const response = await fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { @@ -264,7 +269,7 @@ export const analyzeWithOpenAI = async (file: File, apiKey: string, model: strin { role: 'user', content: [ - { type: 'text', text: PROMPT_BASE }, + { type: 'text', text: prompt }, { type: 'image_url', image_url: { url: `data:${file.type};base64,${base64Data}` } @@ -293,136 +298,25 @@ export const analyzeWithOpenAI = async (file: File, apiKey: string, model: strin return cleanAndParseJson(content) as ReportData[]; }; -export const analyzeWithAnthropic = async (file: File, apiKey: string, model: string = 'claude-3-sonnet-20240229'): Promise => { - if (!apiKey) { - throw new Error("A chave de API da Anthropic não foi fornecida."); - } - - const base64Data = await new Promise((resolve) => { - const reader = new FileReader(); - reader.onloadend = () => resolve((reader.result as string).split(',')[1]); - reader.readAsDataURL(file); - }); - - const response = await fetch('https://api.anthropic.com/v1/messages', { - method: 'POST', - headers: { - 'x-api-key': apiKey, - 'anthropic-version': '2023-06-01', - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - model, - max_tokens: 4096, - temperature: 0.1, - messages: [ - { - role: 'user', - content: [ - { - type: 'image', - source: { - type: 'base64', - media_type: file.type, - data: base64Data - } - }, - { - type: 'text', - text: PROMPT_BASE + "\n\nRetorne apenas JSON válido sem formatação markdown." - } - ] - } - ] - }) - }); - - if (!response.ok) { - const error = await response.json(); - throw new Error(`Erro da Anthropic: ${error.error?.message || 'Erro desconhecido'}`); - } - - const data = await response.json(); - const content = data.content[0]?.text; - - if (!content) { - throw new Error("Resposta vazia da Anthropic"); - } - - return cleanAndParseJson(content) as ReportData[]; -}; - -export const analyzeWithAzure = async (file: File, apiKey: string, endpoint: string, deployment: string): Promise => { - if (!apiKey || !endpoint) { - throw new Error("A chave de API e endpoint do Azure são necessários."); - } - - const base64Data = await new Promise((resolve) => { - const reader = new FileReader(); - reader.onloadend = () => resolve((reader.result as string).split(',')[1]); - reader.readAsDataURL(file); - }); - - const url = `${endpoint}/openai/deployments/${deployment}/chat/completions?api-version=2024-02-15-preview`; - - const response = await fetch(url, { - method: 'POST', - headers: { - 'api-key': apiKey, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - messages: [ - { - role: 'user', - content: [ - { type: 'text', text: PROMPT_BASE }, - { - type: 'image_url', - image_url: { url: `data:${file.type};base64,${base64Data}` } - } - ] - } - ], - max_tokens: 4096, - temperature: 0.1 - }) - }); - - if (!response.ok) { - const error = await response.text(); - throw new Error(`Erro do Azure: ${error}`); - } - - const data = await response.json(); - const content = data.choices[0]?.message?.content; - - if (!content) { - throw new Error("Resposta vazia do Azure"); - } - - return cleanAndParseJson(content) as ReportData[]; -}; - export const analyzeCertificate = async (options: AnalyzeOptions): Promise => { - const { provider, apiKey, model, file, endpoint } = options; + const { provider, apiKey, model, file, endpoint, standardsContext } = options; switch (provider) { case 'gemini': - return analyzeWithGemini(file, apiKey, model); + return analyzeWithGemini(file, apiKey, model, standardsContext); case 'openai': - return analyzeWithOpenAI(file, apiKey, model); + return analyzeWithOpenAI(file, apiKey, model, standardsContext); case 'ollama': - return analyzeWithOllama(file, endpoint!, model); + return analyzeWithOllama(file, endpoint!, model, standardsContext); case 'openrouter': - return analyzeWithOpenRouter(file, apiKey, model); + return analyzeWithOpenRouter(file, apiKey, model, standardsContext); default: // @ts-ignore throw new Error(`Provedor não suportado: ${provider}`); } }; -export const analyzeWithOllama = async (file: File, endpoint: string, model: string = 'llama3.2-vision'): Promise => { +export const analyzeWithOllama = async (file: File, endpoint: string, model: string = 'llama3.2-vision', standardsContext?: any[]): Promise => { if (!endpoint) { throw new Error("O endpoint do Ollama é necessário. Configure o endereço da sua VPS."); } @@ -433,6 +327,8 @@ export const analyzeWithOllama = async (file: File, endpoint: string, model: str reader.readAsDataURL(file); }); + const prompt = buildAnalysisPrompt(standardsContext); + let url = `${endpoint}/api/chat`; // Check if using OpenWebUI (has /api in path but not direct Ollama) @@ -461,7 +357,7 @@ export const analyzeWithOllama = async (file: File, endpoint: string, model: str }, { type: 'text', - text: PROMPT_BASE + "\n\nRetorne apenas JSON válido sem formatação markdown." + text: prompt } ] } @@ -492,7 +388,7 @@ export const analyzeWithOllama = async (file: File, endpoint: string, model: str return cleanAndParseJson(content) as ReportData[]; }; -export const analyzeWithOpenRouter = async (file: File, apiKey: string, model: string = 'google/gemini-2.5-flash'): Promise => { +export const analyzeWithOpenRouter = async (file: File, apiKey: string, model: string = 'openai/gpt-4o', standardsContext?: any[]): Promise => { if (!apiKey) { throw new Error("A chave de API do OpenRouter não foi fornecida."); } @@ -503,13 +399,15 @@ export const analyzeWithOpenRouter = async (file: File, apiKey: string, model: s reader.readAsDataURL(file); }); + const prompt = buildAnalysisPrompt(standardsContext); + const response = await fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json', - 'HTTP-Referer': 'https://steelcheck.local', - 'X-Title': 'SteelCheck', + 'HTTP-Referer': 'https://steelcheck.app', + 'X-Title': 'SteelCheck', }, body: JSON.stringify({ model, @@ -517,7 +415,7 @@ export const analyzeWithOpenRouter = async (file: File, apiKey: string, model: s { role: 'user', content: [ - { type: 'text', text: PROMPT_BASE + "\n\nRetorne apenas JSON válido sem formatação markdown." }, + { type: 'text', text: prompt }, { type: 'image_url', image_url: { url: `data:${file.type};base64,${base64Data}` } @@ -525,13 +423,20 @@ export const analyzeWithOpenRouter = async (file: File, apiKey: string, model: s ] } ], - temperature: 0.1 + temperature: 0.1, + response_format: { type: 'json_object' } }) }); if (!response.ok) { - const error = await response.json(); - throw new Error(`Erro do OpenRouter: ${error.error?.message || 'Erro desconhecido'}`); + let errorMessage = 'Erro desconhecido'; + try { + const errorData = await response.json(); + errorMessage = errorData.error?.message || JSON.stringify(errorData); + } catch (e) { + errorMessage = await response.text(); + } + throw new Error(`Erro do OpenRouter: ${errorMessage}`); } const data = await response.json();