<?php
declare(strict_types=1);
namespace App\Controller\BackEnd;
use App\Entity\Post;
use App\Entity\Category;
use App\Entity\MediaCms;
use App\Entity\AiMotCles;
use Orhanerday\OpenAi\OpenAi;
use App\Service\OpenAiService;
use App\Entity\HistoriqueBlocAi;
use App\Repository\LanguageRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class EditorGenerateContentController extends AbstractController
{
private $parameterBag;
private $session;
private $httpClient;
private $em;
public function __construct(ParameterBagInterface $parameterBag,
SessionInterface $session,
HttpClientInterface $httpClient,
EntityManagerInterface $em)
{
$this->parameterBag = $parameterBag;
$this->session = $session;
$this->em = $em;
$this->httpClient = $httpClient;
}
/**
* @Route("/ai/editor-generate-content", name="editor_generate_content")
*/
public function streamData(Request $request): Response
{
// Set headers for Server-Sent Events (SSE)
$response = new Response();
$response->headers->set('Content-Type', 'text/event-stream');
$response->headers->set('Cache-Control', 'no-cache');
$response->headers->set('Connection', 'keep-alive');
// Retrieve OpenAI API key from environment or config
$openaiApiKey = $this->parameterBag->get('OPENAI_API_KEY');
// Retrieve the POST data
$url = $request->request->get('url');
$data = json_decode($request->request->get('data'), true);
if (!$url || !$data) {
return new Response('Invalid request', 400);
}
// Initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $openaiApiKey,
]);
// Handle streaming data
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $chunk) use ($response) {
echo $chunk;
ob_flush();
flush();
return strlen($chunk);
});
// Execute the request
curl_exec($ch);
if (curl_errno($ch)) {
return new Response('Error: ' . curl_error($ch), 500);
}
curl_close($ch);
return $response;
}
/**
* @Route("/ai/editor-generate-image", name="editor_generate_image")
*/
public function generateImage(Request $request): JsonResponse
{
$url = $request->request->get('url');
$data = json_decode($request->request->get('data'), true);
$openaiApiKey = $this->parameterBag->get('OPENAI_API_KEY');
try {
$response = $this->httpClient->request('POST', $url, [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $openaiApiKey,
],
'json' => $data,
]);
$responseContent = $response->getContent(); // Throws exception if status code >= 400
$responseContent = json_decode($response->getContent(), true);
// Extract the image URL from the response
$imageUrl = $responseContent['data'][0]['url'];
$revisedPrompt = $responseContent['data'][0]['revised_prompt'];
// Download and save the image locally
$filesystem = new Filesystem();
$localDir = $this->getParameter('kernel.project_dir') . '/public/uploads/images';
$localFileName = uniqid('image_') . '.png';
$localPath = $localDir . '/' . $localFileName;
if (!$filesystem->exists($localDir)) {
$filesystem->mkdir($localDir);
}
// Download image content
$imageContent = file_get_contents($imageUrl);
file_put_contents($localPath, $imageContent);
// Update the response to include the new path
$responseContent['data'][0]['url'] = '/uploads/images/' . $localFileName;
$responseContent['data'][0]['revised_prompt'] = $revisedPrompt;
} catch (\Exception $e) {
return new JsonResponse(['error' => $e->getMessage()], 500);
}
return new JsonResponse($responseContent);
}
/**
* @Route("/ai/editor-link",methods={"GET"},name="editor_link")
*/
public function EditorLink(Request $request)
{
$data = [];
$shortCode = [];
$_locale = $request->getLocale();
$bloc_ai = $this->getDoctrine()->getRepository(HistoriqueBlocAi::class)->findAll();
$posts = $this->getDoctrine()->getRepository(Post::class)->findAll();
$categories = $this->getDoctrine()->getRepository(Category::class)->findCategorie();
if($bloc_ai){
foreach ($bloc_ai as $key => $value) {
$shortCode[] = $value->getShortCode();
}
}
if($posts){
foreach($posts as $value){
if($value->getAlias() != 'page-home'){
$data[] = ['name'=> $value->translate($_locale)->getTitle(),'url'=> '/'.$value->translate($_locale)->getSlug()];
}
}
}
if ($categories) {
foreach($categories as $value){
$data[] = ['name'=> $value['titre'],'url'=> '/'.$value['slug']];
}
}
return new JsonResponse(['url'=> $data,'shortCode'=> $shortCode]);
}
}