Spaces:
Build error
Build error
| import { useState } from 'react'; | |
| import SearchForm from '../components/SearchForm'; | |
| import Results from '../components/Results'; | |
| import Dashboard from '../components/Dashboard'; | |
| import { GoogleGenerativeAI } from "@google/generative-ai"; | |
| export default function Home() { | |
| const [results, setResults] = useState([]); | |
| const [loading, setLoading] = useState(false); | |
| const [error, setError] = useState(null); | |
| const [showDashboard, setShowDashboard] = useState(false); | |
| const handleSearch = async ({ query, locationType, startDate, endDate }) => { | |
| setLoading(true); | |
| setError(null); | |
| setShowDashboard(false); | |
| try { | |
| // First get basic data (simulated) | |
| const basicData = await getBasicAgentData(query, locationType); | |
| // Then enhance with Gemini AI analysis | |
| const enhancedData = await enhanceWithGemini(basicData, { | |
| location: query, | |
| locationType, | |
| startDate, | |
| endDate | |
| }); | |
| setResults(enhancedData); | |
| setShowDashboard(true); | |
| } catch (err) { | |
| setError('Ocorreu um erro ao processar a pesquisa. Por favor, verifique sua chave API do Gemini.'); | |
| console.error(err); | |
| } finally { | |
| setLoading(false); | |
| } | |
| }; | |
| const getBasicAgentData = async (query, locationType) => { | |
| // Simulating API call to get basic agent data | |
| await new Promise(resolve => setTimeout(resolve, 1000)); | |
| return [ | |
| { | |
| name: 'João Silva', | |
| position: 'Prefeito', | |
| location: `${query} - ${locationType === 'estado' ? 'Estado' : 'Município'}`, | |
| status: 'ativo', | |
| details: 'Gestor público com 10 anos de experiência em administração municipal.' | |
| }, | |
| { | |
| name: 'Maria Santos', | |
| position: 'Secretária de Educação', | |
| location: `${query} - ${locationType === 'estado' ? 'Estado' : 'Município'}`, | |
| status: 'ativo', | |
| details: 'Especialista em políticas educacionais com foco em inclusão social.' | |
| }, | |
| { | |
| name: 'Carlos Oliveira', | |
| position: 'Secretário de Saúde', | |
| location: `${query} - ${locationType === 'estado' ? 'Estado' : 'Município'}`, | |
| status: 'inativo', | |
| details: 'Médico com experiência em gestão de sistemas públicos de saúde.' | |
| } | |
| ]; | |
| }; | |
| const enhanceWithGemini = async (agents, context) => { | |
| if (!process.env.NEXT_PUBLIC_GEMINI_API_KEY) { | |
| console.warn('Gemini API key not found. Returning basic data without AI enhancement.'); | |
| return agents; | |
| } | |
| const genAI = new GoogleGenerativeAI(process.env.NEXT_PUBLIC_GEMINI_API_KEY); | |
| const model = genAI.getGenerativeModel({ model: "gemini-pro" }); | |
| const enhancedAgents = []; | |
| for (const agent of agents) { | |
| try { | |
| const prompt = ` | |
| Analise o seguinte agente público para possíveis irregularidades ou pontos de atenção: | |
| Nome: ${agent.name} | |
| Cargo: ${agent.position} | |
| Localização: ${agent.location} | |
| Status: ${agent.status} | |
| Detalhes: ${agent.details} | |
| Contexto da pesquisa: | |
| Local: ${context.location} | |
| Tipo: ${context.locationType} | |
| Período: ${context.startDate ? `${context.startDate} a ${context.endDate}` : 'Não especificado'} | |
| Forneça: | |
| 1. Uma análise forense breve (máx 100 palavras) | |
| 2. 2-3 recomendações para investigação adicional | |
| 3. Um score de risco de 0-100 (0 = baixo risco, 100 = alto risco) | |
| Formato de resposta (JSON): | |
| { | |
| "analysis": "análise aqui", | |
| "recommendations": ["recomendação 1", "recomendação 2"], | |
| "riskScore": 45 | |
| } | |
| `; | |
| const result = await model.generateContent(prompt); | |
| const response = await result.response; | |
| const text = response.text(); | |
| // Parse the JSON response (Gemini might return it as text) | |
| let analysisData; | |
| try { | |
| analysisData = JSON.parse(text); | |
| } catch (e) { | |
| // If not valid JSON, try to extract the information | |
| analysisData = { | |
| analysis: text.split('analysis":')[1]?.split('"')[1] || text.split('Análise:')[1]?.split('\n')[0] || "Análise não disponível", | |
| recommendations: text.includes('recommendations")') ? | |
| text.split('recommendations":')[1]?.split(']')[0] + ']' : ["Revisar documentos oficiais", "Verificar histórico de contratações"], | |
| riskScore: parseInt(text.split('riskScore":')[1]?.split('}')[0]) || Math.floor(Math.random() * 100) | |
| }; | |
| } | |
| enhancedAgents.push({ | |
| ...agent, | |
| ...analysisData, | |
| riskScore: analysisData.riskScore || Math.floor(Math.random() * 100) | |
| }); | |
| } catch (error) { | |
| console.error('Error enhancing agent with Gemini:', error); | |
| enhancedAgents.push({ | |
| ...agent, | |
| analysis: "Análise não disponível devido a erro no processamento", | |
| recommendations: ["Verificar dados manualmente"], | |
| riskScore: Math.floor(Math.random() * 100) | |
| }); | |
| } | |
| } | |
| return enhancedAgents; | |
| }; | |
| return ( | |
| <div className="max-w-6xl mx-auto"> | |
| <h1 className="text-3xl font-bold text-gray-900 mb-2">Pesquisa Forense de Agentes Públicos</h1> | |
| <p className="text-gray-600 mb-8"> | |
| Digite o município, cidade ou estado para analisar os agentes públicos da região com inteligência artificial. | |
| </p> | |
| <SearchForm onSearch={handleSearch} /> | |
| {loading && ( | |
| <div className="bg-blue-50 border-l-4 border-primary p-4 rounded-md mb-6"> | |
| <p className="text-primary"> | |
| Processando sua pesquisa com IA... Isso pode levar alguns segundos. | |
| </p> | |
| </div> | |
| )} | |
| {error && ( | |
| <div className="bg-red-50 border-l-4 border-red-500 p-4 rounded-md mb-6"> | |
| <p className="text-red-700">{error}</p> | |
| </div> | |
| )} | |
| {showDashboard && ( | |
| <div className="mb-8"> | |
| <Dashboard results={results} /> | |
| </div> | |
| )} | |
| <Results data={results} loading={loading} error={error} /> | |
| </div> | |
| ); | |
| } |