0% found this document useful (0 votes)
26 views

Code

The document describes seeding data into a database table for HTML generator templates. It includes PHP code to create sample template records for a blog post and contact page template, each with user ID, title, content, HTML sections, and type.

Uploaded by

imtiaze.techvill
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Code

The document describes seeding data into a database table for HTML generator templates. It includes PHP code to create sample template records for a blog post and contact page template, each with user ID, title, content, HTML sections, and type.

Uploaded by

imtiaze.techvill
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 16

<?

php

namespace Modules\OpenAI\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Modules\OpenAI\Entities\Archive;

class HtmlGeneratorTemplatesSeeder extends Seeder


{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Model::unguard();

$data = [
[
'user_id' => 1,
'title' => 'Blog Post',
'content' => 'A blog post is a brief, online article that conveys
information, opinions, or insights on a particular subject.',
'html_section' => '["header", "main_content", "sidebar", "footer",
"pagination", "search_bar", "category_tag_filters", "author_info",
"subscribe_section", "social_media_links", "footer"]',
'type' => 'html_template'
],
[
'user_id' => 1,
'title' => 'Contact Us',
'content' => '"Contact Us" page: Simplifies communication with a
form, contact details, and social links for seamless interaction.',
'html_section' => '["contact_form", "contact_information", "map",
"social_media_links", "business_hours", "additional_contact_options", "faqs",
"submission_confirmation", "privacy_policy_link", "call_to_action"]',
'type' => 'html_template'
],

];

foreach ($data as $value) {


Archive::create($value);
}
}
}
<?php

namespace App\Traits;

use App\Http\Controllers\Backend\AI\GenerateContentsController;
use App\Http\Controllers\Backend\AI\ParsePromptsController;
use App\Models\SubscriptionPackage;
use Illuminate\Http\Request;
use Orhanerday\OpenAi\OpenAi;
use App\Models\AiBlogWizard;
use App\Models\AiBlogWizardArticle;
use App\Models\AiBlogWizardImage;
use App\Models\AiBlogWizardKeyWord;
use App\Models\AiBlogWizardOutline;
use App\Models\AiBlogWizardTitle;
use Illuminate\Support\Facades\File;
use Str;

trait PopulateWizardData
{
# open ai instance for blog wizard
public function openAiInstance(){
$status = true;
$message = '';
$open_ai = new OpenAi(openAiKey());

$return = [
'status' =>$status,
'open_ai' =>$open_ai,
'message' =>$message
];

# verify if user has access to the template [template available in


subscription package]
$user = auth()->user();
if ($user->user_type == "customer") {
$package = optional(activePackageHistory())->subscriptionPackage ?? new
SubscriptionPackage;

if ($package->allow_blog_wizard == 0) {
$return = [
'status' => $status ,
'open_ai' => $open_ai,
'message' => localize('You are not allowed to use blog
wizard')
];
}

// check package balance


$checkBalanceData = activePackageBalance();
if (!empty($checkBalanceData)) {
return $return;
}
// check word limit
if (availableDataCheck('words') <= 0) {
$return = [
'status' => false,
'open_ai' => $open_ai,
'message' => localize('Your word balance is low, please
upgrade you plan')
];
}
$return['activePackageHistory'] = activePackageHistory();
}
return $return;
}

public function firstStep()


{
\Log::info('######*');
$checkOpenAiInstance = $this->openAiInstance();
$open_ai = $checkOpenAiInstance['open_ai'];

$aiParams['messages'] = [[
"role" => "user",
"content" => 'I want to design a responsive landing page of a website.
Can you get the idea from the text mentioned here "I want to generate a Landing
Page for my FastFood Shop".
What type of webpage is mentioned? Just mention the idea in a array as
a single element. Give the output as an array'
]];
$result = $open_ai->chat($aiParams);
$result = json_decode($result, true);
// dd($result);
// dd($result);
if (isset($result['choices'])) {
$a = $result['choices'][0]['message']['content'];
$jsonString = str_replace("'", '"', $a);
// dd($a);
$arr = json_decode($a, true);
return $arr !== null ? $arr : [];
}
return [];
}

public function secondStep($pageName)


{
$checkOpenAiInstance = $this->openAiInstance();
$open_ai = $checkOpenAiInstance['open_ai'];

$message = 'What are the section does a "' . $pageName . '" webpage
contain? Mention at least 10 section name or more. Each section name must be an
array element, give the output only as array.';

$aiParams['messages'] = [[
"role" => "user",
"content" => $message
]];

$result = $open_ai->chat($aiParams);
$result = json_decode($result, true);
// dd($result);
if (isset($result['choices'])) {
$a = $result['choices'][0]['message']['content'];
// dd($a);
$jsonString = str_replace("'", '"', $a);
// dd($a);
$arr = json_decode($a, true);
return $arr !== null ? $arr : [];
}
return [];

// $outputContents = $result['choices'][0]['message']['content'];
}

# generate keywords
public function generateKeywords(Request $request){
$user = auth()->user();
$checkOpenAiInstance = $this->openAiInstance();

if($checkOpenAiInstance['status'] == true){
// generate here
$prompt = $request->topic;

// filter bad words


$parsePromptController = new ParsePromptsController;
$foundBadWords = $parsePromptController->filterBadWords($request-
>all());
if ($foundBadWords != '') {
$prompt = "bad_words_found_#themeTags" . $foundBadWords;
if (preg_match("/bad_words_found/i", $prompt) == 1) {
$badWords = explode('_#themeTags', rtrim($prompt, ","));
$data = [
'status' => 400,
'success' => false,
'message' => localize('Please remove these words from your
inputs') . '-' . $badWords[1],
];
return $data;
}
}

# ai prompt
$prompt = "Generate $request->number_of_results seo friendly keywords
based on this topic: $request->topic, each keywords must be an array element, give
the output as an array.";

# apply openAi model based on admin configuration


$model = 'gpt-3.5-turbo-16k';
//
$num_of_results = 1;
$temperature = 1; // high
$aiParams = [
'model' => $model,
'temperature' => $temperature,
'n' => $num_of_results,
'messages' => [
[
"role" => "user",
"content" => $prompt
]
]
];

# make api call to openAi


// $open_ai = $checkOpenAiInstance['open_ai'];

// First Step
// $aiParams['messages'] = [[
// "role" => "user",
// "content" => 'I want to design a responsive landing page of a
website. Can you get the idea from the text mentioned here "I want to generate a
Landing Page for my FastFood Shop".
// What type of webpage is mentioned? Just mention the idea in a
array as a single element. Give the output as an array'
// ]];
// $result = $open_ai->chat($aiParams);
// $result = json_decode($result, true);

// $outputContents = $result['choices'][0]['message']['content'];
// $pageName = json_decode($outputContents);
$pageNameArray = $this->firstStep();
$count = 1;
while(!is_array($pageNameArray)) {
$count++;
if ($count > 10) {

$pageNameArray = $this->firstStep();
break;
}
}
if (empty($pageNameArray)) {
dd('first stop');
}
$pageName = $pageNameArray[0];
// dd($pageName, 'Is it');

// 2nd Step
// $pageName = 'Contact Us page for an ecommerce site';
// $message = 'What are the section does a "' . $pageName . '" webpage
contain? Mention at least 10 section name or more. Each section name must be an
array element, give the output only as an PHP array.';

// $aiParams['messages'] = [[
// "role" => "user",
// "content" => $message
// ]];

// $result = $open_ai->chat($aiParams);
// $result = json_decode($result, true);
// // dd($result);

// $outputContents = $result['choices'][0]['message']['content'];
// \Log::info($outputContents);
$sectionArray = $this->secondStep($pageName);

$count = 1;
while(!is_array($pageNameArray)) {
$count++;
if ($count > 10) {

$sectionArray = $this->firstStep();
break;
}
}
if (empty($sectionArray)) {
dd('2md stop');
}
$pageSections = $sectionArray;

// $pageSections = is_array($outputContents) ? $outputContents :


json_decode($outputContents);

$filePath = storage_path('app/newfile.txt');
File::put($filePath, 'hello');
// dd(gettype($pageSections));
// dd('ok');
$open_ai = $checkOpenAiInstance['open_ai'];

foreach ($pageSections as $key => $pageSection) {


// dd('ok');
$message = 'Create a responsive html "'. $pageSection .'" section
for "'. $pageName .'" landing page using tailwind css. Only give the section code.
Don\'t need to add other tags like html or body';
// dd('ok');
$aiParams['messages'] = [[
"role" => "user",
"content" => $message
]];
// dd($aiParams);
$result = $open_ai->chat($aiParams);
$result = json_decode($result, true);
// dd($result);

if (isset($result['choices'])){

$content = $result['choices'][0]['message']['content'];
File::append($filePath, $content);
}

}
dd('ok');

$outputContents = '';
if (isset($result['choices'])) {
$outputContents = $result['choices'][0]['message']['content'];

$tokens = $result['usage']['total_tokens'];
if(!empty($request->ai_blog_wizard_id)){
$keyword =
AiBlogWizardKeyWord::where('ai_blog_wizard_id', $request->ai_blog_wizard_id)-
>first();
$oldValues = json_decode($keyword->values);
$aiBlogWizard = $keyword->aiBlogWizard;
if(is_null($aiBlogWizard)){
$aiBlogWizard = $this->__newBlogWizard($user);
$keyword->ai_blog_wizard_id = $aiBlogWizard->id;
}
$values = array_merge($oldValues,
json_decode($outputContents));
$keyword->topic = $request->topic;
$keyword->num_of_copies += 1;
$keyword->values = json_encode($values);
}else{
$aiBlogWizard = $this->__newBlogWizard($user);
$keyword = new AiBlogWizardKeyWord;
$keyword->created_by = $user->id;
$keyword->ai_blog_wizard_id = $aiBlogWizard->id;
$keyword->topic = $request->topic;
$keyword->values = $outputContents;
}

$keyword->total_words += $tokens;
$keyword->save();

$aiBlogWizard->completed_step = 1;
$aiBlogWizard->total_words += $keyword->total_words;
$aiBlogWizard->save();

# 8. update word limit for user or admin/staff


$generateContentsController = new GenerateContentsController;
$generateContentsController->updateUserWords($tokens, $user);

$data = [
'status' => 200,
'success' => true,
'ai_blog_wizard_id' => $keyword->ai_blog_wizard_id ??
'',
'keywords' => json_decode($keyword->values),
'output' =>
view('backend.pages.blogWizard.stepsData.keywords', ['keywords'=>
json_decode($keyword->values)])->render(),
'usedPercentage' =>
view('backend.pages.templates.inc.used-words-percentage')->render(),
];
return $data;
} else {
if (isset($result['error']['message'])) {
$message = $result['error']['message'];
} else {
$message = localize('There is an issue with the open ai
account');
}
$data = [
'status' => 400,
'success' => false,
'message' => $message
];
return $data;
}
}else{
return $checkOpenAiInstance;
}
}

# new blog wizard


private function __newBlogWizard($user){
$aiBlogWizard = new AiBlogWizard;
$aiBlogWizard->user_id = $user->id;
$aiBlogWizard->created_by = $user->id;
$aiBlogWizard->uuid = Str::uuid();
$aiBlogWizard->save();
return $aiBlogWizard;
}

# generate titles
public function generateTitles(Request $request){
$user = auth()->user();
$checkOpenAiInstance = $this->openAiInstance();

if($checkOpenAiInstance['status'] == true){
// generate here
$prompt = "Topic: $request->topic. Keywords: $request-
>keywords";

// filter bad words


$parsePromptController = new ParsePromptsController;
$foundBadWords = $parsePromptController->filterBadWords($request-
>all());
if ($foundBadWords != '') {
$prompt = "bad_words_found_#themeTags" . $foundBadWords;
if (preg_match("/bad_words_found/i", $prompt) == 1) {
$badWords = explode('_#themeTags', rtrim($prompt, ","));
$data = [
'status' => 400,
'success' => false,
'message' => localize('Please remove these words from your
inputs') . '-' . $badWords[1],
];
return $data;
}
}

# ai prompt
$prompt = "Generate $request->number_of_results seo friendly titles in
$request->lang language based on these topic & keywords. Topic: $request->topic,
Keywords: $request->keywords, each titles must be an array element, give the output
as an array.";

# apply openAi model based on admin configuration


$model = getSetting('ai_blog_wizard_model') ?? 'gpt-3.5-turbo-16k';

//
$num_of_results = 1;
$temperature = 1; // high
$aiParams = [
'model' => $model,
'temperature' => $temperature,
'n' => $num_of_results,
'messages' => [
[
"role" => "user",
"content" => $prompt
]
]
];

# make api call to openAi


$open_ai = $checkOpenAiInstance['open_ai'];
$aiParams['messages'] = [[
"role" => "user",
"content" => $prompt
]];
$result = $open_ai->chat($aiParams);

$result = json_decode($result, true);

$outputContents = '';
if (isset($result['choices'])) {

$outputContents = $result['choices'][0]['message']['content'];

$tokens = $result['usage']['total_tokens'];

if(!empty($request->ai_blog_wizard_id)){
$aiBlogWizard = AiBlogWizard::whereId($request-
>ai_blog_wizard_id)->first();
$title =
AiBlogWizardTitle::where('ai_blog_wizard_id', $request->ai_blog_wizard_id)-
>first();
if(!is_null($title)){
$oldValues = json_decode($title-
>values) ?? [];
$values = array_merge($oldValues,
json_decode($outputContents));
$title->num_of_copies += 1;
$title->values = json_encode($values);
}else{
$title = new AiBlogWizardTitle;
$title->values = $outputContents;
$title->created_by = $user->id;
$title->ai_blog_wizard_id = $aiBlogWizard->id;
}
} else{
$aiBlogWizard = $this->__newBlogWizard($user);
$title = new AiBlogWizardTitle;
$title->values = $outputContents;
$title->created_by = $user->id;
$title->ai_blog_wizard_id = $aiBlogWizard->id;
}

$title->topic = $request->topic;
$title->keywords = $request->keywords;
$title->total_words += $tokens;
$title->save();

$aiBlogWizard->completed_step = 2;
$aiBlogWizard->total_words += $title->total_words;
$aiBlogWizard->save();

# 8. update word limit for user


$generateContentsController = new GenerateContentsController;
$generateContentsController->updateUserWords($tokens, $user);

$data = [
'status' => 200,
'success' => true,
'ai_blog_wizard_id' => $title->ai_blog_wizard_id ?? '',
'titles' => json_decode($title->values),
'output' =>
view('backend.pages.blogWizard.stepsData.titles', ['titles'=> json_decode($title-
>values)])->render(),
'usedPercentage' =>
view('backend.pages.templates.inc.used-words-percentage')->render(),
];
return $data;
} else {
if (isset($result['error']['message'])) {
$message = $result['error']['message'];
} else {
$message = localize('There is an issue with the open ai
account');
}
$data = [
'status' => 400,
'success' => false,
'message' => $message
];
return $data;
}
}else{
return $checkOpenAiInstance;
}
}

# generate images
public function generateImages(Request $request)
{

if (env('DEMO_MODE') == "On") {
$data = [
'status' => false,
'success' => false,
'message' => localize('Image generation is turned off in demo')
];
return $data;
}

$user = auth()->user();
$checkOpenAiInstance = $this->openAiInstance();

if($checkOpenAiInstance['status'] == true){
# verify if user has access [available in subscription package]
if ($user->user_type == "customer") {
// check package balance
$checkBalanceData = activePackageBalance('allow_images');
if (!empty($checkBalanceData)) {
return $checkBalanceData;
}

// check images limit


if (availableDataCheck('images') < (int)$request->num_of_results)
{
$data = [
'status' => 400,
'success' => false,
'message' => localize('Your limit is low, please upgrade
you plan'),
];
return $data;
}
}

# 4. generate prompt in selected language


$parsePromptsController = new ParsePromptsController;
$prompt = $parsePromptsController->images($request-
>all());

# 6. generate image
$n = 1;
$resolution = '512x512';

if (env('DEMO_MODE') == 'Off') {
$n = (int)$request->num_of_results;
$resolution = $request->resolution;
}

$open_ai = $checkOpenAiInstance['open_ai'];
$result = $open_ai->image([
'prompt' => $prompt,
'size' => $resolution,
'n' => $n,
"response_format" => "url",
]);

# parse response
$result = json_decode($result, true);
if (isset($result['data'])) {
if (count($result['data']) > 1) {
foreach ($result['data'] as $key => $value) {
$url = $value['url'];

$name = Str::random(10) . '.png';


$image = file_get_contents($url);
file_put_contents(public_path('images/' . $name), $image);

$aiBlogWizardImage = new AiBlogWizardImage;


$aiBlogWizardImage->created_by = $user->id;
$aiBlogWizardImage->ai_blog_wizard_id = $request-
>ai_blog_wizard_id;
$aiBlogWizardImage->title = $request->title .
'-' . ($key + 1);
$aiBlogWizardImage->resolution = $resolution;
$aiBlogWizardImage->value = 'images/' .
$name;
$aiBlogWizardImage->save();
}
} else {
$url = $result['data'][0]['url'];
$name = Str::random(10) . '.png';
$image = file_get_contents($url);
file_put_contents(public_path('images/' . $name), $image);

$aiBlogWizardImage = new AiBlogWizardImage;


$aiBlogWizardImage->created_by = $user->id;
$aiBlogWizardImage->ai_blog_wizard_id = $request-
>ai_blog_wizard_id;
$aiBlogWizardImage->title = $request->title;
$aiBlogWizardImage->resolution = $resolution;
$aiBlogWizardImage->value = 'images/' . $name;
$aiBlogWizardImage->save();
}

try {
$aiBlogWizard =
AiBlogWizard::whereId($request->ai_blog_wizard_id)->first();
$aiBlogWizard->completed_step = 3;
$aiBlogWizard->save();
} catch (\Throwable $th) {
//throw $th;
}

# Update credit balance


if ($user->user_type == "customer") {
updateDataBalance('images', $n, $user);
}

$imagesArray = AiBlogWizardImage::where('ai_blog_wizard_id',
$request->ai_blog_wizard_id)->latest();
$imageIds = $imagesArray->pluck('id');
$images = $imagesArray->get();

$data = [
'status' => 200,
'success' => true,
'imageIds' => $imageIds,
'images' =>
view('backend.pages.blogWizard.stepsData.images', compact('images'))->render(),
'usedPercentage' => view('backend.pages.templates.inc.used-
images-percentage')->render(),
];
return $data;
} else {
$message = $result['error']['message'];
$data = [
'status' => 400,
'success' => false,
'message' => $message
];
return $data;
}

$data = [
'status' => 500,
'success' => false,
];
return $data;
}else{
return $checkOpenAiInstance;
}
}

# generate outlines
public function generateOutlines(Request $request){
$user = auth()->user();
$checkOpenAiInstance = $this->openAiInstance();

if($checkOpenAiInstance['status'] == true){
// generate here
$prompt = "Title: $request->title. Keywords: $request-
>keywords";

// filter bad words


$parsePromptController = new ParsePromptsController;
$foundBadWords = $parsePromptController->filterBadWords($request-
>all());
if ($foundBadWords != '') {
$prompt = "bad_words_found_#themeTags" . $foundBadWords;
if (preg_match("/bad_words_found/i", $prompt) == 1) {
$badWords = explode('_#themeTags', rtrim($prompt, ","));
$data = [
'status' => 400,
'success' => false,
'message' => localize('Please remove these words from your
inputs') . '-' . $badWords[1],
];
return $data;
}
}

# ai prompt
$prompt = "Generate section headings only to write a blog in $request-
>lang language based on these title & keywords. Title: $request->title, Keywords:
$request->keywords, each section headings must be an array element, give the output
as an array.";

# apply openAi model based on admin configuration


$model = getSetting('ai_blog_wizard_model') ?? 'gpt-3.5-turbo-16k';

//
$num_of_results = (int) $request->num_of_results;
$temperature = 1; // high
$aiParams = [
'model' => $model,
'temperature' => $temperature,
'n' => $num_of_results,
'messages' => [
[
"role" => "user",
"content" => $prompt
]
]
];

# make api call to openAi


$open_ai = $checkOpenAiInstance['open_ai'];
$aiParams['messages'] = [[
"role" => "user",
"content" => $prompt
]];
$result = $open_ai->chat($aiParams);

$result = json_decode($result, true);

$outputContents = '';
if (isset($result['choices'])) {
$aiBlogWizard = AiBlogWizard::whereId($request-
>ai_blog_wizard_id)->first();

if (count($result['choices']) > 1) {
foreach ($result['choices'] as $value) {
$outputContents = $value['message']['content'];
// new outline
$this->__newOutline($user, $aiBlogWizard, $outputContents,
$request->title, $request->keywords);
}
} else {
$outputContents = $result['choices'][0]['message']['content'];
// new outline
$this->__newOutline($user, $aiBlogWizard, $outputContents,
$request->title, $request->keywords);
}

$tokens = $result['usage']['total_tokens'];

$aiBlogWizard->completed_step = 4;
$aiBlogWizard->total_words += $tokens;
$aiBlogWizard->save();

# 8. update word limit for user


$generateContentsController = new GenerateContentsController;
$generateContentsController->updateUserWords($tokens, $user);

$outlines = AiBlogWizardOutline::where('ai_blog_wizard_id',
$aiBlogWizard->id)->latest()->get();

$data = [
'status' => 200,
'success' => true,
'ai_blog_wizard_id' => $request->ai_blog_wizard_id ??
'',
'outlines' => $outlines,
'output' =>
view('backend.pages.blogWizard.stepsData.outlines', ['outlines'=> $outlines])-
>render(),
'usedPercentage' =>
view('backend.pages.templates.inc.used-words-percentage')->render(),
];
return $data;
} else {
if (isset($result['error']['message'])) {
$message = $result['error']['message'];
} else {
$message = localize('There is an issue with the open ai
account');
}
$data = [
'status' => 400,
'success' => false,
'message' => $message
];
return $data;
}
}else{
return $checkOpenAiInstance;
}
}

# new blog outline


private function __newOutline($user, $aiBlogWizard, $outputContents, $title,
$keywords){
$outline = new AiBlogWizardOutline;
$outline->values = $outputContents;
$outline->created_by = $user->id;
$outline->ai_blog_wizard_id = $aiBlogWizard->id;
$outline->title = $title;
$outline->keywords = $keywords;
$outlineWords =
str_word_count(collect(json_decode($outputContents))->implode(' '));
$outline->total_words = $outlineWords;
$outline->save();
}

# populate keywords data


public function populateKeywordsData(Request $request)
{
$data = $request->generatedKeywords ?? [];
return [
'html' => view('backend.pages.blogWizard.stepsData.keywords',
['keywords' => $data])->render()
];
}

# populate titles data


public function populateTitlesData(Request $request)
{
$data = $request->generatedTitles ?? [];
return [
'html' => view('backend.pages.blogWizard.stepsData.titles', ['titles'
=> $data])->render()
];
}

# populate images data


public function populateImagesData(Request $request)
{
$data = $request->generatedImages ?? [];
$images = AiBlogWizardImage::whereIn('id', $data)->get();
return [
'html' => view('backend.pages.blogWizard.stepsData.images',
compact('images'))->render()
];
}

# populate outlines data


public function populateOutlinesData(Request $request)
{
$data = $request->generatedOutlines ?? [];
return [
'html' => view('backend.pages.blogWizard.stepsData.outlines',
['outlines' => $data== null ? [] : $data])->render()
];
}

# populate article data


public function populateArticleData(Request $request)
{
$data = $request->generatedArticle ?? null;
$article = AiBlogWizardArticle::where('id', $data)->first();
return [
'html' => view('backend.pages.blogWizard.stepsData.article',
['article' => $article])->render(),
'id' => $article->id ?? null,
'contents' => $article->value ?? ""
];
}
}

You might also like