Code viewer for World: AIRecipe
// talk to OpenAI GPT model (ChatGPT)
// adapted from:
//  https://platform.openai.com/docs/api-reference/making-requests
  
const themodel = "gpt-3.5-turbo";       // the OpenAI model we are going to talk to 

// default API key and prompt:
var apikey = "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";

// default body is margin 0 and padding 0 
// give it more whitespace:

$('body').css( "margin", "20px" );
$('body').css( "padding", "20px" );
 
document.write ( `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 20px;
        }

        h1, h2, p {
            margin-bottom: 10px;
        }

        .recipe-container {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        h2 {
            color: #009688;
        }
        
        ul, ol {
            margin-bottom: 20px;
        }

        li {
            margin-bottom: 5px;
        }

        form {
            max-width: 400px;
            margin: 0 auto;
        }

        label {
            display: block;
            margin-bottom: 8px;
        }

        input[type="text"] {
            width: 100%;
            padding: 8px;
            margin-bottom: 16px;
        }

        input[type="submit"] {
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        input[type="submit"]:hover {
            background-color: #45a049;
        }

        #result {
            margin-top: 20px;
            flex: 1;
            padding: 20px;
        }
        
        .container {
          display: flex;
          align-items: center;
          justify-content: center
        }
        
        img {
          max-width: 100%;
          max-height:100%;
        }
        
    </style>
</head>
    <body>
        <h1>AI Recipe Finder</h1>
        <form id="recipeForm">
            <label for="dishQuery">Enter Dish Name:</label>
            <input type="text" id="dishQuery" name="dishQuery" required>
            <input type="submit" value="Get Recipe">
        </form>
        <div class="container">
            <div id="result"></div>
            <div id="image"></div>
        </div>
    </body>
</html>`);


function parseResult(data, rc) {
    let answer = data["choices"][0].message.content;
    console.log(answer)
    const sections = answer.split(/\n\n/);

    const dishMatch = sections[0].match(/Dish:\s*(.+)/);
    const dish = dishMatch ? dishMatch[1] : '';

    const ingredientsMatch = sections.find(section => section.includes('Ingredients:'));
    const ingredients = ingredientsMatch ? ingredientsMatch.split('\n').slice(1) : [];

    const instructionsMatch = sections.find(section => section.includes('Instructions:'));
    let instructions = instructionsMatch ? instructionsMatch.split('\n').slice(1) : [];
    const instructions2 = instructionsMatch ? instructionsMatch.split(/\n\n/).slice(1) : [];
    if (instructions2.length > instructions.length) {
        instructions = instructions2;
    }
    displayResult({dish, ingredients, instructions});
}

function displayResult(parsedResults) {
    const resultDiv = document.getElementById('result');
    if (parsedResults.dish === '') {
        resultDiv.innerHTML = '<font color=red><h1>Sorry, I could not come up with a Dish</h1></font>';
        return
    }
    const imageDiv = document.getElementById('image');
    imageDiv.innerHTML = `<h2>Loading Image of Dish</h2>`
    var theData2 = {
        "model": "dall-e-2",
        "prompt": `The food dish "${parsedResults.dish}"`,
        "n": 1,
        "size": "512x512"
    }
    var thedatastring2 = JSON.stringify (theData2 );
 
 
// MH edit
console.log ( "MH get image for: " + `The food dish "${parsedResults.dish}"` );


    $.ajax({
        type: "POST",
        url: "https://api.openai.com/v1/images/generations",
        data: thedatastring2,
        dataType: "json",
        success: function ( d, rc ) { displayResult2 ( d, rc ); },
          error: function()         { errorfn (); }
    });
    resultDiv.innerHTML = '';
    resultDiv.innerHTML += `<h2>Dish: ${parsedResults.dish}</h2>`;

    resultDiv.innerHTML += '<h2>Ingredients:</h2><ul>';
    parsedResults.ingredients.forEach(ingredient => {
        resultDiv.innerHTML += `<li>${ingredient}</li>`;
    });
    resultDiv.innerHTML += '</ul>';

    resultDiv.innerHTML += '<h2>Instructions:</h2><ol>';
    parsedResults.instructions.forEach(instruction => {
        resultDiv.innerHTML += `<li>${instruction}</li>`;
    });
    resultDiv.innerHTML += '</ol>';
}

function displayResult2(data, rc)   {
    const imageDiv = document.getElementById('image');
    imageDiv.innerHTML = `<h2>Image of Dish</h2>
            <img src="${data.data[0].url}">`
}

document.getElementById('dishQuery').onkeydown = function(event) { 
    if (event.keyCode == 13) {
        event.preventDefault();
        sendchat();
    }};

document.getElementById('recipeForm').addEventListener('submit', function (event) {
    event.preventDefault();
    sendchat();
});

function sendchat() {
    const resultDiv = document.getElementById('result')
    const imageDiv = document.getElementById('image');
    const dishQuery = $("#dishQuery").val()
    if (dishQuery.length > 100 || dishQuery.length < 1) {
        $("#result").html ( "<font color=red><h1> Not a food </h1></font>");
        return
    }
    resultDiv.innerHTML = '<font color=blue><h1>Loading...</h1></font>';
    imageDiv.innerHTML = '';
    theprompt = `Give me a recipe and the ingredient list for the dish "${dishQuery}.
                Give it this to me in the format 
                Dish:
                Ingredients:
                Instructions:"`
  
  
// MH edit
console.log ( "MH get recipe for: " + theprompt );

    var thedata = {
        "model": themodel,
        "messages": [{
        "role": "user", 
        "content": theprompt
        }] 
    };
    
    // then as string representing that JSON:
    var thedatastring = JSON.stringify ( thedata );
    // HTTP headers must be set up with API key: 
    $.ajaxSetup({
        headers:
        {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + apikey  
        }
    });

    $.ajax({
        type: "POST",
        url: "https://api.openai.com/v1/chat/completions",
        data: thedatastring,
        dataType: "json",
        success: function ( d, rc ) { parseResult ( d, rc ); },
          error: function()         { errorfn (); }
    });
}

function errorfn()  {
    if ( apikey === "" )    $("#result").html ( "<font color=red><b> Enter API key to be able to chat. </b></font>" );
    else                   $("#result").html ( "<font color=red><h1> Unkown error. </h1></font>" ); 
}