35846-vm/upload.php
2025-11-19 12:47:09 +00:00

113 lines
3.8 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/ai/LocalAIApi.php';
function return_error($message) {
echo json_encode(['success' => false, 'error' => $message]);
exit;
}
// 1. Handle File Upload
if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
return_error('File upload error. Please try again. Code: ' . ($_FILES['csv_file']['error'] ?? 'Unknown'));
}
$file = $_FILES['csv_file'];
$tmpPath = $file['tmp_name'];
// 2. Validate File Type (Basic Check)
$fileType = mime_content_type($tmpPath);
$fileName = $file['name'];
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
if ($fileType !== 'text/csv' && $fileType !== 'text/plain' && $fileExtension !== 'csv') {
return_error('Invalid file type. Please upload a valid CSV file.');
}
// 3. Move Uploaded File to a Permanent Location
$uploadsDir = __DIR__ . '/uploads/';
if (!is_dir($uploadsDir)) {
mkdir($uploadsDir, 0777, true);
}
$safeFileName = preg_replace("/[^a-zA-Z0-9_.-]|\.\.+/", "", basename($fileName));
$newFilePath = $uploadsDir . uniqid() . '-' . $safeFileName;
if (!move_uploaded_file($tmpPath, $newFilePath)) {
return_error('Failed to save the uploaded file.');
}
// 4. Read CSV Header and First 2 Rows from the new path
$dataSample = '';
$handle = fopen($newFilePath, 'r');
if (!$handle) {
return_error('Failed to open the uploaded file.');
}
$lineCount = 0;
while (($row = fgetcsv($handle)) !== false && $lineCount < 3) {
$dataSample .= implode(',', array_map(function($cell) {
return '"' . addslashes($cell) . '"';
}, $row)) . "\n";
$lineCount++;
}
fclose($handle);
if (empty($dataSample)) {
return_error('The CSV file appears to be empty or could not be read.');
}
// 4. Prepare Prompt for AI
$prompt = <<<PROMPT
You are an expert data analyst. A user has uploaded a CSV file for analysis.
Below is the header and the first two rows of the data.
Your task is to perform a brief analysis and return the output in **HTML format**.
**Data Sample:**
```csv
{$dataSample}
```
**Instructions:**
1. **Briefly Describe the Data:** In a paragraph, describe what the data appears to be about. Identify the likely data type for each column (e.g., Text, Number, Date).
2. **Suggest Charts & Visualizations:** In a bulleted list, suggest 2-3 relevant charts or visualizations that could be created from this data. For each suggestion, briefly explain what insight it would provide. Use `<ul>` and `<li>` tags.
3. **Suggest Key Statistics:** In a bulleted list, suggest 2-3 key statistical calculations (e.g., average, sum, distribution) that would be meaningful for this dataset. Use `<ul>` and `<li>` tags.
Structure your response using HTML tags like `<h4>`, `<p>`, and `<ul>`.
PROMPT;
// 5. Call AI API
try {
$resp = LocalAIApi::createResponse(
[
'input' => [
['role' => 'system', 'content' => 'You are a helpful data analysis assistant.'],
['role' => 'user', 'content' => $prompt],
],
]
);
if (empty($resp['success'])) {
$errorMsg = 'AI API Error: ' . ($resp['error'] ?? 'Unknown error');
error_log($errorMsg);
return_error('Failed to get a response from the AI. Please try again later.');
}
$aiText = LocalAIApi::extractText($resp);
if (empty($aiText)) {
$decoded = LocalAIApi::decodeJsonFromResponse($resp);
$aiText = $decoded ? '<pre>' . htmlspecialchars(json_encode($decoded, JSON_PRETTY_PRINT)) . '</pre>' : 'The AI returned an empty response.';
}
echo json_encode(['success' => true, 'analysis' => $aiText, 'filePath' => $newFilePath]);
} catch (Exception $e) {
error_log('Exception in AI call: ' . $e->getMessage());
return_error('An unexpected error occurred while processing the file with AI.');
}