Я хочу скомпилировать прогу на питоне с библиотекой eel
У меня ошибка при запуске скомпилированного код с библиотекой eel.
Вот скрин ошибки:
Вот его содержимое:
Traceback (most recent call last):
File "main.py", line 1, in <module>
import eel
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
File "eel\__init__.py", line 15, in <module>
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
File "bottle.py", line 73, in <module>
AttributeError: 'NoneType' object has no attribute 'write'
Вот код main.py:
import eel
import datetime
import sys
import time
import webbrowser
from os import system
from random import choice
import requests
from bs4 import BeautifulSoup
from forex_python.converter import CurrencyRates
from openai import OpenAI
from psutil import virtual_memory as memory
from pyowm import OWM
from translate import Translator
import google.generativeai as genai
import elevenlabs
elevenlabs.set_api_key()
username = "User"
clientID = ''
clientSecret = ''
to_lang = 'ru'
genai.configure(api_key="")
model = genai.GenerativeModel('gemini-pro')
tolng = 'en'
tr = Translator(to_lang=to_lang)
tra = Translator(to_lang=tolng)
client = OpenAI(api_key='')
eel.init('web')
@eel.expose
def process_input(user_input):
global response_text
try:
if user_input.lower() == 'Алло':
response_text = 'Что?'
elif user_input.lower() == "Пока":
response_text = 'До встречи!'
sys.exit()
elif 'Открой youtube' in user_input.lower():
response_text = "Уже открываю."
url = 'https://www.youtube.com'
webbrowser.open(url)
elif 'Открой браузер.' in user_input.lower():
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
webbrowser.get(chrome_path).open("google.com")
elif "Прочитай заметку." in user_input.lower():
with open('todo_list.txt', 'r') as file:
tasks = file.read()
response_text = f"Список задач: \n{tasks}"
elif 'Расскажи факт' in user_input.lower():
fact_url = "https://randstuff.ru/fact/"
response = requests.get(fact_url)
soup = BeautifulSoup(response.content, 'html.parser').findAll('td')
items = list(soup)
funny_fact = items[0]
response_text = str(funny_fact).replace('<td>', '').replace('</td>', '').replace(' ', ' ')
elif 'Курс доллара' in user_input.lower():
response_text = f'Курс доллара к Узбекским суммам: {(CurrencyRates().get_rate("USD", "UZS")): 2f}.'
elif 'Сейчас сколько' in user_input.lower():
now = datetime.datetime.now()
response_text = str(f"Сейчас {now.hour}" + ':' + f"{now.minute}.")
elif 'Открой дискорд' in user_input.lower():
system(r"C:\Users\user\AppData\Local\Discord\Update.exe --processStart Discord.exe")
system("cls")
response_text = choice(["Открываю дискорд.", "Включаю дискорд.", "Запускаю дискорд."])
elif 'Калькулютор' in user_input.lower():
response_text = "Открываю калькулятор."
system("calc")
elif 'Ножницы' in user_input.lower():
response_text = "Открываю ножницы."
system("snippingtool")
elif 'Перезагрузи компьютер' in user_input.lower():
response_text = 'До скорых встреч!'
time.sleep(6)
system('shutdown /r /f /t 10 /c "Перезагрузка будет выполнена через 10 секунд"')
elif 'Какая погода' in user_input.lower():
place = ""
country = ""
country_and_place = place + ", " + country
owm = OWM('')
mgr = owm.weather_manager()
observation = mgr.weather_at_place(country_and_place)
w = observation.weather
status = tr.translate(w.detailed_status)
humidity = w.humidity
temp = w.temperature('celsius')['temp']
response_text = f"""В городе {place} сейчас {status}.\nТемпература {round(temp)} градусов по цельсию.\n
Влажность составляет {humidity}%.\nСкорость ветра {w.wind()['speed']} метров в секунду."""
elif "как" and "тебя зовут" in user_input.lower():
response_text = "Меня зовут Ассистент."
elif "как" and "зовут тебя" in user_input.lower():
response_text = "Меня не зовут, я сам прихожу."
elif "на сколько нагружен компьютер" in user_input.lower() or "На сколько нагружен компьютер" in user_input.lower():
mem = memory()
response_text = f'Компьютер загружен на {round(mem.percent)}%.'
elif "На сколько нагружен компьютер" in user_input.lower() or "На сколько нагружен компьютер" in user_input.lower():
mem = memory()
response_text = f'Компьютер загружен на {round(mem.percent)}%.'
else:
try:
if user_input == "":
pass
else:
ens = tra.translate(user_input)
completion = client.chat.completions.create(
model="gpt-3.5-turbo-1106",
messages=[
{"role": "system",
"content": """Your name is DerNeX, you created by DevNexe. And user name is DevNexe, if DevNexe asks you 'who am I' or 'кто я такой' or something like that,
you should answer like this: 'You are DevNexe, my creator'"""},
{"role": "user",
"content": ens}
]
)
gggsx = completion.choices[0].message.content
response_text = tr.translate(gggsx)
except:
try:
if user_input == "":
pass
else:
ens = tra.translate(user_input)
response = model.generate_content(ens)
hf = response.text
response_text = tr.translate(hf)
except Exception as e:
if user_input == "":
pass
else:
response_text = "Произошла ошибка попробуйте позже"
print(e)
try:
if user_input == "":
pass
else:
audio = elevenlabs.generate(
text=response_text,
voice="Bill",
model="eleven_multilingual_v2"
)
elevenlabs.play(audio)
except Exception as e:
if user_input == "":
pass
else:
print(f"Error: {e}.")
audio = elevenlabs.generate(
text=response_text,
voice="Bill",
model="eleven_multilingual_v2"
)
elevenlabs.play(audio)
except Exception as e:
print(f"Error: {e}.")
if user_input == "":
pass
else:
return "DerNeX: " + response_text
eel.start('main.html', size=(600, 800))
Вот код main.html:
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta content="dark light" name="color-scheme">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<style>
html {
background-color: hsl(0deg 0% 14.32%);
}
body{
overflow: hidden;
}
.mes-con {
display: grid;
margin-top: 50px;
grid-template-rows: 1fr 90px;
color: hsl(0deg 0% 14.32%);
}
.input-container {
display: flex;
margin: 10px;
}
input[type="text"] {
background-color: #121212;
box-sizing: border-box;
border: 2px solid hsl(0deg 0% 76.53%);
padding: 10px;
border-radius: 5px;
width: 95%;
max-height: 90px;
overflow-y: auto;
color: #ffffff;
}
.button {
background-color: hsl(0deg 0% 14.32%);
border-radius: 5px;
border-color: white;
color: white;
padding: 10px 10px;
text-align: center;
text-decoration: none;
font-size: 16px;
cursor: pointer;
margin-left: 10px;
display: flex;
align-items: center;
}
.container {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
text-align: center;
background-color: hsl(0deg 0% 14.32%);
}
#result {
overflow-y: auto;
color: white;
height: 665px;
}
h1 {
color: white;
}
#menu {
background-color: hsl(0deg 0.27% 10.36%);
}
#bar {
background-color: hsl(0deg 0.27% 10.36%);
position: absolute;
top: 0;
left: 0;
width: 100%;
}
#menu-button {
color: white;
margin-left: 10px;
}
#menuPanel {
position: fixed;
top: 0;
left: 0;
width: 300px;
height: 100%;
background-color: hsl(0deg 0% 30.07%);
z-index: 1000;
transform: translateX(-100%);
transition: transform 0.3s ease;
padding: 20px;
}
#closeButton {
position: absolute;
top: 10px;
right: 10px;
cursor: pointer;
color: white;
}
#panelText {
color: white;
}
.blur {
filter: blur(8px);
}
p {
background-color: hsl(0deg 0.27% 10.36%);
border-radius: 5px;
padding: 10px 10px;
}
</style>
<title>DerNeX</title>
</head>
<body>
<div id="menuPanel">
<img id="closeButton" onclick="toggleMenuPanel()" src="close.png">
<h1 id="panelText">test</h1>
</div>
<div id="mainContainer">
<div id="bar" style="display: flex; justify-content: space-between; align-items: center;">
<svg width="24" height="24" id="menu-button" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" onclick="toggleMenuPanel()">
<path fill-rule="evenodd" clip-rule="evenodd" d="M3 8C3 7.44772 3.44772 7 4 7H20C20.5523 7 21 7.44772 21 8C21 8.55228 20.5523 9 20 9H4C3.44772 9 3 8.55228 3 8ZM3 16C3 15.4477 3.44772 15 4 15H14C14.5523 15 15 15.4477 15 16C15 16.5523 14.5523 17 14 17H4C3.44772 17 3 16.5523 3 16Z" fill="currentColor"></path>
</svg>
<div style="text-align: center;">
<img src="logo.png">
</div>
<div></div>
</div>
<div class="mes-con">
<div id="result"></div>
<div class="container">
<div class="input-container">
<input type="text" id="myInput" placeholder="Сообщение…" oninput="handleInput(event)">
<button class="button" onclick="sendRequest()">
<img src="send.png">
</button>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/eel.js"></script>
<script type="text/javascript">
// Function to handle user input
function handleInput(event) {
if (event.inputType === 'insertParagraph') {
document.getElementById('myInput').value += '\n';
}
}
// Function to send user input to Python and display the result
async function sendRequest() {
const userInput = document.getElementById('myInput').value;
// Отображение ввода пользователя
document.getElementById('result').innerHTML += `<p>Вы: ${userInput}</p>`;
const responseText = await eel.process_input(userInput)();
// Отображение ответа
document.getElementById('result').innerHTML += `<p>${responseText}</p>`;
}
// Function to toggle the menu panel
function toggleMenuPanel() {
const menuPanel = document.getElementById('menuPanel');
const mainContainer = document.getElementById('mainContainer');
if (menuPanel.style.transform === 'translateX(-100%)') {
menuPanel.style.transform = 'translateX(0)';
mainContainer.classList.add('blur');
} else {
menuPanel.style.transform = 'translateX(-100%)';
mainContainer.classList.remove('blur');
}
}
</script>
</body>
</html>
Вот команда компиляции:
pyinstaller --onefile --noconsole --icon favicon.ico main.py