viniciusgurgel18@gmail.com require('dotenv').config(); const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const { GoogleGenerativeAI } = require('@google/generative-ai');
const app = express(); const port = process.env.PORT || 3001;
app.use(cors()); app.use(bodyParser.json());
// Initialize Gemini AI const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
async function processTextWithAI(inputText) { try { const model = genAI.getGenerativeModel({ model: "gemini-pro" });
const prompt = `
Please provide an organized and structured summary of the following text:
${inputText}
Include key points, relevant details, and categorize the content logically.
Return the result as a JSON object with the following structure:
{
"summary": "A detailed summary of the content",
"categories": {
"category1": "Details related to category 1",
"category2": "Details related to category 2"
}
}
`;
console.log("Generated Prompt:", prompt);
// Generate content
const result = await model.generateContent({
prompt,
maxTokens: 500,
temperature: 0.7,
});
// Validate the response
if (!result || !result.candidates || !Array.isArray(result.candidates)) {
throw new Error("Unexpected response format from Gemini AI");
}
const content = result.candidates[0]?.content;
if (!content) {
throw new Error("No valid content returned by Gemini AI");
}
// Parse JSON content
try {
return JSON.parse(content);
} catch (parseError) {
console.error("Failed to parse AI response:", parseError.message);
throw new Error("Invalid JSON format in AI response");
}
} catch (error) { console.error("Error processing text with Gemini AI:", error.message); throw new Error("Failed to process text"); } }
// API endpoint to process text app.post('/process', async (req, res) => { const { text } = req.body;
if (!text) { return res.status(400).json({ message: 'Texto não fornecido' }); }
try { const processedData = await processTextWithAI(text); res.json(processedData); } catch (error) { console.error("Error in /process endpoint:", error.message); res.status(500).json({ error: 'Internal server error' }); } });
// Start the server
app.listen(port, () => {
console.log(Server is running on port ${port}
);
});
PS D:\Projetos_Gurgel\notafiscal\api> node index.js
Server is running on port 3001
Generated Prompt:
Please provide an organized and structured summary of the following text:
Date de Facture - Faktuur Datum
Numéro TVA Client - BTW Nummer Klant
Numéro de Facture - Faktuur Nummer
Waterloose Steenweg, 200/8
1640 Sint-Genesius-Rode
BE 0771.590.557
13/11/2024
BCH-202414360
1652 AlsembergTVA-BTW BE 0788.653.451Fax: -Tel: 02 781 13 21Rodestraat, 2
RENOWATION
/CHrNl,17OlATrswoN° DE CLIENT :
34.979
BELFIUS BE45 0689 4632 8589
Prix VenteVerkoop PrijsTVABTWMontantBedragNombreAantalDescriptionBeschrijvingFACTURE/FAKTUUR
10,46
2,20
10,46
1
- PARASILICO PRESTIGE COL RAL7016 ANTHRACITE 300ML 2,85 0,60 2,85 1
- ADH 12*12"Le client déclare avoir pris connaissance des conditions générales reprises au verso du présent document et les avoir acceptées sans réserve".
Signature : 13/11/2024 16,11 € 0,00 € 16,11 € Total/TotaalAcompte/VoorschotA Payer/Te BetalenEcheance/VervalDatum% TVABTW %Total Hors TVATotaal Zonder /0ta4r/81/0taa4rG/u 21 Page/Blz. 11-info.bchbrico@gmail.com
--- NOVA PÁGINA ---
Include key points, relevant details, and categorize the content logically.
Return the result as a JSON object with the following structure:
{
"summary": "A detailed summary of the content",
"categories": {
"category1": "Details related to category 1",
"category2": "Details related to category 2"
}
}
Error processing text with Gemini AI: request is not iterable Error in /process endpoint: Failed to process text
Loading...
Raw API Response: {
"response": {
"candidates": [
{
"content": {
"parts": [
{
"text": "json\n{\n \"summary\": \"This is an invoice from RENOWATION with the invoice number BCH-202414360 dated 13/11/2024. The customer's VAT number is BE 0788.653.451 and the customer number is 34.979. The invoice includes two items:\\n\\n- 1 unit of PARASILICO PRESTIGE COL RAL7016 ANTHRACITE 300ML priced at 10.46 euros\\n- 1 unit of ADH 12*12 priced at 2.85 euros\\n\\nThe total amount of the invoice is 16.11 euros, with no down payment and no VAT charged. The payment should be made to BELFIUS account BE45 0689 4632 8589.\",\n \"categories\": {\n \"Invoice Details\": {\n \"Invoice Number\": \"BCH-202414360\",\n \"Invoice Date\": \"13/11/2024\",\n \"Customer VAT Number\": \"BE 0788.653.451\",\n \"Customer Number\": \"34.979\",\n \"Total Amount\": \"16.11 euros\",\n \"Down Payment\": \"0.00 euros\",\n \"Due Date\": null,\n \"Payment Information\": \"BELFIUS BE45 0689 4632 8589\"\n },\n \"Items\": {\n \"PARASILICO PRESTIGE COL RAL7016 ANTHRACITE 300ML\": {\n \"Unit Price\": \"10.46 euros\",\n \"Quantity\": \"1\",\n \"Total\": \"10.46 euros\"\n },\n \"ADH 12*12\": {\n \"Unit Price\": \"2.85 euros\",\n \"Quantity\": \"1\",\n \"Total\": \"2.85 euros\"\n }\n }\n }\n}\n
"
}
],
"role": "model"
},
"finishReason": "STOP",
"index": 0,
"safetyRatings": [
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HARASSMENT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"probability": "NEGLIGIBLE"
}
]
}
],
"usageMetadata": {
"promptTokenCount": 578,
"candidatesTokenCount": 488,
"totalTokenCount": 1066
},
"modelVersion": "gemini-pro"
}
}
Error processing text with Gemini AI: API response is not iterable
Error in /process endpoint: Failed to process text: API response is not iterable
Loading...
top amei ficou top demais aora quero que me ajude para salvarr em json.data as nota fiscal ou extratos pegos pois devemos
[ { "timestamp": "1736472030504", "fileName": "nota_fiscal_1736472030504.json", "numero": "BCH-202414360", "data": "13/11/2024", "cliente": "34.979", "valor": 16.11 }, { "timestamp": "1736473701593", "fileName": "nota_fiscal_1736473701593.json", "numero": "BCH-202414360", "data": "13/11/2024", "cliente": "34.979", "valor": 16.11 } ] require('dotenv').config(); const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const { GoogleGenerativeAI } = require('@google/generative-ai');
const app = express(); const port = process.env.PORT || 3001;
app.use(cors()); app.use(bodyParser.json());
// Initialize Gemini AI const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY); async function processTextWithAI(inputText) { try { const model = genAI.getGenerativeModel({ model: "gemini-pro" });
const prompt = `
Please provide an organized and structured summary of the following text:
${inputText}
Include key points, relevant details, and categorize the content logically.
Return the result as a JSON object with the following structure:
{
"summary": "A detailed summary of the content",
"categories": {
"category1": "Details related to category 1",
"category2": "Details related to category 2"
}
}
`;
console.log("Generated Prompt:", prompt);
// Generate content
const result = await model.generateContent(prompt);
console.log("Raw API Response:", JSON.stringify(result, null, 2));
if (!result.response || !result.response.candidates || !result.response.candidates[0]) {
throw new Error("Unexpected response format from Gemini AI");
}
const textContent = result.response.candidates[0].content.parts[0].text;
console.log("Extracted Text Content:", textContent);
// Remove the markdown code block delimiters if present
const jsonString = textContent.replace(/```json\n|\n```/g, '');
// Parse JSON content
try {
return JSON.parse(jsonString);
} catch (parseError) {
console.error("Failed to parse AI response:", parseError.message);
console.log("Raw text content:", jsonString);
throw new Error("Invalid JSON format in AI response");
}
} catch (error) {
console.error("Error processing text with Gemini AI:", error.message);
throw new Error(Failed to process text: ${error.message}
);
}
}
// API endpoint to process text
app.post('/process', async (req, res) => {
const { text } = req.body;
if (!text) { return res.status(400).json({ message: 'Texto não fornecido' }); }
try { const processedData = await processTextWithAI(text); res.json(processedData); } catch (error) { console.error("Error in /process endpoint:", error.message); res.status(500).json({ error: 'Internal server error' }); } });
// Start the server
app.listen(port, () => {
console.log(Server is running on port ${port}
);
});
errar codiog completo com toda logica e funcoe