Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

Can you write me a simple web app (i.e. HTML, basic JS, fastapi) that: 1. shows the…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with gpt-4.1-2025-04-14’s answer.
  1. User

    Can you write me a simple web app (i.e. HTML, basic JS, fastapi) that:

    1. shows the document image on the left (for POC purposes this can just a local file reference)
    2. shows a textbox on the right that allows the user to type into
    3. predictive text from a list of given words - NOT in a separate box. But rather gmail style, showing inline in gray as the user is typing with the prediction, allowing the user to press TAB to accept that suggestion, moving the cursor to the end of the prediction.

    If it clarifies requirements, my intention is to use an OCR output from the given image as predictive text for what the user starts writing.

  2. Gemini Assistant

    Okay, this is a fun challenge, especially getting that "Gmail-style" inline predictive text right with textarea. It requires a clever trick with positioning and z-index.

    Here's how we'll build it:

    1. FastAPI Backend: To serve the HTML, CSS, JS, and the document image.
    2. HTML Structure: Two main panels (image and text), with a special wrapper for the text input to enable the inline prediction.
    3. CSS Styling: For layout, and crucial positioning/styling for the inline prediction.
    4. JavaScript Logic:
      • Listen for user input (input event).
      • Determine the current word being typed.
      • Find a matching prediction from a predefined list.
      • Update a hidden "display proxy" div with the text, inserting the gray prediction.
      • Handle Tab key press to accept the prediction.

    Project Structure

    .
    ├── main.py
    ├── index.html
    └── static/
        ├── style.css
        ├── script.js
        └── document_image.jpg  (a placeholder image)
    

    1. Backend (main.py)

    This FastAPI app will serve your static files and the main HTML page.

    # main.py
    from fastapi import FastAPI, Request
    from fastapi.responses import HTMLResponse
    from fastapi.staticfiles import StaticFiles
    from fastapi.templating import Jinja2Templates
    
    app = FastAPI()
    
    # Mount the static directory to serve CSS, JS, and images
    app.mount("/static", StaticFiles(directory="static"), name="static")
    
    # Configure Jinja2Templates to serve HTML files
    # Assuming index.html is in the same directory as main.py
    templates = Jinja2Templates(directory=".")
    
    @app.get("/", response_class=HTMLResponse)
    async def read_root(request: Request):
        """
        Serves the main HTML page for the web application.
        """
        return templates.TemplateResponse("index.html", {"request": request})
    
    # To run this:
    # 1. pip install fastapi uvicorn python-multipart jinja2
    # 2. uvicorn main:app --reload
    

    2. Frontend (index.html)

    This is the main structure of your web page.

    <!-- index.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document Text Predictor</title>
        <link rel="stylesheet" href="/static/style.css">
    </head>
    <body>
        <div class="container">
            <div class="image-panel">
                <h2>Document Image</h2>
                <!-- For POC, this is a local reference served by FastAPI -->
                <img id="document-image" src="/static/document_image.jpg" alt="Document Image">
            </div>
            <div class="text-panel">
                <h2>Transcribe Document</h2>
                <div class="input-wrapper">
                    <!--
                        The `display-proxy` will show the text content including the gray prediction.
                        The `textarea` will sit directly on top, transparent, to receive user input.
                    -->
                    <div id="display-proxy" class="text-display"></div>
                    <textarea id="main-input" placeholder="Start typing here..."></textarea>
                </div>
            </div>
        </div>
    
        <script src="/static/script.js"></script>
    </body>
    </html>
    

    3. Styling (static/style.css)

    This is where the magic happens for the inline prediction. We overlay a transparent textarea on a div that renders the text and the gray prediction.

    /* static/style.css */
    body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 100vh;
        background-color: #f0f0f0;
        overflow: hidden; /* Prevent body scroll if content overflows viewport */
    }
    
    .container {
        display: flex;
        width: 90%;
        max-width: 1200px;
        height: 80vh; /* Adjust height as needed */
        background-color: #fff;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        border-radius: 8px;
        overflow: hidden; /* Contains child panels */
    }
    
    .image-panel, .text-panel {
        flex: 1;
        padding: 20px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
    }
    
    .image-panel {
        border-right: 1px solid #eee;
        background-color: #fdfdfd;
    }
    
    .image-panel img {
        max-width: 100%;
        height: auto;
        display: block;
        margin-top: 15px;
        border: 1px solid #ddd;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }
    
    .text-panel {
        background-color: #fff;
    }
    
    h2 {
        color: #333;
        margin-top: 0;
        margin-bottom: 20px;
        text-align: center;
    }
    
    .input-wrapper {
        position: relative; /* Essential for positioning children absolutely */
        flex-grow: 1; /* Makes it fill available space in text-panel */
        min-height: 150px; /* Ensure some default height */
        border: 1px solid #ccc;
        border-radius: 4px;
        overflow: hidden; /* Ensures text doesn't flow out if proxy/textarea overflows */
    }
    
    /* Base styles for both proxy and textarea */
    .text-display, #main-input {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        padding: 10px;
        box-sizing: border-box;
        font-size: 16px;
        line-height: 1.5; /* Crucial: Match line height for perfect overlay */
        white-space: pre-wrap; /* Preserves whitespace and wraps lines like textarea */
        word-wrap: break-word; /* Allows long words to break */
    }
    
    /* Styling for the display proxy */
    .text-display {
        color: #333; /* Default text color (user's typed text) */
        pointer-events: none; /* Allows mouse events to pass through to the textarea below */
        z-index: 1; /* Below the textarea */
        background-color: #fff; /* Ensure it's opaque */
    }
    
    /* Styling for the actual textarea */
    #main-input {
        color: transparent; /* Makes user's typed text invisible in textarea itself */
        caret-color: #333; /* But keeps the cursor visible */
        background: transparent; /* Makes the textarea transparent */
        resize: none; /* Disable manual resizing */
        border: none; /* Remove default border */
        outline: none; /* Remove outline on focus */
        z-index: 2; /* On top to receive user input */
    }
    
    /* Styling for the predicted text within the display proxy */
    .suggestion {
        color: #aaa; /* Gray color for the predictive text */
    }
    
    /* Responsive adjustments */
    @media (max-width: 768px) {
        .container {
            flex-direction: column;
            height: auto;
            width: 95%;
            margin: 20px 0;
        }
        .image-panel {
            border-right: none;
            border-bottom: 1px solid #eee;
        }
    }
    

    4. JavaScript Logic (static/script.js)

    This script contains the core logic for predictive text.

    // static/script.js
    document.addEventListener('DOMContentLoaded', () => {
        const mainInput = document.getElementById('main-input');
        const displayProxy = document.getElementById('display-proxy');
    
        // Your list of words for prediction (OCR output would go here)
        const predictionWords = [
            "document", "image", "contract", "invoice", "receipt", "signature",
            "address", "date", "total", "amount", "customer", "vendor",
            "product", "description", "quantity", "price", "subtotal", "tax",
            "shipping", "confidential", "agreement", "authorization", "statement"
        ];
    
        /**
         * Escapes HTML characters to prevent XSS and ensure safe rendering.
         * @param {string} text The text to escape.
         * @returns {string} The escaped HTML string.
         */
        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, function(m) { return map[m]; });
        }
    
        /**
         * Updates the display proxy with the current input value and the predictive text.
         */
        function updatePrediction() {
            const inputValue = mainInput.value;
            const cursorPos = mainInput.selectionStart;
    
            // 1. Get the part of the text before the cursor
            const textUpToCursor = inputValue.substring(0, cursorPos);
    
            // 2. Find the current word being typed (or word at cursor)
            // This handles spaces, newlines, and tabs as word separators
            const lastWordBoundaryIndex = Math.max(
                textUpToCursor.lastIndexOf(' '),
                textUpToCursor.lastIndexOf('\n'),
                textUpToCursor.lastIndexOf('\t')
            );
            const currentWordStart = lastWordBoundaryIndex === -1 ? 0 : lastWordBoundaryIndex + 1;
            const currentWordTyped = textUpToCursor.substring(currentWordStart);
    
            let predictedSuffix = ''; // The gray part of the prediction
    
            // 3. Find a prediction
            if (currentWordTyped.length > 0) {
                const foundWord = predictionWords.find(word =>
                    word.toLowerCase().startsWith(currentWordTyped.toLowerCase()) && word.length > currentWordTyped.length
                );
                if (foundWord) {
                    predictedSuffix = foundWord.substring(currentWordTyped.length);
                }
            }
    
            // 4. Construct the HTML for the display proxy
            // It shows the entire input value, with the predicted suffix inserted
            const textBeforeWord = escapeHtml(inputValue.substring(0, currentWordStart));
            const currentWordTypedEscaped = escapeHtml(currentWordTyped);
            const predictedSuffixEscaped = escapeHtml(predictedSuffix);
            const textAfterCursor = escapeHtml(inputValue.substring(cursorPos));
    
            displayProxy.innerHTML =
                textBeforeWord +
                currentWordTypedEscaped + // User's typed part, shown in black (from .text-display color)
                `<span class="suggestion">${predictedSuffixEscaped}</span>` + // Predicted part, shown in gray
                textAfterCursor;
        }
    
        /**
         * Handles the Tab key press to accept the current prediction.
         * @param {KeyboardEvent} event The keyboard event.
         */
        function handleTabKey(event) {
            const inputValue = mainInput.value;
            const cursorPos = mainInput.selectionStart;
    
            const textUpToCursor = inputValue.substring(0, cursorPos);
            const lastWordBoundaryIndex = Math.max(
                textUpToCursor.lastIndexOf(' '),
                textUpToCursor.lastIndexOf('\n'),
                textUpToCursor.lastIndexOf('\t')
            );
            const currentWordStart = lastWordBoundaryIndex === -1 ? 0 : lastWordBoundaryIndex + 1;
            const currentWordTyped = textUpToCursor.substring(currentWordStart);
    
            let prediction = '';
            if (currentWordTyped.length > 0) {
                const foundWord = predictionWords.find(word =>
                    word.toLowerCase().startsWith(currentWordTyped.toLowerCase()) && word.length > currentWordTyped.length
                );
                if (foundWord) {
                    prediction = foundWord;
                }
            }
    
            if (prediction) {
                event.preventDefault(); // Prevent default Tab behavior (e.g., focus change)
    
                // Replace the typed word with the full prediction
                const newValue = inputValue.substring(0, currentWordStart) + prediction + inputValue.substring(cursorPos);
                mainInput.value = newValue;
    
                // Move the cursor to the end of the accepted prediction
                mainInput.selectionStart = mainInput.selectionEnd = currentWordStart + prediction.length;
    
                // Immediately update the prediction display
                updatePrediction();
            }
        }
    
        // Event Listeners
        mainInput.addEventListener('input', updatePrediction); // For general typing
        mainInput.addEventListener('keydown', (event) => {
            if (event.key === 'Tab') {
                handleTabKey(event);
            }
        });
    
        // Initial call to set up the display proxy when the page loads
        updatePrediction();
    });
    

    5. Placeholder Image

    Create a simple document_image.jpg inside the static folder. You can use any image you like, or a blank one for testing.


    How to Run

    1. Save the files:

      • main.py in the root directory.
      • index.html in the root directory.
      • Create a folder named static in the root.
      • Save style.css inside the static folder.
      • Save script.js inside the static folder.
      • Put a document_image.jpg (any image) inside the static folder.
    2. Install dependencies:

      pip install fastapi uvicorn python-multipart jinja2
      
    3. Run the FastAPI server: Open your terminal in the root directory of your project and run:

      uvicorn main:app --reload
      
    4. Open in browser: Go to http://127.0.0.1:8000/ in your web browser.


    Explanation of the Inline Prediction Trick

    The "Gmail-style" inline prediction is achieved using two overlapping elements:

    1. #main-input (the textarea):

      • color: transparent;: Makes the actual text typed by the user invisible.
      • caret-color: black;: Keeps the cursor visible and black.
      • background: transparent;: Allows the div below to show through.
      • z-index: 2;: Positions it on top, so it receives all keyboard input.
    2. #display-proxy (a div with class text-display):

      • color: #333;: This is the default color for all text in this div, effectively making the user's typed text visible in black.
      • <span class="suggestion">: Any text wrapped in this span inside the display-proxy will be color: #aaa; (gray), creating the predictive text effect.
      • pointer-events: none;: This is crucial! It makes the div ignore all mouse events (clicks, hovers), allowing them to "fall through" to the textarea underneath. This ensures you can click and set the cursor normally within the visible text.
      • z-index: 1;: Positions it just below the textarea.

    The JavaScript then carefully constructs the HTML for display-proxy.innerHTML by taking the user's input, identifying the current word, finding a prediction, and then inserting the gray predicted suffix inline with the rest of the text. When Tab is pressed, the textarea's actual value is updated, and the display-proxy is refreshed to reflect the new, complete word.

    This setup provides a very close approximation of the Gmail-style inline prediction experience using standard web technologies.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.