Skip to content

Commit

Permalink
[TASK] Latest update for v12
Browse files Browse the repository at this point in the history
  • Loading branch information
ayacoo committed Apr 14, 2023
1 parent be2d446 commit f698fa8
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 37 deletions.
38 changes: 29 additions & 9 deletions Classes/Controller/SummarizeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,40 @@
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
use TYPO3\CMS\Core\Http\JsonResponse;
use TYPO3\CMS\Core\Http\RequestFactory;
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;

class SummarizeController
{
private const EXTENSION_KEY = 'news_tldr';

public function __construct(
private readonly RequestFactory $requestFactory,
private readonly ExtensionConfiguration $extensionConfiguration,
private readonly RequestFactory $requestFactory,
private readonly ExtensionConfiguration $extensionConfiguration,
private readonly EventDispatcherInterface $eventDispatcher
)
{
}

public function updateTeaserAction(): JsonResponse
{
$extConf = $this->extensionConfiguration->get('news_tldr');
$extConf = $this->extensionConfiguration->get(self::EXTENSION_KEY);
$token = trim($extConf['token'] ?? '');
$summaryLength = (int)($extConf['length'] ?? 200);

if (empty($token)) {
return new JsonResponse([
'text' => LocalizationUtility::translate('no_valid_token', self::EXTENSION_KEY),
'success' => false
]);
}

$request = $GLOBALS['TYPO3_REQUEST'];
$postParams = $request->getParsedBody();

$row = BackendUtility::getRecord('tx_news_domain_model_news', (int)$postParams['uid']);
$content = 'Fasse mir diesen Text in 200 Zeichen zusammen: ' . strip_tags(trim($row['bodytext'] ?? ''));

$content = 'Fasse mir diesen Text in ' . $summaryLength . ' Zeichen zusammen: ';
$content .= strip_tags(trim($row['bodytext'] ?? ''));
$modifyChatGptContentEvent = $this->eventDispatcher->dispatch(
new ModifyChatGptContentEvent($row, $content)
);
Expand All @@ -42,7 +56,7 @@ public function updateTeaserAction(): JsonResponse
$additionalOptions = [
'body' => json_encode($payload),
'headers' => [
'Authorization' => 'Bearer ' . ($extConf['token'] ?? ''),
'Authorization' => 'Bearer ' . $token,
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/json'
],
Expand All @@ -55,20 +69,26 @@ public function updateTeaserAction(): JsonResponse

if ($response->getStatusCode() !== 200) {
throw new \RuntimeException(
'Returned status code is ' . $response->getStatusCode()
LocalizationUtility::translate('status_code_is', self::EXTENSION_KEY) . $response->getStatusCode()
);
}
if ($response->getHeaderLine('Content-Type') !== 'application/json') {
throw new \RuntimeException(
'The request did not return JSON data'
LocalizationUtility::translate('no_valid_json', self::EXTENSION_KEY)
);
}
$content = $response->getBody()->getContents();
try {
$result = json_decode($content, true, flags: JSON_THROW_ON_ERROR);
return new JsonResponse(['text' => $result['choices'][0]['message']['content'] ?? '']);
return new JsonResponse([
'text' => (string)$result['choices'][0]['message']['content'] ?? '',
'success' => true
]);
} catch (\JsonException) {
return new JsonResponse(['text' => '']);
return new JsonResponse([
'text' => LocalizationUtility::translate('no_valid_token', self::EXTENSION_KEY),
'success' => false
]);
}
}
}
8 changes: 7 additions & 1 deletion Classes/Form/Element/SummarizeFieldElement.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
namespace Ayacoo\NewsTldr\Form\Element;

use TYPO3\CMS\Backend\Form\Element\AbstractFormElement;
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Utility\GeneralUtility;

Expand All @@ -30,11 +31,16 @@ public function render(): array
$html[] = '<div class="form-wizards-element">';
$html[] = '<div class="form-control-wrap">';

$icon = $this->iconFactory->getIcon(
'actions-dice',
Icon::SIZE_SMALL,
'overlay-identifier'
);

$html[] = '<button class="btn btn-default t3js-ayacoo-tldr" data-newsid="' . $row['uid'] . '">
<span class="t3js-icon icon icon-size-small icon-state-default icon-apps-pagetree-page-default" data-identifier="apps-pagetree-page-default">
<span class="icon-markup">
<svg class="icon-color"><use xlink:href="/typo3/sysext/core/Resources/Public/Icons/T3Icons/sprites/apps.svg#apps-pagetree-page-default"></use></svg>
' . $icon->getMarkup() . '
</span>
</span>
Start!
Expand Down
7 changes: 2 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@ The extension makes it possible to create short news summaries using ChatGPT.

## 2 Hints

- The extension is only a proof of concept and was tested in the environment of
TYPO3 version 12 and PHP 8.1.
- This code is experimental
- The code can be used and further developed as desired, e.g. for a backport to
version 11
- Only the field bodytext is read. Other linked content elements must be read and
Expand All @@ -23,7 +20,7 @@ To use this extension, you need the following requirements:
- PHP version 8.1 or higher
- TYPO3 version 12
- [News][3] Extension 11 or higher
- [ChatGPT API Token][2]
- [ChatGPT API Token][2] (Please note the number of tokens and costs)

### 3.2 Installation

Expand All @@ -39,7 +36,7 @@ composer require ayacoo/news-tldr

### 3.3 Event / EventListener

To modify the ChatGPT request, e.g. to change the number of characters, there is
To modify the ChatGPT request, e.g. to change the payload, there is
an event: `ModifyChatGptContentEvent`.

### EventListener registration
Expand Down
12 changes: 12 additions & 0 deletions Resources/Private/Language/locallang.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,18 @@
<trans-unit id="tldr.alert.error" resname="tldr.alert.error">
<source>Failed to update news summary</source>
</trans-unit>
<trans-unit id="no_valid_token" resname="no_valid_token">
<source>Please set a token in the extension settings</source>
</trans-unit>
<trans-unit id="no_suitable_feedback" resname="no_suitable_feedback">
<source>No suitable feedback from ChatGPT</source>
</trans-unit>
<trans-unit id="no_valid_json" resname="no_valid_json">
<source>The request did not return JSON data</source>
</trans-unit>
<trans-unit id="status_code_is" resname="status_code_is">
<source>Returned status code is </source>
</trans-unit>
</body>
</file>
</xliff>
42 changes: 23 additions & 19 deletions Resources/Public/JavaScript/summarize.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,29 @@ class Summarize {
new AjaxRequest(url)
.post(payload).then(async function (response) {
const data = await response.resolve();
Notification.success(
TYPO3.lang['tldr.alert.success'],
TYPO3.lang['tldr.alert.success.text']
);

var inputBox = document.querySelector('[data-formengine-input-name="data[tx_news_domain_model_news][' + newsId + '][teaser]"]');
var speed = 50;

inputBox.value = '';

var i = 0;
var timer = setInterval(function () {
if (i < data.text.length) {
inputBox.value += data.text.charAt(i);
i++;
} else {
clearInterval(timer);
}
}, speed);
if (data.success === true) {
Notification.success(
TYPO3.lang['tldr.alert.success'],
TYPO3.lang['tldr.alert.success.text']
);

var inputBox = document.querySelector('[data-formengine-input-name="data[tx_news_domain_model_news][' + newsId + '][teaser]"]');
var speed = 50;

inputBox.value = '';

var i = 0;
var timer = setInterval(function () {
if (i < data.text.length) {
inputBox.value += data.text.charAt(i);
i++;
} else {
clearInterval(timer);
}
}, speed);
} else {
Notification.error(TYPO3.lang['tldr.alert.error'], data.text);
}

}, function (error) {
Notification.error(TYPO3.lang['tldr.alert.error'], error.response.status + ' ' + error.response.statusText);
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
],
"require": {
"php": ">=8.1",
"typo3/cms-core": "^12.0",
"typo3/cms-core": "^12.3",
"georgringer/news": "^11.0"
},
"autoload": {
Expand Down
2 changes: 2 additions & 0 deletions ext_conf_template.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
token =
# cat=Settings/O; type=string; label= ChatGPT Model
model = gpt-3.5-turbo
# cat=Settings/O; type=string; label= Length of summary
length = 200
4 changes: 2 additions & 2 deletions ext_emconf.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
'category' => 'plugin',
'constraints' => [
'depends' => [
'typo3' => '12.0.0-12.9.99',
'typo3' => '12.3.0-12.9.99',
'news' => '11.0.0-11.9.99',
],
'conflicts' => [],
'suggests' => [],
],
'state' => 'beta',
'state' => 'stable',
'clearCacheOnLoad' => true,
'author' => 'Guido Schmechel',
'author_email' => 'info@ayacoo.de',
Expand Down

0 comments on commit f698fa8

Please sign in to comment.