<?php
function cosineSimilarity(array $a, array $b): float
{
$dot = $normA = $normB = 0.0;
foreach ($a as $i => $x) {
$dot += $x * $b[$i];
$normA += $x * $x;
$normB += $b[$i] * $b[$i];
}
return ($normA && $normB) ? $dot / (sqrt($normA) * sqrt($normB)) : 0.0;
}
function getEmbeddingSimule(string $texte): array
{
$texte = strtolower($texte);
if (str_contains($texte, "durée") || str_contains($texte, "dure")
|| str_contains($texte, "heures") || str_contains($texte, "temps")) {
return [0.76, 0.19, -0.27, 0.80];
}
if (str_contains($texte, "prix") || str_contains($texte, "coûte")
|| str_contains($texte, "combien") || str_contains($texte, "tarif")
|| str_contains($texte, "dt")) {
return [-0.58, 0.22, 0.68, 0.18];
}
if (str_contains($texte, "apprend") || str_contains($texte, "programme")
|| str_contains($texte, "contenu") || str_contains($texte, "cours")) {
return [0.28, 0.73, 0.38, -0.08];
}
return [0, 0, 0, 0];
}
$documents = [
["contenu" => "La formation Laravel dure 40 heures.",
"vecteur" => [0.80, 0.18, -0.30, 0.85]],
["contenu" => "La formation comprend PHP, MVC, Eloquent et API REST.",
"vecteur" => [0.30, 0.75, 0.40, -0.10]],
["contenu" => "Le prix de la formation est de 500 DT.",
"vecteur" => [-0.60, 0.20, 0.70, 0.15]],
];
$texte = trim($_POST['texte'] ?? '');
$resultat = null;
if ($texte !== '') {
$vQuestion = getEmbeddingSimule($texte);
$resultat = [];
foreach ($documents as $document) {
$resultat[] = [
'contenu' => $document['contenu'],
'score' => cosineSimilarity($vQuestion, $document['vecteur']),
];
}
}
function e(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Round 3 — Recherche sémantique</title>
<style>
body{font-family:Arial,sans-serif;max-width:700px;margin:30px auto;padding:0 15px;color:#222}
form{margin:10px 0}
input[type=text]{width:100%;padding:6px}
button{margin-top:8px;padding:6px 14px}
.res{border-left:3px solid #1499c0;padding:8px 12px;margin-top:8px}
.score{display:flex;justify-content:space-between;border-bottom:1px solid #ddd;padding:4px 0}
</style>
</head>
<body>
<h1>Round 3 — Rechercher le bon document</h1>
<p>La question est comparée aux 3 documents grâce à la similarité cosinus.</p>
<form method="post">
<label>Votre question :</label>
<input type="text" name="texte" value="<?= e($texte !== '' ? $texte : "Quel est le tarif de la formation ?") ?>">
<button type="submit">Comparer aux documents</button>
</form>
<?php if ($resultat !== null):
$meilleurScore = max(array_column($resultat, 'score')); ?>
<div class="res">
<?php foreach ($resultat as $r): ?>
<div class="score">
<span><?= $r['score'] == $meilleurScore ? '✅ ' : '' ?><?= e($r['contenu']) ?></span>
<b><?= number_format($r['score'], 2) ?></b>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<p><a href="round2.php">← Round 2</a> | <a href="round4.php">Round 4 →</a></p>
</body>
</html>