Files
html/api/ambre-tool-youtube-summary.php
2026-04-22 00:35:02 +02:00

61 lines
2.2 KiB
PHP

<?php
header("Content-Type: application/json; charset=utf-8");
$in = json_decode(file_get_contents("php://input"), true) ?: $_POST ?: $_GET;
$url = trim($in["url"] ?? "");
if (!$url || !preg_match('/(youtube\.com\/watch\?v=|youtu\.be\/)([\w-]{11})/', $url, $m)) {
echo json_encode(["error"=>"YouTube URL required"]); exit;
}
$vid = $m[2];
$t0 = microtime(true);
// New API signature (v1.2.4+): YouTubeTranscriptApi().fetch(video_id)
$py = <<<PYTHON
import json, sys
from youtube_transcript_api import YouTubeTranscriptApi
try:
api = YouTubeTranscriptApi()
transcript = api.fetch('$vid', languages=['fr', 'en', 'es'])
data = [{'text': s.text, 'start': s.start} for s in transcript]
print(json.dumps(data))
except Exception as e:
print(json.dumps({'error': str(e)}))
PYTHON;
$tmp = tempnam(sys_get_temp_dir(), "yt_") . ".py";
file_put_contents($tmp, $py);
$raw = @shell_exec("python3 $tmp 2>&1");
@unlink($tmp);
$decoded = @json_decode($raw, true);
if (!is_array($decoded) || isset($decoded["error"])) {
echo json_encode(["error"=>"transcript unavailable", "detail"=>$decoded["error"] ?? substr($raw, 0, 200)]);
exit;
}
$text = "";
foreach ($decoded as $seg) $text .= ($seg["text"] ?? "") . " ";
$text = trim($text);
if (strlen($text) < 50) { echo json_encode(["error"=>"empty transcript"]); exit; }
$text = substr($text, 0, 10000);
// Summarize
$sys = "Résume cette transcription vidéo en 5-8 points clés, style note professionnelle, en français.";
$llm = @file_get_contents("http://127.0.0.1:4000/v1/chat/completions", false, stream_context_create([
"http"=>["method"=>"POST","header"=>"Content-Type: application/json\r\n",
"content"=>json_encode(["model"=>"fast","messages"=>[
["role"=>"system","content"=>$sys],
["role"=>"user","content"=>$text],
],"max_tokens"=>700,"temperature"=>0.3]),"timeout"=>30]
]));
$d = @json_decode($llm, true);
$summary = $d["choices"][0]["message"]["content"] ?? "Résumé indisponible.";
echo json_encode([
"success"=>true, "video_id"=>$vid, "url"=>$url,
"summary"=>trim($summary),
"transcript_chars"=>strlen($text),
"elapsed_ms"=>round((microtime(true)-$t0)*1000),
"provider"=>"WEVIA Video Summary",
]);