dolibarr 25.0.0-alpha
ajaxuploadpage.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2005-2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This file is a modified version of datepicker.php from phpBSM to fix some
7 * bugs, to add new features and to dramatically increase speed.
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
28if (!defined('NOTOKENRENEWAL')) {
29 define('NOTOKENRENEWAL', 1); // Disables token renewal
30}
31if (!defined('NOREQUIREMENU')) {
32 define('NOREQUIREMENU', '1');
33}
34if (!defined('NOREQUIREHTML')) {
35 define('NOREQUIREHTML', '1');
36}
37if (!defined('NOREQUIREAJAX')) {
38 define('NOREQUIREAJAX', '1');
39}
40if (!defined('NOHEADERNOFOOTER')) {
41 define('NOHEADERNOFOOTER', '1');
42}
43
44require_once '../../main.inc.php';
52require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
53require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
54require_once DOL_DOCUMENT_ROOT.'/ai/class/ai.class.php';
55
56
57if (GETPOST('lang', 'aZ09')) {
58 $langs->setDefaultLang(GETPOST('lang', 'aZ09')); // If language was forced on URL by the main.inc.php
59}
60
61$langs->loadLangs(array("main", "other", "exports"));
62
63$action = GETPOST('action', 'aZ09');
64$modulepart = GETPOST('modulepart', 'aZ09');
65
66$upload_dir = $conf->user->dir_temp.'/import';
67
68// Delete the temporary files that are used when uploading files
69//dol_delete_file($upload_dir.'/upload_page-by'.$user->id.'-*');
70
71$file = GETPOST('file');
72
73$reg = array();
74if (preg_match('/^upload_page-([a-z_]+)-uid(\d+)-/', $file, $reg)) {
75 $modulepart = $reg[1];
76
77 if ($reg[2] != $user->id) {
78 accessforbidden('User id found in filename to process does not match current user id');
79 }
80} else {
81 accessforbidden('Bad value for file parameter');
82}
83
84$error = 0;
85$errors = array();
86
87$ai = new Ai($db);
88
89
90/*
91 * Actions
92 */
93
94//
95
96
97
98/*
99 * View
100 */
101
102top_httphead('application/json');
103
104$originalfilename = $file;
105$uid = $thiid = $pid = $erid = $salid = 0;
106if (preg_match('/-uid([\d+])/', $file, $reg)) {
107 $uid = $reg[1];
108 $originalfilename = preg_replace('/-uid\d+/', '', $originalfilename);
109}
110if (preg_match('/-thiid([\d+])/', $file, $reg)) {
111 $thiid = $reg[1];
112 $originalfilename = preg_replace('/-thiid\d+/', '', $originalfilename);
113}
114if (preg_match('/-pid([\d+])/', $file, $reg)) {
115 $pid = $reg[1];
116 $originalfilename = preg_replace('/-pid\d+/', '', $originalfilename);
117}
118if (preg_match('/-erid([\d+])/', $file, $reg)) {
119 $erid = $reg[1];
120 $originalfilename = preg_replace('/-erid\d+/', '', $originalfilename);
121}
122if (preg_match('/-salid([\d+])/', $file, $reg)) {
123 $salid = $reg[1];
124 $originalfilename = preg_replace('/-salid\d+/', '', $originalfilename);
125}
126$originalfilename = preg_replace('/^upload_page-[a-z_]+-/', '', $originalfilename);
127
128
129
130
131//$METHOD = 'thread'; // For ChatGPT.
132$METHOD = 'converttotext'; // For Mistral and most others
133
134
135$docformat = $doctypelabel = $prompt = '';
136$fullpathoffile = $upload_dir.'/'.$file;
137$answer = null;
138$fileContent = '';
139
140// Set the prompting
141if ($modulepart == 'invoice_supplier') {
142 $docformat = 'pdf';
143 $doctypelabel = 'invoice';
144
145 // Call IA to get information on PDF
146 $prompt = 'Analyze the contents of this '.$docformat.' document of an '.$doctypelabel.' and convert all readable text and numerical information into a structured JSON format. Follow these guidelines:
147
148 1. **Hierarchical Structure:** Group related information into logical categories like "document_info", "vendor or issuer", "recipient", "items", "payment_info" and "other" depending on the content.
149 2. **Flexible Field Identification:** Identify and organize common fields that are found such as:
150 - "invoice number", "invoice reference"
151 - "date", "issue date", "due date", "transaction or invoice date"
152 - "vendor name", "vendor vat number", "vendor professional id (siret, siren, ...), "vendor address", "vendor phone", "vendor email",
153 - "items", "products", "services", "product or service label", "product or service ref", "product or service ref"
154 - "totals", "summary", "amounts", "balance"
155 - "notes," "comments," "messages," "terms"
156 3. **Handle Tables and Lists:** If the document contains tables, represent each row as an object in a list with fields like "no", "ref", "description", "quantity", "vat rate", "unit price", "total excluding tax", "total including tax".
157 4. **Normalize Dates:** If dates are present, format them in ISO format (YYYY-MM-DD) whenever possible.
158 5. **Ignore Background Noise:** Exclude background noise, decorative elements, and irrelevant symbols that do not contribute to the data content.
159 6. **Preserve Context:** If the image contains sections, headings, or grouping indicators, use them to create logical hierarchies in the JSON structure.
160 7. **General Usability:** Format the text to be suitable for further processing, analysis, or database import.
161
162 **Example JSON Structure:**
163
164 {
165 "document_info": {
166 "document_ref": "<document ref or number>",
167 "date": "<date>",
168 "title": "<title>",
169 "currency_code": "<currency_code>"
170 },
171 "vendor": {
172 "name": "<name>",
173 "address": "<address>",
174 "phone": "<phone number>",
175 "email": "<email>",
176 "vatnumber": "<vat number>",
177 "profid": "<professional id>"
178 },
179 "recipient": {
180 "name": "<name>",
181 "address": "<address>",
182 "phone": "<phone number>",
183 "email": "<email>",
184 "vatnumber": "<vat number>",
185 "profid": "<professional id>"
186 },
187 "items": [
188 {
189 "no": "<number>",
190 "ref": "<ref>",
191 "label": "<label>",
192 "description": "<description>",
193 "quantity": "<quantity>",
194 "vatrate": "<vat rate>",
195 "totalinctax": "<total including tax>"
196 "totalexcltax": "<total excluding tax>"
197 }
198 ],
199 "summary": {
200 "subtotal": "<subtotal>",
201 "tax": "<amount of tax>",
202 "total": "<total to pay>"
203 },
204 "payment_methods": [
205 {
206 "method": "<check or cash or card or direct_debit or credit_transfer or other>",
207 "details": "Detail of the payment mode"
208 }
209 ],
210 "payments_done": [
211 {
212 "method": "<check or cash or card or direct_debit or credit_transfer or other>",
213 "amount": "<detail of the payment>",
214 "note":"<other information on payment done>"
215 }
216 ],
217 "notes": "<optional text>"
218 }
219 ';
220}
221
222
223// TODO Move this into an AJAX service and just output the JS code to call the ajax to start
224
225if ($METHOD == 'converttotext') { // @phpstan-ignore-line
226 $result = dolDocToText($fullpathoffile, '', 'fulltext');
227 if (empty($result['error'])) {
228 $fileContent = $result['content'];
229 }
230
231 if ($fileContent) {
232 $prompt = 'This is the content of the document:'."\n\n".dol_substr($fileContent, 0, 12000)."\n\nQuestion: ".$prompt;
233
234 $result = $ai->generateContent($prompt, 'auto', 'docparsing', '');
235 // $result is an array of error messages or a string with answer
236 if (is_array($result)) { // If array, there is an error
237 if ($result['error']) {
238 $error++;
239 $errors[] = $result['error'];
240 }
241 if ($result['curl_error_no']) {
242 $error++;
243 $errors[] = $result['curl_error_no'];
244 }
245 } else {
246 $answer = (string) $result;
247
248 $answer = preg_replace('/^```json/', '', $answer);
249 $answer = preg_replace('/```$/', '', $answer);
250 }
251 } else {
252 $langs->load("errors");
253 $error++;
254 $errors[] = $langs->trans("ErrorFailedToConvertFileInText");
255 $errors[] = $result['message'];
256 }
257}
258
259
260if ($METHOD == 'thread') { // @phpstan-ignore-line
261 $prompt = '';
262
263 $fileId = 0;
264 $assistantId = 0;
265 $threadId = 0;
266 $runId = 0;
267
268
269 // First part is to send the file
270 $payload = array(
271 "purpose" => "assistants",
272 "file" => new CURLFile($fullpathoffile)
273 );
274
275 $result = $ai->generateContent($payload, 'auto', 'file', '');
276
277 if (is_array($result)) { // If array, there is an error
278 if ($result['error']) {
279 $error++;
280 $errors[] = $result['error'];
281 }
282 if ($result['curl_error_no']) {
283 $error++;
284 $errors[] = $result['curl_error_no'];
285 }
286 } else {
287 $fileId = json_decode($result, true)['id'];
288 }
289
290
291 // Create assistant
292 if (!$error) {
293 $payload = [
294 "name" => "PDF Analyzer",
295 "instructions" => "Analyze PDF and answer precisely",
296 "tools" => [
297 ["type" => "file_search"]
298 ]
299 ];
300
301 $result = $ai->generateContent($payload, 'auto', 'assistant', '', array('OpenAI-Beta', 'assistants=v2'));
302
303 if (is_array($result)) { // If array, there is an error
304 if ($result['error']) {
305 $error++;
306 $errors[] = $result['error'];
307 }
308 if ($result['curl_error_no']) {
309 $error++;
310 $errors[] = $result['curl_error_no'];
311 }
312 } else {
313 $assistantId = json_decode($result, true)['id'];
314 }
315 }
316
317
318 // Create thread
319 if (!$error) {
320 $payload = '{}';
321
322 $result = $ai->generateContent($payload, 'auto', 'thread', '', array('OpenAI-Beta', 'assistants=v2'));
323
324 if (is_array($result)) { // If array, there is an error
325 if ($result['error']) {
326 $error++;
327 $errors[] = $result['error'];
328 }
329 if ($result['curl_error_no']) {
330 $error++;
331 $errors[] = $result['curl_error_no'];
332 }
333 } else {
334 $threadId = json_decode($result, true)['id'];
335 }
336 }
337
338
339 // Add file to thread
340 if (!$error) {
341 $payload = array(
342 "role" => "user",
343 "content" => [
344 [
345 "type" => "input_text",
346 "text" => $prompt
347 ]
348 ],
349 "attachments" => [
350 [
351 "file_id" => $fileId,
352 "tools" => [["type" => "file_search"]]
353 ]
354 ]
355 );
356 $moreendpoint = $threadId.'/messages';
357
358 $result = $ai->generateContent($payload, 'auto', 'thread', '', array('OpenAI-Beta', 'assistants=v2'), $moreendpoint);
359
360 if (is_array($result)) { // If array, there is an error
361 if ($result['error']) {
362 $error++;
363 $errors[] = $result['error'];
364 }
365 if ($result['curl_error_no']) {
366 $error++;
367 $errors[] = $result['curl_error_no'];
368 }
369 }
370 }
371
372
373 // Run the thread
374 if (!$error) {
375 $payload = array(
376 ["assistant_id" => $assistantId]
377 );
378 $moreendpoint = $threadId.'/runs';
379
380 $result = $ai->generateContent($payload, 'auto', 'thread', '', array('OpenAI-Beta', 'assistants=v2'), $moreendpoint);
381
382 if (is_array($result)) { // If array, there is an error
383 if ($result['error']) {
384 $error++;
385 $errors[] = $result['error'];
386 }
387 if ($result['curl_error_no']) {
388 $error++;
389 $errors[] = $result['curl_error_no'];
390 }
391 } else {
392 $runId = json_decode($result, true)['id'];
393 }
394 }
395
396
397 // Poll until end of thread
398 if (!$error) {
399 do {
400 sleep(1);
401
402 $payload = '';
403 $moreendpoint = $threadId.'/runs/'.$runId;
404
405 $result = $ai->generateContent($payload, 'auto', 'thread', '', array('OpenAI-Beta', 'assistants=v2'), $moreendpoint);
406
407 if (is_array($result)) { // If array, there is an error
408 if ($result['error']) {
409 $error++;
410 $errors[] = $result['error'];
411 }
412 if ($result['curl_error_no']) {
413 $error++;
414 $errors[] = $result['curl_error_no'];
415 }
416
417 $status = 'completed';
418 } else {
419 $status = json_decode($result, true)['status'];
420 }
421 } while ($status !== "completed");
422 }
423
424
425 // Get answer
426 if (!$error) {
427 $payload = '';
428 $moreendpoint = $threadId.'/messages';
429
430 $result = $ai->generateContent($prompt, 'auto', 'thread', '', array('OpenAI-Beta', 'assistants=v2'));
431
432 if (is_array($result)) { // If array, there is an error
433 if ($result['error']) {
434 $error++;
435 $errors[] = $result['error'];
436 }
437 if ($result['curl_error_no']) {
438 $error++;
439 $errors[] = $result['curl_error_no'];
440 }
441 } else {
442 $answer = $result;
443 }
444 }
445}
446
447
448// End of page
449
450$db->close();
451
452
453if (!empty($errors)) {
454 http_response_code(500);
455
456 print json_encode(array('errors' => $errors));
457} else {
458 $data = json_decode((string) $answer, true);
459
460 if ($data == null) {
461 http_response_code(500);
462
463 $error++;
464 $errors[] = 'Failed to decode answer';
465 print 'Failed to decode answer';
466 } else {
467 print $answer;
468 }
469}
Class for AI feature.
Definition ai.class.php:36
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dolDocToText($filetoprocess, $useFullTextIndexation='pdftotext', $options='html')
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.