src/Controller/BackEnd/EditorGenerateContentController.php line 159

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller\BackEnd;
  4. use App\Entity\Post;
  5. use App\Entity\Category;
  6. use App\Entity\MediaCms;
  7. use App\Entity\AiMotCles;
  8. use Orhanerday\OpenAi\OpenAi;
  9. use App\Service\OpenAiService;
  10. use App\Entity\HistoriqueBlocAi;
  11. use App\Repository\LanguageRepository;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Symfony\Component\Filesystem\Filesystem;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use Symfony\Component\HttpFoundation\JsonResponse;
  18. use Symfony\Contracts\HttpClient\HttpClientInterface;
  19. use Symfony\Component\String\Slugger\SluggerInterface;
  20. use Symfony\Component\HttpFoundation\File\UploadedFile;
  21. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  22. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  23. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  24. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  25. class EditorGenerateContentController extends AbstractController
  26. {
  27. private $parameterBag;
  28. private $session;
  29. private $httpClient;
  30. private $em;
  31. public function __construct(ParameterBagInterface $parameterBag,
  32. SessionInterface $session,
  33. HttpClientInterface $httpClient,
  34. EntityManagerInterface $em)
  35. {
  36. $this->parameterBag = $parameterBag;
  37. $this->session = $session;
  38. $this->em = $em;
  39. $this->httpClient = $httpClient;
  40. }
  41. /**
  42. * @Route("/ai/editor-generate-content", name="editor_generate_content")
  43. */
  44. public function streamData(Request $request): Response
  45. {
  46. // Set headers for Server-Sent Events (SSE)
  47. $response = new Response();
  48. $response->headers->set('Content-Type', 'text/event-stream');
  49. $response->headers->set('Cache-Control', 'no-cache');
  50. $response->headers->set('Connection', 'keep-alive');
  51. // Retrieve OpenAI API key from environment or config
  52. $openaiApiKey = $this->parameterBag->get('OPENAI_API_KEY');
  53. // Retrieve the POST data
  54. $url = $request->request->get('url');
  55. $data = json_decode($request->request->get('data'), true);
  56. if (!$url || !$data) {
  57. return new Response('Invalid request', 400);
  58. }
  59. // Initialize cURL
  60. $ch = curl_init();
  61. curl_setopt($ch, CURLOPT_URL, $url);
  62. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  63. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  64. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  65. 'Content-Type: application/json',
  66. 'Authorization: Bearer ' . $openaiApiKey,
  67. ]);
  68. // Handle streaming data
  69. curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $chunk) use ($response) {
  70. echo $chunk;
  71. ob_flush();
  72. flush();
  73. return strlen($chunk);
  74. });
  75. // Execute the request
  76. curl_exec($ch);
  77. if (curl_errno($ch)) {
  78. return new Response('Error: ' . curl_error($ch), 500);
  79. }
  80. curl_close($ch);
  81. return $response;
  82. }
  83. /**
  84. * @Route("/ai/editor-generate-image", name="editor_generate_image")
  85. */
  86. public function generateImage(Request $request): JsonResponse
  87. {
  88. $url = $request->request->get('url');
  89. $data = json_decode($request->request->get('data'), true);
  90. $openaiApiKey = $this->parameterBag->get('OPENAI_API_KEY');
  91. try {
  92. $response = $this->httpClient->request('POST', $url, [
  93. 'headers' => [
  94. 'Content-Type' => 'application/json',
  95. 'Authorization' => 'Bearer ' . $openaiApiKey,
  96. ],
  97. 'json' => $data,
  98. ]);
  99. $responseContent = $response->getContent(); // Throws exception if status code >= 400
  100. $responseContent = json_decode($response->getContent(), true);
  101. // Extract the image URL from the response
  102. $imageUrl = $responseContent['data'][0]['url'];
  103. $revisedPrompt = $responseContent['data'][0]['revised_prompt'];
  104. // Download and save the image locally
  105. $filesystem = new Filesystem();
  106. $localDir = $this->getParameter('kernel.project_dir') . '/public/uploads/images';
  107. $localFileName = uniqid('image_') . '.png';
  108. $localPath = $localDir . '/' . $localFileName;
  109. if (!$filesystem->exists($localDir)) {
  110. $filesystem->mkdir($localDir);
  111. }
  112. // Download image content
  113. $imageContent = file_get_contents($imageUrl);
  114. file_put_contents($localPath, $imageContent);
  115. // Update the response to include the new path
  116. $responseContent['data'][0]['url'] = '/uploads/images/' . $localFileName;
  117. $responseContent['data'][0]['revised_prompt'] = $revisedPrompt;
  118. } catch (\Exception $e) {
  119. return new JsonResponse(['error' => $e->getMessage()], 500);
  120. }
  121. return new JsonResponse($responseContent);
  122. }
  123. /**
  124. * @Route("/ai/editor-link",methods={"GET"},name="editor_link")
  125. */
  126. public function EditorLink(Request $request)
  127. {
  128. $data = [];
  129. $shortCode = [];
  130. $_locale = $request->getLocale();
  131. $bloc_ai = $this->getDoctrine()->getRepository(HistoriqueBlocAi::class)->findAll();
  132. $posts = $this->getDoctrine()->getRepository(Post::class)->findAll();
  133. $categories = $this->getDoctrine()->getRepository(Category::class)->findCategorie();
  134. if($bloc_ai){
  135. foreach ($bloc_ai as $key => $value) {
  136. $shortCode[] = $value->getShortCode();
  137. }
  138. }
  139. if($posts){
  140. foreach($posts as $value){
  141. if($value->getAlias() != 'page-home'){
  142. $data[] = ['name'=> $value->translate($_locale)->getTitle(),'url'=> '/'.$value->translate($_locale)->getSlug()];
  143. }
  144. }
  145. }
  146. if ($categories) {
  147. foreach($categories as $value){
  148. $data[] = ['name'=> $value['titre'],'url'=> '/'.$value['slug']];
  149. }
  150. }
  151. return new JsonResponse(['url'=> $data,'shortCode'=> $shortCode]);
  152. }
  153. }