the RunwareAI Plugin is working now

This commit is contained in:
2025-07-30 23:24:47 +02:00
parent 07c6786bda
commit 47860b4b7d
35 changed files with 544 additions and 218 deletions

View File

@@ -11,6 +11,5 @@ interface ApiPluginInterface
public function disable(): bool;
public function getStatus(string $imageUUID): array;
public function getProgress(string $imageUUID): array;
public function upload(string $imagePath): array;
public function styleChangeRequest(string $prompt, string $seedImageUUID): array;
public function processImageStyleChange(string $imagePath, string $prompt, string $modelId, ?string $parameters = null): array;
}

View File

@@ -1,106 +0,0 @@
<?php
namespace App\Api\Plugins;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class RunwareAIPlugin implements ApiPluginInterface
{
protected $client;
protected $apiUrl;
protected $apiKey;
public function __construct()
{
// Hier müssten die API-URL und der API-Schlüssel aus der Datenbank oder Konfiguration geladen werden.
// Fürs Erste hardcodiere ich sie als Platzhalter.
$this->apiUrl = env('RUNWARE_AI_API_URL', 'https://api.runware.ai/v1');
$this->apiKey = env('RUNWARE_AI_API_KEY', 'YOUR_RUNWARE_AI_API_KEY');
$this->client = new Client([
'base_uri' => $this->apiUrl,
'headers' => [
'Authorization' => 'Bearer ' . $this->apiKey,
'Accept' => 'application/json',
],
]);
}
public function getIdentifier(): string
{
return 'runware-ai';
}
public function getName(): string
{
return 'Runware AI';
}
public function isEnabled(): bool
{
// Implementieren Sie hier die Logik, um zu prüfen, ob das Plugin aktiviert ist
return true;
}
public function enable(): bool
{
// Implementieren Sie hier die Logik zum Aktivieren des Plugins
return true;
}
public function disable(): bool
{
// Implementieren Sie hier die Logik zum Deaktivieren des Plugins
return true;
}
public function getStatus(string $imageUUID): array
{
try {
$response = $this->client->get("image-inference/status/{$imageUUID}");
return json_decode($response->getBody()->getContents(), true);
} catch (RequestException $e) {
return ['error' => $e->getMessage()];
}
}
public function getProgress(string $imageUUID): array
{
// Runware AI hat keine separate Progress-API, Status enthält den Fortschritt
return $this->getStatus($imageUUID);
}
public function upload(string $imagePath): array
{
try {
$response = $this->client->post('image-inference/upload', [
'multipart' => [
[
'name' => 'image',
'contents' => fopen($imagePath, 'r'),
'filename' => basename($imagePath),
],
],
]);
return json_decode($response->getBody()->getContents(), true);
} catch (RequestException $e) {
return ['error' => $e->getMessage()];
}
}
public function styleChangeRequest(string $prompt, string $seedImageUUID): array
{
try {
$response = $this->client->post('image-inference/image-to-image', [
'json' => [
'prompt' => $prompt,
'seed_image_uuid' => $seedImageUUID,
],
]);
return json_decode($response->getBody()->getContents(), true);
} catch (RequestException $e) {
return ['error' => $e->getMessage()];
}
}
}

View File

@@ -71,7 +71,27 @@ class RunwareAi implements ApiPluginInterface
return ['progress' => 0];
}
public function upload(string $imagePath): array
public function processImageStyleChange(string $imagePath, string $prompt, string $modelId, ?string $parameters = null): array
{
// Step 1: Upload the original image
$uploadResult = $this->upload($imagePath);
if (!isset($uploadResult['data'][0]['imageUUID'])) {
throw new \Exception('Image upload to AI service failed or returned no UUID.');
}
$seedImageUUID = $uploadResult['data'][0]['imageUUID'];
// Step 2: Request style change using the uploaded image's UUID
$result = $this->styleChangeRequest($prompt, $seedImageUUID, $modelId, $parameters);
if (!isset($result['base64Data'])) {
throw new \Exception('AI service did not return base64 image data.');
}
return $result;
}
private function upload(string $imagePath): array
{
$this->logInfo('Attempting to upload image to RunwareAI.', ['image_path' => $imagePath]);
if (!$this->apiProvider->api_url || !$this->apiProvider->token) {
@@ -83,15 +103,19 @@ class RunwareAi implements ApiPluginInterface
$token = $this->apiProvider->token;
$taskUUID = (string) Str::uuid();
$imageData = 'data:image/png;base64,' . base64_encode(file_get_contents($imagePath));
try {
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
])->attach(
'image', file_get_contents($imagePath), basename($imagePath)
)->post($apiUrl, [
'taskType' => 'imageUpload',
'taskUUID' => $taskUUID,
'Content-Type' => 'application/json',
])->post($apiUrl, [
[
'taskType' => 'imageUpload',
'taskUUID' => $taskUUID,
'image' => $imageData,
]
]);
$response->throw();
@@ -103,7 +127,7 @@ class RunwareAi implements ApiPluginInterface
}
}
public function styleChangeRequest(string $prompt, string $seedImageUUID, ?string $parameters = null): array
private function styleChangeRequest(string $prompt, string $seedImageUUID, string $modelId, ?string $parameters = null): array
{
$this->logInfo('Attempting style change request to RunwareAI.', ['prompt' => $prompt, 'seed_image_uuid' => $seedImageUUID]);
if (!$this->apiProvider->api_url || !$this->apiProvider->token) {
@@ -121,6 +145,7 @@ class RunwareAi implements ApiPluginInterface
'positivePrompt' => $prompt,
'seedImage' => $seedImageUUID,
'outputType' => 'base64Data',
'model' => $modelId,
];
$decodedParameters = json_decode($parameters, true) ?? [];
@@ -132,13 +157,28 @@ class RunwareAi implements ApiPluginInterface
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
])->post($apiUrl, $data);
])->post($apiUrl, [
$data
]);
$response->throw();
$this->logInfo('Style change request successful to RunwareAI.', ['task_uuid' => $taskUUID, 'response' => $response->json()]);
return $response->json();
$responseData = $response->json();
if (!isset($responseData['data'][0]['imageBase64Data'])) {
throw new \Exception('AI service did not return base64 image data.');
}
$base64Image = $responseData['data'][0]['imageBase64Data'];
$this->logInfo('Style change request successful to RunwareAI.', ['task_uuid' => $taskUUID, 'response' => $responseData]);
return ['base64Data' => $base64Image];
} catch (\Exception $e) {
$this->logError('Style change request to RunwareAI failed.', ['error' => $e->getMessage(), 'task_uuid' => $taskUUID]);
$errorData = [];
/*if ($e instanceof \Illuminate\Http\Client\RequestException && $e->response) {
$errorData['response_body'] = $e->response->body();
$errorData['response_status'] = $e->response->status();
}*/
$this->logError('Style change request to RunwareAI failed.', ['error' => $e->getMessage(), 'task_uuid' => $taskUUID] + $errorData);
throw $e;
}
}

View File

@@ -18,7 +18,7 @@ class InstallPluginPage extends Page implements HasForms
protected static string $view = 'filament.pages.install-plugin-page';
protected static ?string $navigationGroup = 'Settings';
protected static ?string $navigationGroup = 'Plugins';
protected static ?string $title = 'Install Plugin';

View File

@@ -24,7 +24,7 @@ class ListPlugins extends Page implements HasTable
protected static string $view = 'filament.pages.list-plugins';
protected static ?string $navigationGroup = 'Settings';
protected static ?string $navigationGroup = 'Plugins';
protected static ?string $title = 'Plugins';

View File

@@ -35,12 +35,16 @@ class AiModelResource extends Resource
->required()
->maxLength(255),
TextInput::make('model_type')
->label(__('filament.resource.ai_model.form.model_type'))
->nullable()
->maxLength(255),
Forms\Components\Toggle::make('enabled')
->label(__('filament.resource.ai_model.form.enabled'))
->default(true),
Select::make('apiProviders')
->relationship('apiProviders', 'name')
->multiple()
->preload()
->searchable(false)
->label(__('filament.resource.ai_model.form.api_providers')),
]);
}
@@ -52,6 +56,9 @@ class AiModelResource extends Resource
TextColumn::make('name')->label(__('filament.resource.ai_model.table.name'))->searchable()->sortable(),
TextColumn::make('model_id')->label(__('filament.resource.ai_model.table.model_id'))->searchable()->sortable(),
TextColumn::make('model_type')->label(__('filament.resource.ai_model.table.model_type'))->searchable()->sortable(),
Tables\Columns\IconColumn::make('enabled')
->label(__('filament.resource.ai_model.table.enabled'))
->boolean(),
TextColumn::make('apiProviders.name')->label(__('filament.resource.ai_model.table.api_providers'))->searchable()->sortable(),
])
->filters([

View File

@@ -0,0 +1,67 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\SettingResource\Pages;
use App\Filament\Resources\SettingResource\RelationManagers;
use App\Models\Setting;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
class SettingResource extends Resource
{
protected static ?string $model = Setting::class;
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
public static function form(Form $form): Form
{
return $form
->schema([
//
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
//
])
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
])
->emptyStateActions([
Tables\Actions\CreateAction::make(),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListSettings::route('/'),
'create' => Pages\CreateSetting::route('/create'),
'edit' => Pages\EditSetting::route('/{record}/edit'),
];
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace App\Filament\Resources\SettingResource\Pages;
use App\Filament\Resources\SettingResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
class CreateSetting extends CreateRecord
{
protected static string $resource = SettingResource::class;
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\SettingResource\Pages;
use App\Filament\Resources\SettingResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditSetting extends EditRecord
{
protected static string $resource = SettingResource::class;
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\SettingResource\Pages;
use App\Filament\Resources\SettingResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListSettings extends ListRecords
{
protected static string $resource = SettingResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace App\Filament\Resources\SettingResource\Pages;
use App\Filament\Resources\SettingResource;
use App\Models\Setting;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Illuminate\Database\Eloquent\Model;
class Settings extends Page implements HasForms
{
use InteractsWithForms;
protected static string $resource = SettingResource::class;
protected static ?string $navigationIcon = 'heroicon-o-cog';
protected static ?string $navigationGroup = 'Settings';
protected static ?string $navigationLabel = 'Global Settings';
protected static ?string $slug = 'global-settings';
protected static string $view = 'filament.resources.setting-resource.pages.settings';
public ?array $data = [];
public function mount(): void
{
$this->form->fill(
collect(Setting::all())
->mapWithKeys(fn (Setting $setting) => [$setting->key => $setting->value])
->all()
);
}
public function form(Form $form): Form
{
return $form
->schema([
TextInput::make('gallery_heading')
->label(__('settings.gallery_heading')),
])
->statePath('data')
->model(Setting::class);
}
public function submit(): void
{
foreach ($this->form->getState() as $key => $value) {
Setting::updateOrCreate(['key' => $key], ['value' => $value]);
}
Notification::make()
->title(__('settings.saved_successfully'))
->success()
->send();
}
}

View File

@@ -8,18 +8,48 @@ use App\Api\Plugins\PluginLoader;
use App\Models\ApiProvider;
use App\Models\Style;
use App\Models\Image;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
class ImageController extends Controller
{
public function index()
{
$images = Storage::disk('public')->files('uploads');
$publicUploadsPath = public_path('storage/uploads');
// Ensure the directory exists
if (!File::exists($publicUploadsPath)) {
File::makeDirectory($publicUploadsPath, 0755, true);
}
// Get files from the public/storage/uploads directory
$diskFiles = File::files($publicUploadsPath);
$diskImagePaths = [];
foreach ($diskFiles as $file) {
// Store path relative to public/storage/
$diskImagePaths[] = 'uploads/' . $file->getFilename();
}
$dbImagePaths = Image::pluck('path')->toArray();
// Add images from disk that are not in the database
$imagesToAdd = array_diff($diskImagePaths, $dbImagePaths);
foreach ($imagesToAdd as $path) {
Image::create(['path' => $path]);
}
// Remove images from database that are not on disk
$imagesToRemove = array_diff($dbImagePaths, $diskImagePaths);
Image::whereIn('path', $imagesToRemove)->delete();
// Fetch all images from the database after synchronization
$images = Image::orderBy('updated_at', 'desc')->get();
$formattedImages = [];
foreach ($images as $image) {
$formattedImages[] = [
'path' => Storage::url($image),
'name' => basename($image),
'image_id' => $image->id,
'path' => asset('storage/' . $image->path),
'name' => basename($image->path),
'is_temp' => (bool) $image->is_temp,
];
}
return response()->json($formattedImages);
@@ -31,21 +61,39 @@ class ImageController extends Controller
'image' => 'required|image|max:10240', // Max 10MB
]);
$path = $request->file('image')->store('uploads', 'public');
$file = $request->file('image');
$fileName = uniqid() . '.' . $file->getClientOriginalExtension();
$destinationPath = public_path('storage/uploads');
// Ensure the directory exists
if (!File::exists($destinationPath)) {
File::makeDirectory($destinationPath, 0755, true);
}
$file->move($destinationPath, $fileName);
$relativePath = 'uploads/' . $fileName; // Path relative to public/storage/
$image = Image::create([
'path' => $path,
'path' => $relativePath,
]);
return response()->json([
'message' => __('api.image_uploaded_successfully'),
'image_id' => $image->id,
'path' => Storage::url($path),
'path' => asset('storage/' . $relativePath),
]);
}
public function styleChangeRequest(Request $request)
{
// Same-origin check
$appUrl = config('app.url');
$referer = $request->headers->get('referer');
if ($referer && parse_url($referer, PHP_URL_HOST) !== parse_url($appUrl, PHP_URL_HOST)) {
return response()->json(['error' => 'Unauthorized: Request must originate from the same domain.'], 403);
}
$request->validate([
'image_id' => 'required|exists:images,id',
'style_id' => 'required|exists:styles,id',
@@ -69,32 +117,29 @@ class ImageController extends Controller
}
$plugin = PluginLoader::getPlugin($apiProvider->plugin, $apiProvider);
// Step 1: Upload the original image
$originalImagePath = Storage::disk('public')->path($image->path);
$uploadResult = $plugin->upload($originalImagePath);
if (!isset($uploadResult['imageUUID'])) {
throw new \Exception('Image upload to AI service failed or returned no UUID.');
}
$seedImageUUID = $uploadResult['imageUUID'];
// Step 2: Request style change using the uploaded image's UUID
$result = $plugin->styleChangeRequest($style->prompt, $seedImageUUID, $style->parameters);
if (!isset($result['base64Data'])) {
throw new \Exception('AI service did not return base64 image data.');
}
$result = $plugin->processImageStyleChange(
public_path('storage/' . $image->path),
$style->prompt,
$style->aiModel->model_id,
$style->parameters
);
$base64Image = $result['base64Data'];
$decodedImage = base64_decode(preg_replace('#^data:image/\w+;base64, #i', '', $base64Image));
$newImageName = 'styled_' . uniqid() . '.png'; // Assuming PNG for now
$newImagePath = 'uploads/' . $newImageName;
$newImagePathRelative = 'uploads/' . $newImageName; // Path relative to public/storage/
$newImageFullPath = public_path('storage/' . $newImagePathRelative); // Full path to save
Storage::disk('public')->put($newImagePath, $decodedImage);
// Ensure the directory exists
if (!File::exists(public_path('storage/uploads'))) {
File::makeDirectory(public_path('storage/uploads'), 0755, true);
}
File::put($newImageFullPath, $decodedImage); // Save using File facade
$newImage = Image::create([
'path' => $newImagePath,
'path' => $newImagePathRelative, // Store relative path
'original_image_id' => $image->id, // Link to original image
'style_id' => $style->id, // Link to applied style
'is_temp' => true, // Mark as temporary until user keeps it
@@ -104,7 +149,7 @@ class ImageController extends Controller
'message' => 'Style change successful',
'styled_image' => [
'id' => $newImage->id,
'path' => Storage::url($newImage->path),
'path' => asset('storage/' . $newImage->path),
'is_temp' => $newImage->is_temp,
],
]);
@@ -133,44 +178,9 @@ class ImageController extends Controller
public function deleteImage(Image $image)
{
// Ensure the image is temporary or belongs to the authenticated user if not temporary
// For simplicity, we'll allow deletion of any image passed for now.
// In a real app, you'd add authorization checks here.
try {
Storage::disk('public')->delete($image->path);
$image->delete();
return response()->json(['message' => __('api.image_deleted_successfully')]);
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
public function keepImage(Request $request)
{
$request->validate([
'image_id' => 'required|exists:images,id',
]);
$image = Image::find($request->image_id);
if (!$image) {
return response()->json(['error' => __('api.image_not_found')], 404);
}
try {
$image->is_temp = false;
$image->save();
return response()->json(['message' => __('api.image_kept_successfully')]);
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
public function deleteImage(Image $image)
{
try {
Storage::disk('public')->delete($image->path);
// Delete from the public/storage directory
File::delete(public_path('storage/' . $image->path));
$image->delete();
return response()->json(['message' => __('api.image_deleted_successfully')]);
} catch (\Exception $e) {
@@ -222,4 +232,5 @@ class ImageController extends Controller
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
}

View File

@@ -10,7 +10,8 @@ class StyleController extends Controller
{
public function index()
{
$styles = Style::where('enabled', true)
$styles = Style::with(['aiModel.apiProviders'])
->where('enabled', true)
->whereHas('aiModel', function ($query) {
$query->where('enabled', true);
$query->whereHas('apiProviders', function ($query) {
@@ -19,6 +20,10 @@ class StyleController extends Controller
})
->get();
if ($styles->isEmpty()) {
return response()->json(['message' => __('api.no_styles_available')], 404);
}
return response()->json($styles);
}
}

View File

@@ -3,6 +3,7 @@
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Setting;
use Inertia\Inertia;
use Illuminate\Support\Facades\Lang;
@@ -12,9 +13,11 @@ class HomeController extends Controller
{
$locale = app()->getLocale();
$translations = Lang::get('messages', [], $locale);
$galleryHeading = Setting::where('key', 'gallery_heading')->first()->value ?? 'Style Gallery';
return Inertia::render('Home', [
'translations' => $translations,
'galleryHeading' => $galleryHeading,
]);
}
}

View File

@@ -35,6 +35,16 @@ class HandleInertiaRequests extends Middleware
'user' => $request->user(),
],
'locale' => app()->getLocale(),
'lang' => function () {
$lang = [
'filament' => trans('filament'),
'api' => trans('api'),
'settings' => trans('settings'),
'messages' => trans('messages'),
// Add other translation files as needed
];
return $lang;
},
];
}
}

View File

@@ -8,10 +8,13 @@ use Illuminate\Database\Eloquent\Concerns\HasUuids;
class Image extends Model
{
use HasFactory, HasUuids;
use HasFactory;
protected $fillable = [
'path',
'uuid',
'original_image_id',
'style_id',
'is_temp',
];
}

13
app/Models/Setting.php Normal file
View File

@@ -0,0 +1,13 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
use HasFactory;
protected $fillable = ['key', 'value'];
}

View File

@@ -18,6 +18,7 @@ use Illuminate\Session\Middleware\AuthenticateSession;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
use App\Filament\Resources\StyleResource;
use App\Filament\Resources\SettingResource\Pages\Settings;
class AdminPanelProvider extends PanelProvider
{
@@ -36,6 +37,7 @@ class AdminPanelProvider extends PanelProvider
->pages([
Pages\Dashboard::class,
\App\Filament\Pages\InstallPluginPage::class,
Settings::class,
])
->discoverWidgets(in: app_path('Filament/Widgets'), for: 'App\\Filament\\Widgets')
->widgets([