首页 > 其他分享 >单个应用失败代码存档

单个应用失败代码存档

时间:2024-05-02 21:23:42浏览次数:14  
标签:return 存档 代码 error file 单个 import data image

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>

 

标签:return,存档,代码,error,file,单个,import,data,image
From: https://www.cnblogs.com/zly324/p/18170586

相关文章

  • c#矩阵代码
    转置让我写成了对角线交换。。。还是要记录下对角线交换代码:publicint[][]Transpose(int[][]matrix){inttemp=0;intm=matrix.Length,n=matrix[0].Length;for(inti=0;i<m;i++){for(intj=i+1;j<n;j++){......
  • kafka消费者提交方式(代码演示)
    自动提交,手动提交(异步提交,同步提交,异步同步结合提交),原理:提交后,重新消费消息位移发生变化。1publicclassMyConsumer{23privatestaticKafkaConsumer<String,String>consumer;4privatestaticPropertiesproperties;56static{7......
  • ResNet代码精读
    classBasicBlock(nn.Module):expansion=1def__init__(self,in_channel,out_channel,stride=1,downsample=None,**kwargs):#虚线对应的downsamplesuper(BasicBlock,self).__init__()self.conv1=nn.Conv2d(in_channels=in_channel,ou......
  • Sensor代码框架
    #include<stdio.h>//定义一个枚举类型来表示光电开关的状态typedefenum{SWITCH_OPEN,SWITCH_CLOSED}SwitchState;//定义一个结构体来记录光电开关传感器的状态typedefstruct{SwitchStatecurrentState;//当前状态SwitchStatelastState;......
  • SAP 事务代码CU71报错 - 特性LOBM_LWEDT不存在 -
    SAP事务代码CU71报错-特性LOBM_LWEDT不存在 -  1,在事务代码CU71或者如下配置里。    定义排序规则,   试图使用SAP标准特性LOBM_LWEDT, SAP报错说:’特性LOBM_LWEDT不存在’。这是SAP系统上的一个标准的特性,怎么能不存在SAP系统上呢?  2,解决方法:......
  • Unity游戏框架设计之存档管理器
    Unity游戏框架设计之存档管理器存档管理器的主要功能是实现游戏进度的查询、存储(存档)、读取(读档)和删除(删档)。存档主要有三种实现方案。(一)PlayerPrefs。PlayerPrefs类用于在游戏中存储、删除、修改和访问玩家的数据。存储的数据是持久化的,即使玩家关闭游戏或重新启动设备,数据也......
  • 五个重要的编程原则让你写出高质量代码
    Therearefiveprinciplesthatyoushouldconform.1:Singleresponsibilityprinciple.各司其职,一个对象不要封装的太复杂,设计的时候要考虑好哪些功能属于这个对象,不要将一个对象弄得太复杂,当你意识到一个对象承担了太多责任的时候,尝试分开它,减小耦合度,以便维护。2:Open-Clo......
  • 代码
     #-*-coding:utf-8-*-"""@author:14931@file:deletlie.py@time:2024/05/01@desc:"""importnumpyasnpimportpandasaspdfile_path='D:/NM004-20230627224400-20230627224859-0.txt'#读整个txt文件读取到单个字符串wit......
  • html,js代码编译,加密,代码一键打包软件,HTML转exe程序
    个人软件注意杀毒软件会报毒,,放行便可小尘web打包程序可以将整个web工程项目打包成一个exe程序运行不是打包浏览器内核应用,是代码打包软件,打包后和原来一样放在nginx类软件里运行下载地址https://download.csdn.net/download/rllmqe/88789653链接:https://pan.baidu.com/s/1HTql......
  • SpringBoot camunda常用代码
    图例: 1:默认排他网关,表达式Type:expression:${number%200==0}2:servicetask(系统自动执行用的最多):常用Delegateexpression${testGateWay}举例:@Component("testGateWay")publicclassTestGateWayimplementsJavaDelegate{@Overridepublicvoidexecute......