File size: 27,582 Bytes
5f32fbd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 | <?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\OpenAIGenerator;
use App\Models\PaymentPlans;
use App\Models\Setting;
use App\Models\SettingTwo;
use App\Models\UserFavorite;
use App\Models\UserOpenai;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use OpenAI;
use OpenAI\Laravel\Facades\OpenAI as FacadesOpenAI;
use Symfony\Component\HttpFoundation\File\File;
class AIWriterController extends Controller
{
protected $client;
protected $settings;
protected $settings_two;
public const STABLEDIFFUSION = 'stablediffusion';
public const STORAGE_S3 = 's3';
public const STORAGE_LOCAL = 'public';
public function __construct()
{
//Settings
$this->settings = Setting::first();
$this->settings_two = SettingTwo::first();
// Fetch the Site Settings object with openai_api_secret
if ($this->settings?->user_api_option) {
$apiKeys = explode(',', auth()->user()?->api_keys);
} else {
$apiKeys = explode(',', $this->settings?->openai_api_secret);
}
$apiKey = $apiKeys[array_rand($apiKeys)];
config(['openai.api_key' => $apiKey]);
set_time_limit(120);
}
/**
* @OA\Get(
* path="/api/aiwriter/generator/{slug}",
* operationId="openAIGeneratorApi",
* tags={"AI Writer"},
* security={{ "passport": {} }},
* summary="returns the openai writer info and related user generated docs",
* description="Retrieve details of an OpenAI generator by slug",
*
* @OA\Parameter(
* name="slug",
* in="path",
* description="Slug of the OpenAI generator",
* required=true,
*
* @OA\Schema(type="string")
* ),
*
* @OA\Response(
* response=200,
* description="Successful operation",
*
* @OA\JsonContent(
* type="object",
*
* @OA\Property(property="openai", type="object"),
* @OA\Property(property="userOpenai", type="object"),
* ),
* ),
*
* @OA\Response(
* response=404,
* description="OpenAI generator not found",
*
* @OA\JsonContent(
* type="object",
*
* @OA\Property(property="error", type="string", example="Resource not found"),
* ),
* ),
* )
*/
public function openAIGeneratorApi($slug)
{
try {
$openai = OpenAIGenerator::whereSlug($slug)->firstOrFail();
$userOpenai = UserOpenai::where('user_id', Auth::id())->where('openai_id', $openai->id)->orderBy('created_at', 'desc')->get();
return response()->json([
'openai' => $openai,
'userOpenai' => $userOpenai,
], 200);
} catch (Exception $e) {
return response()->json(['error' => __('Resource not found')], 404);
}
}
/**
* @OA\Get(
* path="/api/aiwriter/generator/{slug}/workbook",
* operationId="openAIGeneratorWorkbookApi",
* tags={"AI Writer"},
* security={{ "passport": {} }},
* summary="returns the openai writer info ",
* description="Retrieve details of an OpenAI generator workbook by slug",
*
* @OA\Parameter(
* name="slug",
* in="path",
* description="Slug of the OpenAI generator",
* required=true,
*
* @OA\Schema(type="string")
* ),
*
* @OA\Response(
* response=200,
* description="Successful operation",
*
* @OA\JsonContent(
* type="object",
*
* @OA\Property(property="openai", type="object"),
* ),
* ),
*
* @OA\Response(
* response=404,
* description="OpenAI generator not found",
*
* @OA\JsonContent(
* type="object",
*
* @OA\Property(property="error", type="string", example="Resource not found"),
* ),
* ),
* )
*/
public function openAIGeneratorWorkbookApi($slug)
{
try {
$openai = OpenAIGenerator::whereSlug($slug)->firstOrFail();
return response()->json([
'openai' => $openai,
], 200);
} catch (Exception $e) {
return response()->json(['error' => __('Resource not found')], 404);
}
}
/**
* @OA\Post(
* path="/api/aiwriter/generate-output",
* summary="Streaming Text Output",
* description="Handle streamed text output based on specified parameters.",
* tags={"AI Writer"},
* security={{ "passport": {} }},
*
* @OA\Parameter(
* name="message_id",
* in="query",
* required=true,
* description="ID of the message",
*
* @OA\Schema(type="integer", example=1),
* ),
*
* @OA\Parameter(
* name="creativity",
* in="query",
* required=true,
* description="Creativity level for the generated content (0 to 1)",
*
* @OA\Schema(type="integer", example=1),
* ),
*
* @OA\Parameter(
* name="maximum_length",
* in="query",
* required=true,
* description="Maximum length of the generated text",
*
* @OA\Schema(type="integer", example=500),
* ),
*
* @OA\Parameter(
* name="number_of_results",
* in="query",
* required=true,
* description="Number of summary results to generate",
*
* @OA\Schema(type="integer", example=1),
* ),
*
* @OA\Response(
* response=200,
* description="Successful response",
*
* @OA\JsonContent(
*
* @OA\Property(property="status", type="string", example="DONE"),
* ),
* ),
*
* @OA\Response(
* response=412,
* description="Precondition Failed",
* ),
* @OA\Response(
* response=500,
* description="Error response",
*
* @OA\JsonContent(
*
* @OA\Property(property="error", type="string", example="Error from API call. Please try again."),
* ),
* ),
* )
*/
public function streamedTextOutput(Request $request)
{
if ($request->message_id == null) {
return response()->json(['error' => __('Message ID is required')], 412);
}
if ($request->creativity == null) {
return response()->json(['error' => __('Creativity is required')], 412);
}
if ($request->maximum_length == null) {
return response()->json(['error' => __('Max length is required')], 412);
}
if ($request->number_of_results == null) {
return response()->json(['error' => __('Number of results is required')], 412);
}
$user = Auth::user();
if ($user->remaining_words != -1) {
if ($user->remaining_words <= 0) {
return response()->json(['error' => __('You have no remaining words. Please upgrade your plan.')], 412);
}
}
$settings = $this->settings;
$message_id = $request->message_id;
$message = UserOpenai::whereId($message_id)->first();
$prompt = $message->input;
$youtube_url = $request->youtube_url;
$rss_image = $request->rss_image;
$creativity = $request->creativity;
$maximum_length = $request->maximum_length;
$number_of_results = $request->number_of_results;
return Response::stream(function () use ($prompt, $message_id, $settings, $creativity, $maximum_length, $number_of_results, $youtube_url, $rss_image) {
try {
if ($settings->openai_default_model == 'text-davinci-003') {
$stream = FacadesOpenAI::completions()->createStreamed([
'model' => $this->settings->openai_default_model,
'prompt' => $prompt,
'temperature' => (int) $creativity,
'max_tokens' => (int) $maximum_length,
'n' => (int) $number_of_results,
]);
} else {
if ((int) $number_of_results > 1) {
$prompt = $prompt . ' number of results should be ' . (int) $number_of_results;
}
$stream = FacadesOpenAI::chat()->createStreamed([
'model' => $this->settings->openai_default_model,
'messages' => [
['role' => 'user', 'content' => $prompt],
],
]);
}
} catch (Exception $exception) {
$messageError = 'Error from API call. Please try again. If error persists again, please contact the system administrator with this message ' . $exception->getMessage();
//echo 'data: {"error": "'.$messageError.'"}';
echo "error: $messageError"; // defined error: to handle error in frontend
echo "\n\n";
//ob_flush();
flush();
// echo 'data: {"status": "DONE"}';
echo 'data: [DONE]';
echo "\n\n";
//ob_flush();
flush();
usleep(50000);
$stream = []; // empty array to prevent further processing and $stream is undefined error
}
$total_used_tokens = 0;
$output = '';
$responsedText = '';
// Youtube Thumbnail
if ($youtube_url) {
$parsedUrl = parse_url($youtube_url);
if (isset($parsedUrl['query'])) {
parse_str($parsedUrl['query'], $queryParameters);
if (isset($queryParameters['v'])) {
$video_id = $queryParameters['v'];
}
}
$video_thumbnail = sprintf('https://img.youtube.com/vi/%s/maxresdefault.jpg', $video_id);
$contents = file_get_contents($video_thumbnail);
$nameOfImage = "youtube-$video_id.jpg";
//save file on local storage or aws s3
Storage::disk('public')->put($nameOfImage, $contents);
$path = '/uploads/' . $nameOfImage;
$uploadedFile = new File(substr($path, 1));
if (SettingTwo::first()->ai_image_storage == 's3') {
try {
$aws_path = Storage::disk('s3')->put('', $uploadedFile);
unlink(substr($path, 1));
$path = Storage::disk('s3')->url($aws_path);
} catch (Exception $e) {
return response()->json(['status' => 'error', 'message' => 'AWS Error - ' . $e->getMessage()]);
}
}
$output = "<img src=\"$path\" style=\"width:100%\"><br><br>";
$total_used_tokens += 1;
$needChars = 6000 - 1;
echo $output;
//ob_flush();
flush();
usleep(500);
}
// RSS Thumbnail
if ($rss_image) {
$contents = file_get_contents($rss_image);
$nameOfImage = 'rss-' . Str::random(12) . '.jpg';
//save file on local storage or aws s3
Storage::disk('public')->put($nameOfImage, $contents);
$path = '/uploads/' . $nameOfImage;
$uploadedFile = new File(substr($path, 1));
if (SettingTwo::first()->ai_image_storage == 's3') {
try {
$aws_path = Storage::disk('s3')->put('', $uploadedFile);
unlink(substr($path, 1));
$path = Storage::disk('s3')->url($aws_path);
} catch (Exception $e) {
return response()->json(['status' => 'error', 'message' => 'AWS Error - ' . $e->getMessage()]);
}
}
$output = "<img src=\"$path\" style=\"width:100%\"><br><br>";
$total_used_tokens += 1;
$needChars = 6000 - 1;
echo $output;
//ob_flush();
flush();
usleep(500);
}
// Disable output buffering
while (ob_get_level() > 0) {
ob_end_flush();
}
ob_start();
foreach ($stream as $response) {
if ($settings->openai_default_model == 'text-davinci-003') {
if (isset($response->choices[0]->text)) {
$message = $response->choices[0]->text;
$messageFix = str_replace(["\r\n", "\r", "\n"], '<br/>', $message);
$output .= $messageFix;
$responsedText .= $message;
$total_used_tokens += countWords($messageFix);
echo $messageFix;
echo PHP_EOL;
ob_flush();
flush();
usleep(100); //500
}
} else {
if (isset($response['choices'][0]['delta']['content'])) {
$message = $response['choices'][0]['delta']['content'];
$messageFix = str_replace(["\r\n", "\r", "\n"], '<br/>', $message);
$output .= $messageFix;
$responsedText .= $message;
$total_used_tokens += countWords($messageFix);
echo $messageFix;
echo PHP_EOL;
ob_flush();
flush();
usleep(100); //500
}
}
if (connection_aborted()) {
break;
}
}
$message = UserOpenai::whereId($message_id)->first();
$message->response = $responsedText;
$message->output = $output;
$message->hash = Str::random(256);
$message->credits = $total_used_tokens;
$message->words = 0;
$message->save();
$user = Auth::user();
userCreditDecreaseForWord($user, $total_used_tokens, $this->settings->openai_default_model);
// echo 'data: {"status": "DONE"}';
echo "\n\n";
echo 'data: [DONE]';
ob_flush();
flush();
usleep(50000);
}, 200, [
'Cache-Control' => 'no-cache',
'X-Accel-Buffering' => 'no',
'Content-Type' => 'text/event-stream',
]);
}
/**
* @OA\Get(
* path="/api/aiwriter/generate/lazyload",
* summary="Lazy Load Images",
* description="Load images based on the specified parameters.",
* tags={"AI Writer"},
* security={{ "passport": {} }},
*
* @OA\Parameter(
* name="post_type",
* in="query",
* required=true,
* description="Type of post",
*
* @OA\Schema(
* type="string",
* enum={"ai_image_generator"},
* example="ai_image_generator"
* )
* ),
*
* @OA\Parameter(
* name="offset",
* in="query",
* required=false,
* description="Offset for lazy loading",
*
* @OA\Schema(
* type="integer",
* example=0
* )
* ),
*
* @OA\Response(
* response=200,
* description="Successful response",
*
* @OA\JsonContent(
*
* @OA\Property(property="images", type="array", description="Array of images", @OA\Items(type="string")),
* @OA\Property(property="hasMore", type="boolean", description="Indicates whether there are more images")
* )
* ),
*
* @OA\Response(
* response=404,
* description="Post not found",
*
* @OA\JsonContent(
*
* @OA\Property(property="error", type="string", description="Error message")
* )
* )
* )
*/
public function lazyLoadImage(Request $request)
{
$offset = $request->get('offset', 0);
$post_type = $request->get('post_type');
$post = OpenAIGenerator::where('slug', $post_type)->first();
if (! $post) {
return response()->json([
'error' => __('Post not found'),
], 404);
}
$limit = 5;
$images = UserOpenai::where('user_id', Auth::id())
->where('openai_id', $post->id)
->orderBy('created_at', 'desc')
->skip($offset)
->take($limit)
->get();
return response()->json([
'images' => $images,
'hasMore' => $images->count() === $limit,
]);
}
/**
* @OA\Post(
* path="/api/aiwriter/generate/save",
* summary="Low Generate Save",
* description="Save the generated response and update user information.",
* tags={"AI Writer"},
*
* @OA\RequestBody(
* required=true,
*
* @OA\MediaType(
* mediaType="application/json",
*
* @OA\Schema(
* type="object",
*
* @OA\Property(
* property="message_id",
* description="ID of the message",
* type="integer",
* example=1
* ),
* @OA\Property(
* property="response",
* description="Generated response",
* type="string",
* example="This is a generated response."
* ),
* ),
* ),
* ),
*
* @OA\Response(
* response=200,
* description="Successful response",
*
* @OA\JsonContent(
*
* @OA\Property(property="status", type="string", example="Data saved successfully."),
* ),
* ),
*
* @OA\Response(
* response=500,
* description="Error response",
*
* @OA\JsonContent(
*
* @OA\Property(property="error", type="string", example="Error saving data."),
* ),
* ),
* security={{ "passport": {} }},
* )
*/
public function lowGenerateSave(Request $request)
{
$response = $request->response;
$total_user_tokens = countWords($response);
$entry = UserOpenai::find($request->message_id);
$entry->credits = $total_user_tokens;
$entry->words = $total_user_tokens;
$entry->response = $response;
$entry->output = $response;
$entry->save();
$user = Auth::user();
userCreditDecreaseForWord($user, $total_user_tokens, $this->settings->openai_default_model);
return response()->json(['status' => 'Data saved successfully.']);
}
/**
* Gets all AI Generators related to text
*
* @OA\Get(
* path="/api/aiwriter/openai-list",
* operationId="getOpenAIWriterList",
* tags={"AI Writer"},
* security={{ "passport": {} }},
* summary="Gets all AI Generators related to text",
* description="Gets all AI Generators related to text. Controls user access to premium generators.",
*
* @OA\Response(
* response=200,
* description="Successful operation",
*
* @OA\JsonContent(
* type="object",
*
* @OA\Property(property="data", type="array", @OA\Items(type="object")),
* ),
* ),
*
* @OA\Response(
* response=401,
* description="Unauthorized: User not authenticated",
* ),
* )
*/
public function getOpenAIWriterList(Request $request)
{
// Check if user can access the AI Writer premium types
$userId = Auth::user()->id;
$planId = '';
// Get current active subscription
$activeSub = getCurrentActiveSubscription($userId);
if ($activeSub != null) {
$planId = $activeSub->plan_id;
} else {
$activeSub = getCurrentActiveSubscriptionYokkasa($userId);
if ($activeSub != null) {
$planId = $activeSub->plan_id;
}
}
if ($planId != '') {
$plan = PaymentPlans::where([['id', '=', $planId]])->first();
if ($plan->plan_type == 'All' || $plan->plan_type == 'all' || $plan->plan_type == 'premium' || $plan->plan_type == 'Premium') {
$aiList = OpenAIGenerator::where([['type', '=', 'text']])->get();
return response()->json($aiList, 200);
}
}
$aiList = OpenAIGenerator::where([['type', '=', 'text'], ['premium', '=', false]])->get();
return response()->json($aiList, 200);
}
/**
* Gets favorite openai list
*
* @OA\Get(
* path="/api/aiwriter/favorite-openai-list",
* operationId="favoriteOpenaiList",
* tags={"AI Writer"},
* summary="Gets favorite openai list",
* description="Returns favorite openai id list of current user.",
* security={{ "passport": {} }},
*
* @OA\Response(
* response=200,
* description="Successful operation",
*
* @OA\JsonContent(
* type="object",
* ),
* ),
*
* @OA\Response(
* response=401,
* description="Unauthenticated",
* ),
* )
*/
public function favoriteOpenaiList(Request $request)
{
$userId = Auth::user()->id;
$favoriteList = UserFavorite::where([['user_id', '=', $userId]])->pluck('openai_id')->toArray();
return response()->json($favoriteList, 200);
}
/**
* Add favorite openai list
*
* @OA\Post(
* path="/api/aiwriter/favorite-openai-list-add",
* operationId="addToFavoriteOpenaiList",
* tags={"AI Writer"},
* summary="Adds openai to favorite openai list",
* description="Returns favorite openai id list of current user.",
* security={{ "passport": {} }},
*
* @OA\Parameter(
* name="openai_id",
* in="query",
* required=true,
* description="OpenAI ID",
*
* @OA\Schema(
* type="integer",
* example=0
* )
* ),
*
* @OA\Response(
* response=200,
* description="Successful operation",
*
* @OA\JsonContent(
* type="object",
* ),
* ),
*
* @OA\Response(
* response=401,
* description="Unauthenticated",
* ),
* @OA\Response(
* response=412,
* description="Precondition Failed",
* ),
* )
*/
public function addToFavoriteOpenaiList(Request $request)
{
if ($request->openai_id == null) {
return response()->json(['error' => __('OpenAI ID is required')], 412);
}
$openAi = OpenAIGenerator::where([['id', '=', $request->openai_id]])->first();
if ($openAi == null) {
return response()->json(['error' => __('OpenAI not found')], 412);
}
$userId = Auth::user()->id;
$favorite = new UserFavorite;
$favorite->user_id = $userId;
$favorite->openai_id = $openAi->id;
$favorite->save();
$favoriteList = UserFavorite::where([['user_id', '=', $userId]])->pluck('openai_id')->toArray();
return response()->json($favoriteList, 200);
}
/**
* Remove from favorite openai list
*
* @OA\Post(
* path="/api/aiwriter/favorite-openai-list-remove",
* operationId="removeFromFavoriteOpenaiList",
* tags={"AI Writer"},
* summary="Removes openai from favorite openai list",
* description="Returns favorite openai id list of current user.",
* security={{ "passport": {} }},
*
* @OA\Parameter(
* name="openai_id",
* in="query",
* required=true,
* description="OpenAI ID",
*
* @OA\Schema(
* type="integer",
* example=0
* )
* ),
*
* @OA\Response(
* response=200,
* description="Successful operation",
*
* @OA\JsonContent(
* type="object",
* ),
* ),
*
* @OA\Response(
* response=401,
* description="Unauthenticated",
* ),
* @OA\Response(
* response=404,
* description="Not found",
* ),
* @OA\Response(
* response=412,
* description="Precondition Failed",
* ),
* )
*/
public function removeFromFavoriteOpenaiList(Request $request)
{
if ($request->openai_id == null) {
return response()->json(['error' => __('OpenAI ID is required')], 412);
}
$openAi = OpenAIGenerator::where([['id', '=', $request->openai_id]])->first();
if ($openAi == null) {
return response()->json(['error' => __('OpenAI not found')], 412);
}
$userId = Auth::user()->id;
$isFavorite = UserFavorite::where([['user_id', '=', $userId], ['openai_id', '=', $openAi->id]])->first();
if ($isFavorite == null) {
return response()->json(['error' => __('OpenAI is not in your favorite list')], 404);
}
$isFavorite->delete();
$favoriteList = UserFavorite::where([['user_id', '=', $userId]])->pluck('openai_id')->toArray();
return response()->json($favoriteList, 200);
}
}
|