首页 > 编程语言 >niji&网文 exe程序

niji&网文 exe程序

时间:2024-03-17 17:46:22浏览次数:25  
标签:exe niji self response tk 网文 path font image

import tkinter as tk
from tkinter import filedialog, messagebox
import requests
import os
from PIL import Image, ImageTk
from threading import Thread
import time
import shutil

class WebNovelImageGenerator:
    def __init__(self, root):
        self.root = root
        self.setup_ui()
        self.folder_path = ""
        self.latest_image_path = ""

    def setup_ui(self):
        self.root.title("网文图片生成器")
        self.root.configure(bg='black')
        self.root.state('zoomed')  # Set the window to fullscreen

        self.main_frame = tk.Frame(self.root, bg='black')
        self.main_frame.pack(fill=tk.BOTH, expand=True)

        # Left panel for inputs and buttons
        self.left_panel = tk.Frame(self.main_frame, bg='black')
        self.left_panel.pack(side=tk.LEFT, fill=tk.Y, padx=20, pady=20)

        # Right panel for image display
        self.right_panel = tk.Frame(self.main_frame, bg='black')
        self.right_panel.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

        label_font = ('Arial', 17)  # Enlarged font size
        tk.Label(self.left_panel, text="网文图片生成器:请在输入框内输入一段网络文学", fg='white', bg='black', font=label_font).pack(anchor='w')

        self.entry = tk.Entry(self.left_panel, width=50, font=label_font)
        self.entry.pack(anchor='w', pady=5)

        self.generate_button = tk.Button(self.left_panel, text="生成图片", command=self.generate_image, height=2, width=20, font=label_font)
        self.generate_button.pack(anchor='w', pady=5)

        self.clear_input_button = tk.Button(self.left_panel, text="清除输入", command=self.clear_input, height=2, width=20, font=label_font)
        self.clear_input_button.pack(anchor='w', pady=5)

        self.folder_button = tk.Button(self.left_panel, text="选择图片保存文件夹", command=self.select_folder, height=2, width=20, font=label_font)
        self.folder_button.pack(anchor='w', pady=5)

        self.copy_button = tk.Button(self.left_panel, text="复制最新图片", command=self.copy_latest_image, height=2, width=20, font=label_font)
        self.copy_button.pack(anchor='w', pady=5)

        self.gpt_response_label = tk.Label(self.left_panel, text="", fg='white', bg='black', wraplength=self.entry.winfo_reqwidth(), font=label_font)  # Adjusted width
        self.gpt_response_label.pack(anchor='w', pady=5)

        self.image_label = tk.Label(self.right_panel, bg='black')
        self.image_label.pack(pady=10)

    def select_folder(self):
        self.folder_path = filedialog.askdirectory(title="选择图片保存的文件夹")
        if not self.folder_path:
            messagebox.showwarning("警告", "未选择文件夹!")
        else:
            self.display_latest_image()

    def generate_image(self):
        if not self.folder_path:
            messagebox.showerror("错误", "请先选择一个文件夹!")
            return

        user_input = self.entry.get()
        if not user_input:
            messagebox.showwarning("警告", "输入框为空,请输入一段网文!")
            return

        Thread(target=self.fetch_and_display_image, args=(user_input,)).start()

    def fetch_and_display_image(self, user_input):
        gpt_response = self.get_prompt_from_openai(user_input)
        if gpt_response:
            self.gpt_response_label.config(text=gpt_response)  # Display GPT response in the GUI
            self.download_and_display_image(gpt_response)



    def get_prompt_from_openai(self, user_input):
        api_key = "sk-JBQJmyrMcAAJJtWb00816e05Ff80438389BaE80834Ea5480"
        headers = {"Authorization": f"Bearer {api_key}"}
        instruction = (
            "我将给你一段网络文学,如{0}, 先判断文学是现代文还是古代文。如果是现代文,用现代都市漫画风格。返还给我一段自然语言提示词,提示词要长80英文词。"
            "如果是古代文,用国风古风武侠漫画风格。画面需要精美,叙事小说风格。请你把这个文学转译成适合stable diffusion作画的英文描述。不要直译,需要一个画面。"
            "画面要有故事感,提示词以描述人物为主,武侠感强一点,人物白瘦幼。"
            "重要:提示词最后加上后缀' --niji 6',提示词不要有引号出现。只要回答英文提示词,不要回答其他东西。"
        )

        data = {
            "model": "gpt-4-1106-preview",
            "messages": [
                {"role": "system", "content": instruction.format(user_input)},
                {"role": "user", "content": user_input}
            ]
        }

        response = requests.post("https://oneapi.xty.app/v1/chat/completions", json=data, headers=headers)
        if response.status_code == 200:
            completion = response.json()
            gpt_response = completion['choices'][0]['message']['content']
            return gpt_response
        else:
            messagebox.showerror("错误", "获取提示词失败!")
            return None

    def download_and_display_image(self, prompt):
        token = "8ed375d196b849098c43dae29b9ab0dc"
        headers = {"accept": "application/json", "content-type": "application/json"}
        payload = {"action": "generate", "prompt": prompt, "timeout": 480}

        response = requests.post(f"https://api.zhishuyun.com/midjourney/imagine?token={token}", json=payload, headers=headers)
        if response.status_code == 200:
            data = response.json()
            image_url = data.get("image_url")
            if image_url:
                self.download_image(image_url)
            else:
                messagebox.showerror("错误", "未从API获取到图片URL。")
        else:
            messagebox.showerror("错误", "图片生成失败!")

    def download_image(self, image_url):
        response = requests.get(image_url)
        if response.status_code == 200:
            image_filename = f"image_{int(time.time())}.jpg"
            image_path = os.path.join(self.folder_path, image_filename)
            with open(image_path, 'wb') as f:
                f.write(response.content)
            self.display_image(image_path)
        else:
            messagebox.showerror("错误", "下载图片失败!")

    def display_image(self, image_path):
        self.latest_image_path = image_path
        img = Image.open(image_path)
        img.thumbnail((1000, 1000), Image.Resampling.LANCZOS)
        photo = ImageTk.PhotoImage(img)
        self.image_label.config(image=photo)
        self.image_label.image = photo  # keep a reference

    def display_latest_image(self):
        if self.folder_path:
            try:
                list_of_files = [os.path.join(self.folder_path, file) for file in os.listdir(self.folder_path) if file.endswith('.jpg')]
                latest_file = max(list_of_files, key=os.path.getctime)
                self.display_image(latest_file)
            except ValueError:
                messagebox.showinfo("信息", "文件夹内没有图片!")

    def copy_latest_image(self):
        if not self.latest_image_path:
            messagebox.showinfo("提示", "没有图片可以复制!")
            return
        destination = filedialog.askdirectory(title="选择复制到的文件夹")
        if not destination:
            return
        shutil.copy(self.latest_image_path, destination)
        messagebox.showinfo("成功", "图片复制成功!")

    def clear_input(self):
        # Clears the text in the entry widget
        self.entry.delete(0, tk.END)

def main():
    root = tk.Tk()
    app = WebNovelImageGenerator(root)
    root.mainloop()

if __name__ == "__main__":
    main()

 

标签:exe,niji,self,response,tk,网文,path,font,image
From: https://www.cnblogs.com/zly324/p/18078869

相关文章

  • Windows7系统consent.exe文件丢失问题
    其实很多用户玩单机游戏或者安装软件的时候就出现过这种问题,如果是新手第一时间会认为是软件或游戏出错了,其实并不是这样,其主要原因就是你电脑系统的该dll文件丢失了或没有安装一些系统软件平台所需要的动态链接库,这时你可以下载这个consent.exe文件(挑选合适的版本文件)把它放......
  • Python疑难杂症(13)---Python的几个比较难理解的内置函数,包括range、zip、map、lambda
    1、range()range(start=0, stop[, step=1])构造器的参数必须为整数(可以是内置的 int 或任何实现了 __index__() 特殊方法的对象)。生成一个start到stop的数组,左闭右开, 类型表示不可变的数字序列,通常用于在 for 循环中循环指定的次数。list(range(6))[0,1,2,3......
  • 小白解决Win11(Win10)下.html文件默认打开方式无法修改,绑定为IE浏览器 iexplorer.exe
    解决方法按Win+R键,输入regedit,地址栏输入计算机\HKEY_CLASSES_ROOT\IE.AssocFile.HTM\shell\opennew\command双击(默认),将"C:\ProgramFiles(x86)\internetexplorer\iexplore.exe"%1修改成"你的浏览器的路径"%1(英文的双引号不要去掉)OK了如何查找浏览器的路径打开任......
  • 【2024.03.12】定时执行专家 V7.2 发布 - TimingExecutor V7.2 Release
    目录▉软件介绍▉新版本V7.2 下载地址▉ V7.2新功能▼2024-03-12 V7.2 -更新日志▉ V7.x 新UI设计▉软件介绍《定时执行专家》是一款制作精良、功能强大、毫秒精度、专业级的定时任务执行软件。软件具有25种【任务类型】、12种【触发器】触发方式,并且......
  • eclipse 问题之一:Plugin execution not covered by lifecycle configuration
    1、问题eclipse作为java工程的开发工具,可以集成maven直接管理maven工程。但是对于maven工程中描述的插件,有时候eclipse会报如下错误(示例:Pluginexecutionnotcoveredbylifecycleconfiguration:org.codehaus.mojo:exec-maven-plugin:3.1.1:java(execution:default......
  • 【rust】《处理报错could not execute `llvm-config` one or more times》
    报错信息couldnotexecute`llvm-config`oneormoretimes,iftheLLVM_CONFIG_PATHenvironmentvariableissettoafullpathtovalid`llvm-config`executableitwillbeusedtotrytofindaninstanceof`libclang`onyoursystem:"couldn'texec......
  • 标准库之exec
    目录一、exec介绍1.exec函数和Cmd的方法二、案例1.只执行命令,不获取结果2.执行命令并获取结果3.执行命令,区分stdout和stderr4.使用管道,多条命令组合5.设置程序级别的环境变量一、exec介绍有时候我们的go程序需要执行外部的命令,比如执行linuxshell命令,一个其他语言编......
  • 取证中exe文件的分析
    对exe文件的分析,对于犯罪嫌疑人的作案手法的确定有着极其重要的参考价值!奈何本人逆向还未涉猎,拿到exe文件后也只能跑跑软件,下面分享下exe文件的常见分析思路!微步云沙箱https://s.threatbook.com/使用很方便,可以对需要分析的文件有个初步的了解火绒安全火绒安全工具中有启动......
  • [Javascript] Generator & Iterators exercise
    Generatorcanrunwithfor..ofand...,whichwillonlyemityieldvalues Forexample:function*count(){yield1;yield2;return3;}for(constvalueofcount()){console.log(value)//1,2}console.log([...count()])//[1,2] ......
  • vagrant up 启动报错 Stderr: VBoxManage.exe: error: A NAT rule of this name alrea
    报错:使用vagrantup启动VirtualBox虚拟机时报错:Stderr:VBoxManage.exe:error:ANATruleofthisnamealreadyexistsVBoxManage.exe:error:Details:codeE_INVALIDARG(0x80070057),componentNATEngineWrap,interfaceINATEngine,calleeIUnknownVBoxManage.exe:e......