from fastapi import FastAPI, HTTPException, UploadFile, File, Request, Response
from fastapi.responses import HTMLResponse, FileResponse, RedirectResponse
# from hairstyle_transfer_tool import Tool
import os
import uvicorn

app = FastAPI()
IMAGE_DIR='data\\uploaded_images'
# @app.get("/")
# async def hello():
#     return "Hello, have your virtual haircut with StyleDreamer!"

@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
    files = os.listdir(IMAGE_DIR)
    files_list_html = "".join(
        [
            f"""
            <li>
                {image}
                <a href="/download/{image}">Download</a>
                <form style="display:inline;" action="/delete/{image}" method="post">
                    <button type="submit">Delete</button>
                </form>
            </li>
            """
            for image in files
        ]
    )

    return HTMLResponse(
        content=f"""
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Image Management</title>
        </head>
        <body>
            <h1>Image Management</h1>

            <ul>
                {files_list_html}
            </ul>
        </body>
        </html>
        """,
        status_code=200,
    )


@app.post("/delete/{filename}")
async def delete_image(filename: str):
    file_path = os.path.join(IMAGE_DIR, filename)
    if not os.path.isfile(file_path):
        raise HTTPException(status_code=404, detail="File not found")
    os.remove(file_path)
    return RedirectResponse("/", status_code=303)


@app.get("/download/{filename}")
async def download_image(filename: str):
    file_path = os.path.join(IMAGE_DIR, filename)
    if not os.path.isfile(file_path):
        raise HTTPException(status_code=404, detail="File not found")
    return FileResponse(file_path, media_type='application/octet-stream', filename=filename)

@app.post("/run-inference")
async def get_haircut(source: UploadFile = File(...), target: UploadFile = File(...)):
    try:
        # Define file paths
        source_filepath = os.path.join('./data/uploaded_images', source.filename)
        target_filepath = os.path.join('./data/uploaded_images', target.filename)

        # Save files to disk
        with open(source_filepath, 'wb') as f:
            f.write(source.file.read())
        with open(target_filepath, 'wb') as f:
            f.write(target.file.read())

        # # Perform the hairstyle transfer
        # result_file_path = tool.hairstyle_transfer(
        #     source_filepath,
        #     target_filepath,
        #     alpha_blend=False
        # )

        # # Verify that the result file exists
        # if not os.path.exists(result_file_path):
        #     raise HTTPException(status_code=404, detail="Result file not found")

        # # Clean up temporary files
        # # os.remove(source_filepath)
        # # os.remove(target_filepath)

        # # Respond with the result image file
        # return FileResponse(result_file_path)

    except Exception as e:
        # General exception handling, return error response
        return JSONResponse(
            content={"error": f"An error occurred: {str(e)}"},
            status_code=500
        )


if __name__ == "__main__":
    uvicorn.run("main:app", reload=True, port=8000)
generate,fast,api,route,for,download,checked,delete,checked,and,download,delete,individual,image,into,below,html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Dashboard</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f0f0f0;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .tabs {
            display: flex;
            margin-bottom: 20px;
        }
        .tab {
            padding: 10px 20px;
            background-color: #ddd;
            border: none;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        .tab:hover {
            background-color: #ccc;
        }
        .tab.active {
            background-color: #fff;
        }
        .tab-content {
            display: none;
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
        }
        .tab-content.active {
            display: block;
        }
        .image-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
        }
        .image-box {
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 5px;
            overflow: hidden;
            transition: transform 0.3s;
            position: relative;
        }
        .image-box:hover {
            transform: scale(1.05);
        }
        .image-box img {
            width: 100%;
            height: 200px;
            object-fit: cover;
        }
        .image-box .title {
            padding: 10px;
            text-align: center;
            font-weight: bold;
        }
        .image-actions {
            display: flex;
            justify-content: space-around;
            padding: 10px;
        }
        .btn {
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn-download {
            background-color: #4CAF50;
            color: white;
        }
        .btn-delete {
            background-color: #f44336;
            color: white;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 300px;
            text-align: center;
        }
        .modal-actions {
            margin-top: 20px;
        }
        .modal-actions button {
            margin: 0 10px;
        }
        .checkbox-container {
            position: absolute;
            top: 10px;
            left: 10px;
            background-color: rgba(255, 255, 255, 0.7);
            padding: 5px;
            border-radius: 3px;
        }
        .bulk-actions {
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .select-all-container {
            display: flex;
            align-items: center;
        }
        .select-all-container label {
            margin-left: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Image Dashboard</h1>
        <div class="tabs">
            <button class="tab active" data-tab="face">Face Images</button>
            <button class="tab" data-tab="hair">Hair Images</button>
        </div>
        <div id="faceTab" class="tab-content active">
            <div class="bulk-actions">
                <div class="select-all-container">
                    <input type="checkbox" id="selectAllFace" class="select-all" data-tab="face">
                    <label for="selectAllFace">Select All</label>
                </div>
                <div>
                    <button id="downloadAllFace" class="btn btn-download">Download Selected</button>
                    <button id="deleteAllFace" class="btn btn-delete">Delete Selected</button>
                </div>
            </div>
            <div class="image-grid">
                <div class="image-box" data-id="face1">
                    <div class="checkbox-container">
                        <input type="checkbox" class="image-checkbox" data-tab="face">
                    </div>
                    <img src="/placeholder.svg?height=200&width=200" alt="Face 1">
                    <div class="title">Face 1</div>
                    <div class="image-actions">
                        <button class="btn btn-download">Download</button>
                        <button class="btn btn-delete">Delete</button>
                    </div>
                </div>
                <div class="image-box" data-id="face2">
                    <div class="checkbox-container">
                        <input type="checkbox" class="image-checkbox" data-tab="face">
                    </div>
                    <img src="/placeholder.svg?height=200&width=200" alt="Face 2">
                    <div class="title">Face 2</div>
                    <div class="image-actions">
                        <button class="btn btn-download">Download</button>
                        <button class="btn btn-delete">Delete</button>
                    </div>
                </div>
                <div class="image-box" data-id="face3">
                    <div class="checkbox-container">
                        <input type="checkbox" class="image-checkbox" data-tab="face">
                    </div>
                    <img src="/placeholder.svg?height=200&width=200" alt="Face 3">
                    <div class="title">Face 3</div>
                    <div class="image-actions">
                        <button class="btn btn-download">Download</button>
                        <button class="btn btn-delete">Delete</button>
                    </div>
                </div>
                <div class="image-box" data-id="face4">
                    <div class="checkbox-container">
                        <input type="checkbox" class="image-checkbox" data-tab="face">
                    </div>
                    <img src="/placeholder.svg?height=200&width=200" alt="Face 4">
                    <div class="title">Face 4</div>
                    <div class="image-actions">
                        <button class="btn btn-download">Download</button>
                        <button class="btn btn-delete">Delete</button>
                    </div>
                </div>
            </div>
        </div>
        <div id="hairTab" class="tab-content">
            <div class="bulk-actions">
                <div class="select-all-container">
                    <input type="checkbox" id="selectAllHair" class="select-all" data-tab="hair">
                    <label for="selectAllHair">Select All</label>
                </div>
                <div>
                    <button id="downloadAllHair" class="btn btn-download">Download Selected</button>
                    <button id="deleteAllHair" class="btn btn-delete">Delete Selected</button>
                </div>
            </div>
            <div class="image-grid">
                <div class="image-box" data-id="hair1">
                    <div class="checkbox-container">
                        <input type="checkbox" class="image-checkbox" data-tab="hair">
                    </div>
                    <img src="/placeholder.svg?height=200&width=200" alt="Hair 1">
                    <div class="title">Hair 1</div>
                    <div class="image-actions">
                        <button class="btn btn-download">Download</button>
                        <button class="btn btn-delete">Delete</button>
                    </div>
                </div>
                <div class="image-box" data-id="hair2">
                    <div class="checkbox-container">
                        <input type="checkbox" class="image-checkbox" data-tab="hair">
                    </div>
                    <img src="/placeholder.svg?height=200&width=200" alt="Hair 2">
                    <div class="title">Hair 2</div>
                    <div class="image-actions">
                        <button class="btn btn-download">Download</button>
                        <button class="btn btn-delete">Delete</button>
                    </div>
                </div>
                <div class="image-box" data-id="hair3">
                    <div class="checkbox-container">
                        <input type="checkbox" class="image-checkbox" data-tab="hair">
                    </div>
                    <img src="/placeholder.svg?height=200&width=200" alt="Hair 3">
                    <div class="title">Hair 3</div>
                    <div class="image-actions">
                        <button class="btn btn-download">Download</button>
                        <button class="btn btn-delete">Delete</button>
                    </div>
                </div>
                <div class="image-box" data-id="hair4">
                    <div class="checkbox-container">
                        <input type="checkbox" class="image-checkbox" data-tab="hair">
                    </div>
                    <img src="/placeholder.svg?height=200&width=200" alt="Hair 4">
                    <div class="title">Hair 4</div>
                    <div class="image-actions">
                        <button class="btn btn-download">Download</button>
                        <button class="btn btn-delete">Delete</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <p>Are you sure you want to delete the selected image(s)?</p>
            <div class="modal-actions">
                <button id="confirmDelete" class="btn btn-delete">Delete</button>
                <button id="cancelDelete" class="btn">Cancel</button>
            </div>
        </div>
    </div>

    <script>
        const tabs = document.querySelectorAll('.tab');
        const tabContents = document.querySelectorAll('.tab-content');
        const deleteModal = document.getElementById('deleteModal');
        const confirmDeleteBtn = document.getElementById('confirmDelete');
        const cancelDeleteBtn = document.getElementById('cancelDelete');
        let imagesToDelete = [];

        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const tabId = tab.getAttribute('data-tab');
                
                tabs.forEach(t => t.classList.remove('active'));
                tabContents.forEach(content => content.classList.remove('active'));
                
                tab.classList.add('active');
                document.getElementById(`${tabId}Tab`).classList.add('active');
            });
        });

        function downloadImage(imageBox) {
            const imageId = imageBox.getAttribute('data-id');
            const imageSrc = imageBox.querySelector('img').src;
            const link = document.createElement('a');
            link.href = imageSrc;
            link.download = `${imageId}.png`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        document.querySelectorAll('.btn-download').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const imageBox = e.target.closest('.image-box');
                downloadImage(imageBox);
            });
        });

        document.querySelectorAll('.btn-delete').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const imageBox = e.target.closest('.image-box');
                imagesToDelete = [imageBox];
                deleteModal.style.display = 'block';
            });
        });

        confirmDeleteBtn.addEventListener('click', () => {
            imagesToDelete.forEach(image => image.remove());
            imagesToDelete = [];
            deleteModal.style.display = 'none';
        });

        cancelDeleteBtn.addEventListener('click', () => {
            imagesToDelete = [];
            deleteModal.style.display = 'none';
        });

        window.addEventListener('click', (e) => {
            if (e.target === deleteModal) {
                deleteModal.style.display = 'none';
                imagesToDelete = [];
            }
        });

        function handleBulkAction(action, tab) {
            const checkboxes = document.querySelectorAll(`.image-checkbox[data-tab="${tab}"]:checked`);
            const selectedImages = Array.from(checkboxes).map(checkbox => checkbox.closest('.image-box'));

            if (action === 'download') {
                selectedImages.forEach(downloadImage);
            } else if (action === 'delete') {
                imagesToDelete = selectedImages;
                deleteModal.style.display = 'block';
            }
        }

        document.getElementById('downloadAllFace').addEventListener('click', () => handleBulkAction('download', 'face'));
        document.getElementById('deleteAllFace').addEventListener('click', () => handleBulkAction('delete', 'face'));
        document.getElementById('downloadAllHair').addEventListener('click', () => handleBulkAction('download', 'hair'));
        document.getElementById('deleteAllHair').addEventListener('click', () => handleBulkAction('delete', 'hair'));

        // Select All functionality
        document.querySelectorAll('.select-all').forEach(selectAll => {
            selectAll.addEventListener('change', (e) => {
                const tab = e.target.getAttribute('data-tab');
                const checkboxes = document.querySelectorAll(`.image-checkbox[data-tab="${tab}"]`);
                checkboxes.forEach(checkbox => {
                    checkbox.checked = e.target.checked;
                });
            });
        });

        // Update Select All when individual checkboxes change
        document.querySelectorAll('.image-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', (e) => {
                const tab = e.target.getAttribute('data-tab');
                const selectAll = document.querySelector(`.select-all[data-tab="${tab}"]`);
                const checkboxes = document.querySelectorAll(`.image-checkbox[data-tab="${tab}"]`);
                selectAll.checked = Array.from(checkboxes).every(cb => cb.checked);
            });
        });
    </script>
</body>
</html>use,fastapi,efficient,engine,to,handle,this,promote,code,modul.arity,and,best,practice