單個應用失敗程式碼存檔

不上火星不改名發表於2024-05-02

python版本

from flask import Flask, render_template, request, jsonify
import requests
import base64
import os
from PIL import Image
import io
import logging

# Configure Flask application
app = Flask(__name__, template_folder='../web')
app.config['UPLOAD_FOLDER'] = 'uploads/'  # Assuming there is an 'uploads' folder at the same level as 'web'
logging.basicConfig(level=logging.DEBUG)

def encode_image_to_base64(image_path):
    """Encode image file to base64 string."""
    with Image.open(image_path) as image:
        buffered = io.BytesIO()
        image.save(buffered, format="PNG")
        return base64.b64encode(buffered.getvalue()).decode('utf-8')

def call_api(image_data):
    """Call an external API to process the image data."""
    url = "http://127.0.0.1:7860/sdapi/v1/txt2img"  # Replace with your actual API URL
    data = {
        "prompt": "<lora:CWG_archisketch_v1:1>,Building,pre sketch,masterpiece,best quality,featuring markers,(3D:0.7)",
        "negative_prompt": "blurry, lower quality, glossy finish,insufficient contrast",
        "init_images": [image_data],
        "steps": 30,
        "width": 1024,
        "height": 1024,
    }
    try:
        response = requests.post(url, json=data)
        response.raise_for_status()  # Raises an HTTPError for bad responses
        return response.json()
    except requests.exceptions.RequestException as e:
        logging.error(f"API call failed: {e}")
        return None

@app.route('/', methods=['GET'])
def index():
    """Render the main page."""
    return render_template('upload.html')

@app.route('/upload', methods=['POST'])
def upload_file():
    """Handle image upload and API interaction."""
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    if file:
        filename = file.filename
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)  # Save file to uploads folder
        image_data = encode_image_to_base64(file_path)
        api_result = call_api(image_data)
        if api_result is not None:
            return jsonify(api_result)
        else:
            return jsonify({'error': 'API call failed'}), 500

if __name__ == '__main__':
    app.run(debug=True)

html版本

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload and Process</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        img {
            max-width: 100%;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Upload an Image</h1>
        <form id="uploadForm" enctype="multipart/form-data">
            <input type="file" name="file" required>
            <button type="submit">Upload and Process</button>
        </form>
        <div id="result"></div>
    </div>

    <script>
        document.getElementById('uploadForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const formData = new FormData(this);
            fetch('/upload', {
                method: 'POST',
                body: formData,
            })
            .then(response => response.json())
            .then(data => {
                const resultDiv = document.getElementById('result');
                if (data.error) {
                    resultDiv.innerHTML = `<p>Error: ${data.error}</p>`;
                } else {
                    // Assuming the API returns an image URL or image data directly
                    resultDiv.innerHTML = `<img src="data:image/png;base64,${data.image}" alt="Processed Image">`;
                    // If data is structured differently, adjust accordingly
                }
            })
            .catch(error => {
                document.getElementById('result').innerHTML = `<p>Error: ${error.message}</p>`;
            });
        });
    </script>
</body>
</html>

相關文章