basic AI analytics
This commit is contained in:
parent
f13abdd4fe
commit
b388b6375e
@ -55,26 +55,40 @@ document.addEventListener('DOMContentLoaded', function () {
|
|||||||
spinner.classList.remove('d-none');
|
spinner.classList.remove('d-none');
|
||||||
submitButton.disabled = true;
|
submitButton.disabled = true;
|
||||||
|
|
||||||
// --- FAKE LOADER FOR DEMO ---
|
const formData = new FormData(uploadForm);
|
||||||
// In the next step, we will replace this with a real AJAX call to the backend.
|
|
||||||
setTimeout(() => {
|
|
||||||
// Hide spinner and re-enable button
|
|
||||||
spinner.classList.add('d-none');
|
|
||||||
submitButton.disabled = false;
|
|
||||||
|
|
||||||
// Show results section with a placeholder message
|
// Show loading state
|
||||||
resultsSection.style.display = 'block';
|
resultsSection.style.display = 'block';
|
||||||
analysisOutput.innerHTML = `
|
analysisOutput.innerHTML = `
|
||||||
<div class="text-center p-5">
|
<div class="text-center p-5">
|
||||||
<div class="spinner-border text-primary" role="status">
|
<div class="spinner-border text-primary" role="status">
|
||||||
<span class="visually-hidden">Loading...</span>
|
<span class="visually-hidden">Loading...</span>
|
||||||
</div>
|
</div>
|
||||||
<p class="mt-3">AI is analyzing your data... This will be implemented in the next step.</p>
|
<p class="mt-3">AI is analyzing your data, this may take a moment...</p>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
// Scroll to results
|
|
||||||
resultsSection.scrollIntoView({ behavior: 'smooth' });
|
resultsSection.scrollIntoView({ behavior: 'smooth' });
|
||||||
|
|
||||||
}, 2000);
|
fetch('upload.php', {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData
|
||||||
|
})
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
if (data.success) {
|
||||||
|
analysisOutput.innerHTML = data.analysis;
|
||||||
|
} else {
|
||||||
|
analysisOutput.innerHTML = `<div class="alert alert-danger">${data.error || 'An unknown error occurred.'}</div>`;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Error:', error);
|
||||||
|
analysisOutput.innerHTML = `<div class="alert alert-danger">An error occurred while communicating with the server.</div>`;
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
// Hide spinner and re-enable button
|
||||||
|
spinner.classList.add('d-none');
|
||||||
|
submitButton.disabled = false;
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
100
upload.php
Normal file
100
upload.php
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
<?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. Read CSV Header and First 2 Rows
|
||||||
|
$dataSample = '';
|
||||||
|
$handle = fopen($tmpPath, '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]);
|
||||||
|
|
||||||
|
} catch (Exception $e) {
|
||||||
|
error_log('Exception in AI call: ' . $e->getMessage());
|
||||||
|
return_error('An unexpected error occurred while processing the file with AI.');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
Loading…
x
Reference in New Issue
Block a user