skip to Main Content

I am trying to make a loading wheel that displays while a background process is running and hides itself on completion of that background process. The background process is the ingestion process, which runs a web scraper across a Wikipedia page and converts it to a text file, and then ingests it into an LLM model. I want the loading gif to appear the whole time ingestion is running, and then disappear upon completion. I am using Flask to communicate between my front end and back end.

I have tried ajaxComplete on the POST request which only displays the wheel for a millisecond, and the current method which is posted in my code below.

html:

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style> #loading { display: none; } </style>
<div class="card-footer">
            <form id="ingestArea" class="input-group">
                <input type="text" id="html" name="url" placeholder="Type your message..." autocomplete="off" class="form-control type_msg" required/>
                <div class="input-group-append">
                    <button type="submit" id="feed" class="input-group-text send_btn"><i class="fas fa-location-arrow"></i></button>
                </div>
                <div id="loading"><img src="https://i.pinimg.com/originals/36/3c/2e/363c2ec45f7668e82807a0c053d1e1d0.gif"></div>
            </form>
        </div>
<script>
            $(document).ready(function() {
                var interval;
                $("#messageArea").on("submit", function(event) {
                    const date = new Date();
                    const hour = date.getHours();
                    const minute = date.getMinutes();
                    const str_time = hour+":"+minute;
                    var rawText = $("#text").val();

                    var userHtml = '<div class="d-flex justify-content-end mb-4"><div class="msg_cotainer_send">' + rawText + '<span class="msg_time_send">'+ str_time + '</span></div><div class="img_cont_msg"><img src="https://i.ibb.co/d5b84Xw/Untitled-design.png" class="rounded-circle user_img_msg"></div></div>';
                    
                    $("#text").val("");
                    $("#messageFormeight").append(userHtml);

                    $.ajax({
                        data: {
                            msg: rawText,   
                        },
                        type: "POST",
                        url: "/get",
                    }).done(function(data) {
                        var botHtml = '<div class="d-flex justify-content-start mb-4"><div class="img_cont_msg"><img src="https://i.ibb.co/fSNP7Rz/icons8-chatgpt-512.png" class="rounded-circle user_img_msg"></div><div class="msg_cotainer">' + data + '<span class="msg_time">' + str_time + '</span></div></div>';
                        $("#messageFormeight").append($.parseHTML(botHtml));
                    });
                    event.preventDefault();
                });
                $("#ingestArea").on("submit",function(event) {
                    var rawText = $("#html").val();
                    $('#loading').show();
                    interval = setInterval(checkStatus, 1000);
                    $("#html").val("");
                    $.ajax({
                        data:{
                            url: rawText,
                        },
                        type: "POST",
                        url: "/ingest",
                    });
                });
            });
            function checkStatus() {
                $.ajax({
                    url: '/check_status',
                    type: 'GET',
                    success: function(response) {
                        if (response.status === "in_progress") {
                            $('#loading').show();
                        } else{
                            clearInterval(interval);
                            $('#loading').hide();
                        }
                    },
                    error: function(xhr) {
                        clearInterval(interval);
                        $('#loading').hide();
                    }
                });
        </script>

python (using Flask):

is_ingesting = False

@app.route('/check_status', methods=['GET'])
def check_status():
    global is_ingesting
    if is_ingesting:
        return jsonify(status="in_progress")
    else:
        return jsonify(status="completed")


def ingest():
    global is_ingesting
    is_ingesting = True
    start_url = request.form["url"]
    scrape_web(start_url, 0)
    if does_vectorstore_exist(persist_directory):
        # Update and store locally vectorstore
        print(f"Appending to existing vectorstore at {persist_directory}")
        db = Chroma(persist_directory=persist_directory, embedding_function=embeddings, client_settings=CHROMA_SETTINGS)
        collection = db.get()
        texts = process_documents([metadata['source'] for metadata in collection['metadatas']])
        print(f"Creating embeddings. May take some minutes...")
        db.add_documents(texts)
    else:
        # Create and store locally vectorstore
        print("Creating new vectorstore")
        texts = process_documents()
        print(f"Creating embeddings. May take some minutes...")
        db = Chroma.from_documents(texts, embeddings, persist_directory=persist_directory,
                                   client_settings=CHROMA_SETTINGS)
    db.persist()
    db = None
    is_ingesting = False
    print(f"Ingestion complete! You can now run privateGPT.py to query your documents")
    return jsonify("All done!")

2

Answers


  1. Chosen as BEST ANSWER

    The above comment is correct! It was a refresh issue. I learned about the preventDefault() method as well! It seems to be an equally correct solution. Here is the following edited code for comparison to my previous code!

    $("#ingestArea").on("submit",function(event) {
                        event.preventDefault();
                        var rawText = $("#html").val();
                        $("#html").val("");
                        $.ajax({
                            data:{
                                url: rawText,
                            },
                            type: "POST",
                            url: "/ingest",
                            beforeSend: function() {
                                $('#loading').show();
                            },
                            complete: function(data) {
                                $('#loading').hide();
                            },
                        }); 
    

    Here's the edited jQuery. I left the style as hidden at the top. This seems to work just great! I deleted the unnecessary python code for the function that tracked progress.


  2. The problem seems to be the reload on the click of the submit button which is in a form so the element gets shown and instant hidden by css on the reload.

    Maybe use the jquery click event to don’t get your page reloaded on the click.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search