Skip to content

Commit

Permalink
Merge branch 'esteban' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
QuitoTactico committed Nov 20, 2024
2 parents 4e8fb02 + 702a50f commit 2048a0f
Show file tree
Hide file tree
Showing 9 changed files with 164 additions and 22 deletions.
30 changes: 15 additions & 15 deletions app/Http/Controllers/GameController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@

namespace App\Http\Controllers;

use App\Interfaces\BalanceGenerator;
use App\Models\Game;
use App\Utils\FormattingUtils;
use Exception;
use Gemini;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
Expand Down Expand Up @@ -101,26 +100,17 @@ public function mostPurchased(Request $request): View
return view('game.mostPurchased')->with('viewData', $viewData);
}

public function generateBalance(Request $request, string $id): RedirectResponse
public function generateBalance(Request $request, string $id, string $type): RedirectResponse
{
try {
$game = Game::findOrFail($id);
$reviews = $game->getReviews();
$comments = $reviews->pluck('comment')->implode(' | ');

$prompt = "Generate a summary of the balance of the next comments about the game {$game->getName()} that has a rating of {$game->getRating()}, also, say the reasons of the good and bad comments, that's the vital part: {$comments}";

$apiKey = env('GEMINI_API_KEY');
$client = Gemini::client($apiKey);

$result = $client->geminiPro()->generateContent($prompt);

$balanceMarkdown = $result->text();
$balanceHtml = FormattingUtils::convertMarkdownToHtml($balanceMarkdown);
$balanceGenerator = app(BalanceGenerator::class, ['type' => $type]);
$balanceHtml = $balanceGenerator->generateBalance($game);

$game->setBalance($balanceHtml);
$game->setBalanceDate(now());
$game->setBalanceReviewsCount($reviews->count());
$game->setBalanceReviewsCount($game->getReviews()->count());
$game->save();

return redirect()->route('game.show', ['id' => $id])->with('viewData', ['success' => 'Balance generated successfully!']);
Expand All @@ -130,4 +120,14 @@ public function generateBalance(Request $request, string $id): RedirectResponse
return redirect()->route('error.nonexistent')->with('viewData', $viewData);
}
}

public function generateBalanceGemini(Request $request, string $id): RedirectResponse
{
return $this->generateBalance($request, $id, 'gemini');
}

public function generateBalanceHuggingFace(Request $request, string $id): RedirectResponse
{
return $this->generateBalance($request, $id, 'huggingface');
}
}
12 changes: 12 additions & 0 deletions app/Interfaces/BalanceGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

// Esteban

namespace App\Interfaces;

use app\Models\Game;

interface BalanceGenerator
{
public function generateBalance(Game $game): string;
}
40 changes: 40 additions & 0 deletions app/Providers/BalanceGeneratorServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

// Esteban

namespace App\Providers;

use App\Interfaces\BalanceGenerator;
use App\Util\BalanceGemini;
use App\Util\BalanceHuggingFace;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;

class BalanceGeneratorServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
$this->app->bind(BalanceGenerator::class, function (Application $app, array $params): BalanceGenerator {
$type = $params['type'] ?? 'gemini';

switch ($type) {
case 'huggingface':
return new BalanceHuggingFace;
case 'gemini':
default:
return new BalanceGemini;
}
});
}

/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}
30 changes: 30 additions & 0 deletions app/Util/BalanceGemini.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

// Esteban

namespace App\Util;

use App\Interfaces\BalanceGenerator;
use App\Models\Game;
use Gemini;

class BalanceGemini implements BalanceGenerator
{
public function generateBalance(Game $game): string
{
$reviews = $game->getReviews();
$comments = $reviews->pluck('comment')->implode(' | ');

$prompt = "Generate a summary of the balance of the next comments about the game {$game->getName()} that has a rating of {$game->getRating()}, also, say the reasons of the good and bad comments, that's the vital part: {$comments}";

$apiKey = env('GEMINI_API_KEY');
$client = Gemini::client($apiKey);

$result = $client->geminiPro()->generateContent($prompt);

$balanceMarkdown = "**Made with Gemini**\n\n".$result->text();
$balanceHtml = FormattingUtil::convertMarkdownToHtml($balanceMarkdown);

return $balanceHtml;
}
}
50 changes: 50 additions & 0 deletions app/Util/BalanceHuggingFace.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

// Esteban

namespace App\Util;

use App\Interfaces\BalanceGenerator;
use App\Models\Game;
use Illuminate\Support\Facades\Http;

class BalanceHuggingFace implements BalanceGenerator
{
public function generateBalance(Game $game): string
{
$reviews = $game->getReviews();
$comments = $reviews->map(fn ($review) => "{$review->comment}")->implode('. ');

// Configura las preguntas
$positiveQuestion = "From the following reviews, give me all the positive aspects mentioned about the game '{$game->getName()}'. Be so detailed, answer in english and use complete sentences.";
$negativeQuestion = "From the following reviews, give me all the negative aspects mentioned about the game '{$game->getName()}'. Be so detailed, answer in english and use complete sentences.";

// Obtén respuestas para ambas preguntas
$positiveAnswer = $this->askQuestion($positiveQuestion, $comments);
$negativeAnswer = $this->askQuestion($negativeQuestion, $comments);

// Genera el resultado en formato Markdown
$balanceMarkdown = "**Made with HuggingFace**\n\n";
$balanceMarkdown .= "**A Positive Comment:**\n".$positiveAnswer."\n\n";
$balanceMarkdown .= "**A Negative Comment:**\n".$negativeAnswer;

// Convierte el Markdown a HTML
return FormattingUtil::convertMarkdownToHtml($balanceMarkdown);
}

private function askQuestion(string $question, string $context): string
{
$apiKey = env('HUGGINGFACE_API_KEY');

$response = Http::withHeaders([
'Authorization' => "Bearer $apiKey",
])->post('https://api-inference.huggingface.co/models/deepset/roberta-base-squad2', [
'inputs' => [
'question' => $question,
'context' => $context,
],
]);

return $response->json()['answer'] ?? 'No answer found.';
}
}
4 changes: 2 additions & 2 deletions app/Utils/FormattingUtils.php → app/Util/FormattingUtil.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?php

namespace App\Utils;
namespace App\Util;

class FormattingUtils
class FormattingUtil
{
public static function convertMarkdownToHtml(string $markdown): string
{
Expand Down
1 change: 1 addition & 0 deletions bootstrap/providers.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@

return [
App\Providers\AppServiceProvider::class,
App\Providers\BalanceGeneratorServiceProvider::class,
];
11 changes: 8 additions & 3 deletions resources/views/game/show.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,15 @@
<button type="submit" class="btn btn-primary">{{ __('Add to Cart') }}</button>
</form>
@auth
@if(Auth::user()->is_admin)
<form action="{{ route('game.generateBalance', ['id' => $viewData['game']->getId()]) }}" method="POST" class="d-inline">
@if(Auth::user()->getIsAdmin())
<form action="{{ route('game.generateBalanceGemini', ['id' => $viewData['game']->getId()]) }}" method="POST" class="d-inline">
@csrf
<button type="submit" class="btn btn-secondary">{{ __('Generate Balance') }}</button>
<button type="submit" class="btn btn-secondary">{{ __('Generate Balance (Gemini)') }}</button>
</form>

<form action="{{ route('game.generateBalanceHuggingFace', ['id' => $viewData['game']->getId()]) }}" method="POST" class="d-inline">
@csrf
<button type="submit" class="btn btn-secondary">{{ __('Generate Balance (HuggingFace)') }}</button>
</form>
@endif
@endauth
Expand Down
8 changes: 6 additions & 2 deletions routes/web.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
<?php

// Esteban, Jonathan, Samuel

use App\Http\Middleware\AdminMiddleware;
use App\Http\Middleware\LanguageMiddleware;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

// Language change route
// ========================== LANGUAGE =================================
Route::get('lang/{locale}', 'App\Http\Controllers\LocaleController@setLocale')->name('locale.setLocale');

// ========================== GUEST USER =================================
Expand Down Expand Up @@ -47,7 +49,8 @@
// ========================== ADMIN ================================
Route::middleware(['auth', AdminMiddleware::class, LanguageMiddleware::class])->group(function () {
// Games (User)
Route::post('/games/{id}/generate-balance', 'App\Http\Controllers\GameController@generateBalance')->name('game.generateBalance');
Route::post('/games/{id}/generate-balance-gemini', 'App\Http\Controllers\GameController@generateBalanceGemini')->name('game.generateBalanceGemini');
Route::post('/games/{id}/generate-balance-huggingface', 'App\Http\Controllers\GameController@generateBalanceHuggingFace')->name('game.generateBalanceHuggingFace');

// Games (Admin)
Route::get('/admin/games', 'App\Http\Controllers\Admin\AdminGameController@index')->name('admin-game.index');
Expand Down Expand Up @@ -85,4 +88,5 @@
// ========================== ERRORS =================================
Route::get('/errors/nonexistent', 'App\Http\Controllers\ErrorController@nonexistent')->name('error.nonexistent');

// ========================== AUTH =================================
Auth::routes();

0 comments on commit 2048a0f

Please sign in to comment.