Skip to content

Commit

Permalink
fix some psalm errors
Browse files Browse the repository at this point in the history
Signed-off-by: Julien Veyssier <[email protected]>
  • Loading branch information
julien-nc committed Jan 30, 2024
1 parent e579ad5 commit f00138c
Show file tree
Hide file tree
Showing 9 changed files with 34 additions and 44 deletions.
3 changes: 2 additions & 1 deletion lib/Controller/Text2ImageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ public function getPromptHistory(): DataResponse {
#[PublicPage]
#[BruteForceProtection(action: 'imageGenId')]
public function getImage(string $imageGenId, int $fileNameId): DataDisplayResponse | DataResponse {

try {
$result = $this->text2ImageHelperService->getImage($imageGenId, $fileNameId);
} catch (Exception $e) {
Expand All @@ -91,9 +90,11 @@ public function getImage(string $imageGenId, int $fileNameId): DataDisplayRespon
return $response;
}

/*
if (isset($result['processing'])) {
return new DataResponse($result, Http::STATUS_OK);
}
*/

return new DataDisplayResponse(
$result['image'] ?? '',
Expand Down
5 changes: 0 additions & 5 deletions lib/Cron/CleanupImageGenerations.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
namespace OCA\TpAssistant\Cron;

use Exception;
use OCA\TpAssistant\Db\Text2Image\ImageGenerationMapper;
use OCA\TpAssistant\Service\Text2Image\CleanUpService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
Expand All @@ -16,7 +15,6 @@
class CleanupImageGenerations extends TimedJob {
public function __construct(
ITimeFactory $time,
private ImageGenerationMapper $imageGenerationMapper,
private LoggerInterface $logger,
private CleanUpService $cleanUpService,
) {
Expand All @@ -32,8 +30,5 @@ protected function run($argument): void {
} catch (Exception $e) {
$this->logger->debug('Cleanup job for image generations failed: ' . $e->getMessage());
}


return;
}
}
3 changes: 1 addition & 2 deletions lib/Db/TaskMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
namespace OCA\TpAssistant\Db;

use DateTime;
use Doctrine\DBAL\Exception\InvalidArgumentException;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\AppFramework\Db\QBMapper;
Expand Down Expand Up @@ -109,7 +108,7 @@ public function getTasksByOcpTaskIdAndCategory(int $ocpTaskId, int $category): a
$task = $this->update($task);
} catch (\InvalidArgumentException $e) {
// This should never happen
throw new Exception('Failed to touch timestamp of task', 0 , $e);
throw new Exception('Failed to touch timestamp of task', 0, $e);
}
}
unset($task);
Expand Down
20 changes: 10 additions & 10 deletions lib/Db/Text2Image/ImageGeneration.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@
use OCP\AppFramework\Db\Entity;

/**
* @method string getImageGenId()
* @method void setImageGenId(string $imageGenId)
* @method string getPrompt()
* @method void setPrompt(string $prompt)
* @method void setUserId(string $userId)
* @method string getUserId()
* @method void setTimestamp(int $timestamp)
* @method int getTimestamp()
* @method void setExpGenTime(int $expGenTime)
* @method int getExpGenTime()
* @method \string getImageGenId()
* @method \void setImageGenId(string $imageGenId)
* @method \string getPrompt()
* @method \void setPrompt(string $prompt)
* @method \void setUserId(string $userId)
* @method \string getUserId()
* @method \void setTimestamp(int $timestamp)
* @method \int getTimestamp()
* @method \void setExpGenTime(int $expGenTime)
* @method \int getExpGenTime()
*
*/
class ImageGeneration extends Entity implements \JsonSerializable {
Expand Down
4 changes: 1 addition & 3 deletions lib/Db/Text2Image/ImageGenerationMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ public function setNotifyReady(string $imageGenId, bool $notifyReady): int {

/**
* @param int $maxAge
* @return array ('deleted_generations' => int, 'file_names' => string[])
* @return array{deleted_generations: int, file_names: array<string>}
* @throws Exception
* @throws \RuntimeException
*/
Expand All @@ -188,11 +188,9 @@ public function cleanupImageGenerations(int $maxAge = Application::DEFAULT_MAX_I
$qb->expr()->lt('timestamp', $qb->createNamedParameter($maxTimestamp, IQueryBuilder::PARAM_INT))
);

/** @var ImageGeneration[] $generations */
$generations = $this->findEntities($qb);
$qb->resetQueryParts();

/** @var array[] $fileNames */
$fileNames = [];
$imageGenIds = [];
$generationIds = [];
Expand Down
22 changes: 14 additions & 8 deletions lib/Service/AssistantService.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\Common\Exception\NotFoundException;
use OCP\Files\File;
use OCP\Files\GenericFileException;
use OCP\Files\IRootFolder;
use OCP\Files\NotPermittedException;
Expand Down Expand Up @@ -207,7 +208,7 @@ public function runTextProcessingTask(string $type, array $inputs, string $appId
}

$assistantTask = $this->taskMapper->createTask($userId, $inputs, $task->getOutput(), time(), $task->getId(), $type, $appId, $task->getStatus(), Application::TASK_GATEGORY_TEXT_GEN, $identifier);

return $assistantTask;
}

Expand Down Expand Up @@ -242,7 +243,7 @@ public function scheduleTextProcessingTask(string $type, array $inputs, string $
}

$assistantTask = $this->taskMapper->createTask($userId, $inputs, $task->getOutput(), time(), $task->getId(), $type, $appId, $task->getStatus(), Application::TASK_GATEGORY_TEXT_GEN, $identifier);

return $assistantTask;
}

Expand Down Expand Up @@ -278,7 +279,7 @@ public function runOrScheduleTextProcessingTask(string $type, array $inputs, str
}

$assistantTask = $this->taskMapper->createTask($userId, $inputs, $task->getOutput(), time(), $task->getId(), $type, $appId, $task->getStatus(), Application::TASK_GATEGORY_TEXT_GEN, $identifier);

return $assistantTask;
}

Expand All @@ -294,7 +295,7 @@ public function parseTextFromFile(string $filePath): string {
} catch (\OC\User\NoUserException | NotPermittedException $e) {
throw new \Exception('Could not access user storage.');
}


try {
$mimeType = $userFolder->get($filePath)->getMimeType();
Expand All @@ -303,17 +304,22 @@ public function parseTextFromFile(string $filePath): string {
}

try {
$contents = $userFolder->get($filePath)->getContent();
$file = $userFolder->get($filePath);
if ($file instanceof File) {
$contents = $file->getContent();
} else {
throw new \Exception('File is not a file.');
}
} catch (NotFoundException | LockedException | GenericFileException | NotPermittedException $e) {
throw new \Exception('File not found or could not be accessed.');
}

switch ($mimeType) {
default:
case 'text/plain':
{
$text = $contents;

break;
}
case 'text/markdown':
Expand All @@ -338,7 +344,7 @@ public function parseTextFromFile(string $filePath): string {
file_put_contents($tempFilePath, $contents);

$text = $this->parseDocument($tempFilePath, $mimeType);

// Remove the hardlink to the file (delete it):
unlink($tempFilePath);

Expand Down
12 changes: 1 addition & 11 deletions lib/Service/Text2Image/CleanUpService.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,24 @@
use Exception;
use OCA\TpAssistant\AppInfo\Application;
use OCA\TpAssistant\Db\Text2Image\ImageGenerationMapper;
use OCP\Files\IAppData;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\IConfig;
use Psr\Log\LoggerInterface;
use RuntimeException;

/**
* Service to make requests to OpenAI REST API
*/
class CleanUpService {
public function __construct(
private LoggerInterface $logger,
private ImageGenerationMapper $imageGenerationMapper,
private Text2ImageHelperService $text2ImageHelperService,
private IAppData $appData,
private IConfig $config
) {

}

/**
* @param int|null $maxAge
* @return array ('deleted_files' => int, 'file_deletion_errors' => int, 'deleted_generations' => int)
* @return array{deleted_files: int, file_deletion_errors: int, deleted_generations: int}
* @throws Exception
*/
public function cleanupGenerationsAndFiles(?int $maxAge = null): array {
Expand All @@ -56,7 +50,6 @@ public function cleanupGenerationsAndFiles(?int $maxAge = null): array {
throw new Exception('Image data folder could not be accessed');
}


$deletedFiles = 0;
$deletionErrors = 0;

Expand All @@ -75,8 +68,5 @@ public function cleanupGenerationsAndFiles(?int $maxAge = null): array {
' idle generations. Failed to delete ' . $deletionErrors . ' files.');

return ['deleted_files' => $deletedFiles, 'file_deletion_errors' => $deletionErrors, 'deleted_generations' => $cleanedUp['deleted_generations']];

}


}
7 changes: 3 additions & 4 deletions lib/Service/Text2Image/Text2ImageHelperService.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ class Text2ImageHelperService {
public function __construct(
private LoggerInterface $logger,
private IManager $textToImageManager,
private ?string $userId,
private PromptMapper $promptMapper,
private ImageGenerationMapper $imageGenerationMapper,
private ImageFileNameMapper $imageFileNameMapper,
Expand All @@ -55,6 +54,7 @@ public function __construct(
private IL10N $l10n,
private AssistantService $assistantService,
private TaskMapper $taskMapper,
private ?string $userId,
) {
}

Expand Down Expand Up @@ -281,7 +281,6 @@ public function getImageDataFolder(): ISimpleFolder {
* Get image generation info.
* @param string $imageGenId
* @param bool $updateTimestamp
* @param string|null $userId
* @return array
* @throws \Exception
*/
Expand Down Expand Up @@ -356,10 +355,10 @@ public function getGenerationInfo(string $imageGenId, bool $updateTimestamp = tr
* Get image based on imageFileNameId (imageGenId is used to prevent guessing image ids)
* @param string $imageGenId
* @param int $imageFileNameId
* @return array ('image' => string, 'content-type' => string)
* @return array{image: string, 'content-type': array<string>}
* @throws BaseException
*/
public function getImage(string $imageGenId, int $imageFileNameId): ?array {
public function getImage(string $imageGenId, int $imageFileNameId): array {
try {
$generationId = $this->imageGenerationMapper->getImageGenerationOfImageGenId($imageGenId)->getId();
/** @var ImageFileName $imageFileName */
Expand Down
2 changes: 2 additions & 0 deletions psalm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,13 @@
<referencedClass name="Symfony\Component\Console\Input\InputArgument" />
<referencedClass name="Symfony\Component\Console\Input\InputInterface" />
<referencedClass name="Symfony\Component\Console\Output\OutputInterface" />
<referencedClass name="OC\User\NoUserException" />
</errorLevel>
</UndefinedClass>
<UndefinedDocblockClass>
<errorLevel type="suppress">
<referencedClass name="Doctrine\DBAL\Schema\Table" />
<referencedClass name="Doctrine\DBAL\Schema\Schema" />
</errorLevel>
</UndefinedDocblockClass>
<InvalidClass>
Expand Down

0 comments on commit f00138c

Please sign in to comment.