Skip to content

Commit e521d74

Browse files
authored
Merge pull request #16 from keiserjb/1.x-1.x
images and audio files are now managed files
2 parents bb7714b + b18d4e4 commit e521d74

File tree

2 files changed

+204
-101
lines changed

2 files changed

+204
-101
lines changed

modules/openai_dalle/openai_dalle.module

Lines changed: 109 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
* Permissions for the OpenAI DALL·E module.
66
*/
77

8+
use GuzzleHttp\Client as GuzzleClient;
9+
810
function openai_dalle_permission() {
911
return [
1012
'access openai dalle' => [
@@ -57,9 +59,16 @@ function openai_dalle_form($form, &$form_state) {
5759
$form['model'] = [
5860
'#type' => 'select',
5961
'#title' => t('Model'),
60-
'#options' => $models,
62+
'#options' => [
63+
'dall-e-2' => 'dall-e-2',
64+
'dall-e-3' => 'dall-e-3',
65+
],
6166
'#default_value' => 'dall-e-3',
62-
'#description' => t('The model to use to generate an image. See the <a href=":link">link</a> for more information.', ['@link' => 'https://platform.openai.com/docs/models/dall-e']),
67+
'#description' => t('The model to use to generate an image.'),
68+
'#ajax' => [
69+
'callback' => 'openai_dalle_model_select_callback',
70+
'wrapper' => 'size-wrapper',
71+
],
6372
];
6473

6574
$form['quality'] = [
@@ -82,13 +91,13 @@ function openai_dalle_form($form, &$form_state) {
8291
'#type' => 'select',
8392
'#title' => t('Size'),
8493
'#options' => [
85-
'256x256' => '256x256',
86-
'512x512' => '512x512',
87-
'1024x1024' => '1024x1024',
94+
'1024x1024' => '1024x1024', // Default options for 'dall-e-3'.
8895
'1792x1024' => '1792x1024',
8996
'1024x1792' => '1024x1792',
9097
],
91-
'#default_value' => '',
98+
'#default_value' => '1024x1024', // Default value.
99+
'#prefix' => '<div id="size-wrapper">',
100+
'#suffix' => '</div>',
92101
'#description' => t('The size of the generated images.'),
93102
];
94103

@@ -116,7 +125,7 @@ function openai_dalle_form($form, &$form_state) {
116125
'b64_json' => 'b64_json',
117126
],
118127
'#default_value' => 'url',
119-
'#description' => t('The image format of the result. See the <a href=":link">link</a> for more information.', ['@link' => 'https://platform.openai.com/docs/api-reference/images/create#images-create-response_format']),
128+
'#description' => t('The image format of the result. See the <a href="@link">link</a> for more information.', ['@link' => 'https://platform.openai.com/docs/api-reference/images/create#images-create-response_format']),
120129
];
121130

122131
$form['filename'] = [
@@ -160,6 +169,29 @@ function openai_dalle_form($form, &$form_state) {
160169
return $form;
161170
}
162171

172+
function openai_dalle_model_select_callback($form, &$form_state) {
173+
$selected_model = $form_state['values']['model'];
174+
175+
if ($selected_model === 'dall-e-2') {
176+
$form['size']['#options'] = [
177+
'256x256' => '256x256',
178+
'512x512' => '512x512',
179+
'1024x1024' => '1024x1024',
180+
];
181+
} elseif ($selected_model === 'dall-e-3') {
182+
$form['size']['#options'] = [
183+
'1024x1024' => '1024x1024',
184+
'1792x1024' => '1792x1024',
185+
'1024x1792' => '1024x1792',
186+
];
187+
}
188+
189+
// Ensure the default value is set to the first option in the updated list.
190+
$form['size']['#default_value'] = array_key_first($form['size']['#options']);
191+
192+
return $form['size'];
193+
}
194+
163195
/**
164196
* Form validation handler for the DALL-E form.
165197
*/
@@ -209,18 +241,11 @@ function openai_dalle_form_validate($form, &$form_state) {
209241
* The modified form element.
210242
*/
211243
function openai_dalle_get_response($form, &$form_state) {
212-
$storage = $form_state['storage'];
213-
214-
if (empty($form_state['errors']) && !empty($storage['filepath'])) {
215-
if ($storage['format'] === 'b64_json') {
216-
$file_url = file_create_url($storage['filepath']);
217-
$link = l($storage['filename'], $file_url);
218-
} else {
219-
$url = $storage['filepath'];
220-
$link = l('DALL·E result', $url);
221-
}
222-
223-
$form['file']['#markup'] = 'Download/view the image: ' . $link;
244+
if (isset($form_state['storage']) && !empty($form_state['storage']['filepath'])) {
245+
$file_url = $form_state['storage']['filepath'];
246+
$form['file']['#markup'] = '<img src="' . $file_url . '" alt="' . t('Generated image') . '">';
247+
} else {
248+
$form['file']['#markup'] = t('No image generated yet.');
224249
}
225250

226251
return $form['file'];
@@ -240,55 +265,94 @@ function openai_dalle_form_submit($form, &$form_state) {
240265

241266
$api = new OpenAIApi($apiKey);
242267

268+
// Retrieve form values.
243269
$prompt = $form_state['values']['prompt'];
244270
$model = $form_state['values']['model'];
245271
$quality = $form_state['values']['quality'];
246272
$size = $form_state['values']['size'];
247273
$style = $form_state['values']['style'];
248274
$format = $form_state['values']['response_format'];
249-
$filename = $form_state['values']['filename'];
275+
$filename_base = $form_state['values']['filename'];
276+
277+
// Determine file scheme and create a unique filename.
278+
$file_scheme = file_default_scheme();
279+
$timestamp = REQUEST_TIME;
280+
$unique_filename = $filename_base . '-' . $timestamp . '.png';
250281

251282
try {
283+
// Generate the image using the OpenAI API.
252284
$result = $api->images($model, $prompt, $size, $format, $quality, $style);
253285

254286
if ($format === 'b64_json') {
255-
$filename = $filename . '.png';
256287
$data = base64_decode($result);
257288

258-
// Save the data and create the file.
259-
$file_uri = 'public://' . $filename;
289+
if ($data === false) {
290+
form_set_error('', t('Failed to decode the Base64 image data.'));
291+
return;
292+
}
293+
294+
// Save the binary data to the file system.
295+
$file_uri = $file_scheme . '://' . $unique_filename;
260296
$file_save_result = file_unmanaged_save_data($data, $file_uri, FILE_EXISTS_REPLACE);
261297

262298
if ($file_save_result) {
263-
$file = file_save_data($data, $file_uri, FILE_EXISTS_REPLACE);
264-
if ($file) {
265-
$file->status = FILE_STATUS_PERMANENT;
266-
file_save($file);
267-
$filepath = file_create_url($file->uri);
268-
$form_state['storage'] = [
269-
'filename' => $file->filename,
270-
'filepath' => $filepath,
271-
'format' => $format,
272-
];
273-
} else {
274-
form_set_error('', t('File could not be saved.'));
275-
}
299+
// Create a managed file entity.
300+
$file = entity_create('file', [
301+
'uri' => $file_uri,
302+
'filename' => $unique_filename,
303+
'filemime' => 'image/png',
304+
'status' => 1,
305+
'uid' => $GLOBALS['user']->uid,
306+
'timestamp' => $timestamp,
307+
]);
308+
309+
file_save($file);
310+
311+
$form_state['storage'] = [
312+
'filename' => $file->filename,
313+
'filepath' => file_create_url($file->uri),
314+
'fid' => $file->fid,
315+
'format' => $format,
316+
];
276317
} else {
277-
form_set_error('', t('File could not be saved.'));
318+
form_set_error('', t('Failed to save the image to the file system.'));
278319
}
279320
} else {
280-
$form_state['storage'] = [
281-
'filename' => 'DALL-E result',
282-
'filepath' => $result,
283-
'format' => $format,
284-
];
321+
// Handle URL format response.
322+
$client = new GuzzleHttp\Client();
323+
$response = $client->get($result);
324+
325+
if ($response->getStatusCode() === 200) {
326+
$file_uri = $file_scheme . '://' . $unique_filename;
327+
file_unmanaged_save_data($response->getBody(), $file_uri, FILE_EXISTS_REPLACE);
328+
329+
$file = entity_create('file', [
330+
'uri' => $file_uri,
331+
'filename' => $unique_filename,
332+
'filemime' => 'image/png',
333+
'status' => 1,
334+
'uid' => $GLOBALS['user']->uid,
335+
'timestamp' => $timestamp,
336+
]);
337+
338+
file_save($file);
339+
340+
$form_state['storage'] = [
341+
'filename' => $file->filename,
342+
'filepath' => file_create_url($file->uri),
343+
'fid' => $file->fid,
344+
'format' => $format,
345+
];
346+
} else {
347+
form_set_error('', t('Failed to download the image from the URL.'));
348+
}
285349
}
286350
} catch (Exception $e) {
287351
form_set_error('', t('Error generating image: @message', ['@message' => $e->getMessage()]));
288352
}
289353

290354
$form_state['rebuild'] = TRUE;
291-
}
292-
293-
294355

356+
// Ensure storage is set to avoid warnings.
357+
$form_state['storage'] = $form_state['storage'] ?? [];
358+
}

0 commit comments

Comments
 (0)