ACF Library

AIfetchImages

Back to List

Description: Ask DALL•E•3 API to get an image based on descriptiom, update image tag in document.

FileMaker Prototype:

Set Variable [$res; ACF_Run("AIfetchImages"; string_imageDescription;  string_emailContent;  string_tag)]

Category: OPENAI

NOTE: This function serves as a reference template. To use it effectively, you may need to adjust certain parts of the code, such as field names, database structures, and specific data lists to fit the requirements of your system. This customization allows the function to work seamlessly within your environment.

Function source:

/*

   Fetch implied images
   
*/
function AIfetchImages ( string imageDescription, string emailContent, string tag )
   $$ImgURL = ""; 
   string imgurl, err, imgcontent, filename, filetype, basepath, path,res; 
   // Check if we need to update the image
   if ( Email_Messages::ImageDescription == imageDescription ) then
      // reuse the old image
      path = Email_Messages::ImagePath;
      emailContent = substitute ( emailContent, tag, "file://"+path); 
      $$ImgURL = path; 
      return emailContent; 
   end if
   string url = "https://api.openai.com/v1/images/generations";
   JSON quest;
   quest = JSON ("model", "dall-e-3", "prompt", imageDescription, "n", 1, "size", "1024x1024"); 
   string APIkey = ExecuteSQL ("SELECT AI_APIKey FROM Preferences"); 
   string hdr = "Content-Type: application/json\nAuthorization: Bearer "+APIkey;
   string respons = HTTP_POST ( url, string (quest), hdr);
   print respons; 
   
   int x; 
   basepath = Email_Accounts::HTML_Folder ;
   if ( basepath == "") then
      alert ("HTML folder is not configured!"); 
      return emailContent;
   end if
   basepath += "/images/";
   res = create_directory(basepath); 
   JSON resp; 
   resp = respons; 
   if ( list_keys (resp) == "error") then
      err = resp["error.message"];
      alert (err);
      return emailContent; 
   else
      imgurl = resp["data[1].url"];
   end if
   if (imgurl != "" ) then
      imgcontent = HTTP_GET ( imgurl ); 
      filename = regex_replace("^(.+)\/(.+\..+)\?.*$", imgurl, "\2");
      print basepath + "\n";
      path = basepath  + filename; 
      print path + "\n";
       x = open (path, "w"); 
       write (x, imgcontent); 
       close ( x ); 
      emailContent = substitute ( emailContent, tag, "file://"+path); 
      $$ImgURL = path; 
      $$ImageName = regex_replace("^(.+)/(.+\..+)$", path, "\2");
   end if
   return emailContent; 
end 

Back to List