Skip to content

Instantly share code, notes, and snippets.

@KaushikShresth07
Created December 29, 2024 12:13
Show Gist options
  • Save KaushikShresth07/7c62c2c7f233d334e79799ac0896713e to your computer and use it in GitHub Desktop.
Save KaushikShresth07/7c62c2c7f233d334e79799ac0896713e to your computer and use it in GitHub Desktop.
responses = [
"The rest of the result has been printed to the chat screen, kindly check it out sir.",
"The rest of the text is now on the chat screen, sir, please check it.",
"You can see the rest of the text on the chat screen, sir.",
"The remaining part of the text is now on the chat screen, sir.",
"Sir, you'll find more text on the chat screen for you to see.",
"The rest of the answer is now on the chat screen, sir.",
"Sir, please look at the chat screen, the rest of the answer is there.",
"You'll find the complete answer on the chat screen, sir.",
"The next part of the text is on the chat screen, sir.",
"Sir, please check the chat screen for more information.",
"There's more text on the chat screen for you, sir.",
"Sir, take a look at the chat screen for additional text.",
"You'll find more to read on the chat screen, sir.",
"Sir, check the chat screen for the rest of the text.",
"The chat screen has the rest of the text, sir.",
"There's more to see on the chat screen, sir, please look.",
"Sir, the chat screen holds the continuation of the text.",
"You'll find the complete answer on the chat screen, kindly check it out sir.",
"Please review the chat screen for the rest of the text, sir.",
"Sir, look at the chat screen for the complete answer."
]
@axinyyyx
Copy link

axinyyyx commented Feb 9, 2025

hey everyone i wrote the Gui.py code from his video but i got error please look at this code written below and the error i got is

====>ERROR<===== QPixmap::scaled: Pixmap is a null pixmap Traceback (most recent call last): File "d:\Uka\A-ver1\Frontend\GUI.py", line 454, in GraphicalUserInterface() ~~~~~~~~~~~~~~~~~~~~~~^^ File "d:\Uka\A-ver1\Frontend\GUI.py", line 449, in GraphicalUserInterface window = MainWindow() File "d:\Uka\A-ver1\Frontend\GUI.py", line 426, in init self.initUI() ~~~~~~~~~~~^^ File "d:\Uka\A-ver1\Frontend\GUI.py", line 434, in initUI initial_screen = InitialScreen() File "d:\Uka\A-ver1\Frontend\GUI.py", line 247, in init self.toggle_icon() ^^^^^^^^^^^^^^^^ AttributeError: 'InitialScreen' object has no attribute 'toggle_icon'

====================\ =====>GUI.PY code<======| ====================/

from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit,QStackedWidget, QWidget, QLineEdit,QGridLayout,QVBoxLayout,QHBoxLayout,QPushButton,QFrame,QLabel,QSizePolicy from PyQt5.QtGui import QIcon, QPainter,QMovie,QColor,QTextCharFormat,QFont,QPixmap,QTextBlockFormat from PyQt5.QtCore import Qt , QSize,QTimer from dotenv import dotenv_values import sys import os

env_vars = dotenv_values(".env") AssistantName = env_vars.get("AssistantName") current_dir = os.getcwd() old_chat_messages = "" TempDirPath = rf"{current_dir}/Frontend/Files" GraphicsDirPath = rf"{current_dir}/Frontend/Graphics"

def AnswerModifier(Answer): lines = Answer.split('\n') non_empty_lines = [line for line in lines if line.strip()] modified_answer = '\n'.join(non_empty_lines) return modified_answer

def QueryModifier(Query): new_query = Query.lower().strip() query_words = new_query.split() question_words = ["how", "what", "who", "where", "when", "why", "which", "whose", "whom", "can you", "what's", "where's", "how's"]

if any(word + " " in new_query for word in question_words):
    if query_words[-1][-1] in ['.', '?', '!']:
        new_query = new_query[:-1] + "?"
    else:
        new_query += "?"
else:
    if query_words[-1][-1] in ['.', '?', '!']:
        new_query = new_query[:-1] + "."
    else:
        new_query += "."

return new_query.capitalize()

def SetMicrophoneStatus(Command): with open(rf'{TempDirPath}\Mic.data', "w", encoding='utf-8') as file: file.write(Command)

def GetMicrophoneStatus(): with open(rf'{TempDirPath}\Mic.data', "r", encoding='utf-8') as file: Status = file.read() return Status

def SetAssistantStatus(Status): with open(rf'{TempDirPath}\Status.data', "w", encoding='utf-8') as file: file.write(Status)

def GetAssistantStatus(): with open(rf'{TempDirPath}\Status.data', "r", encoding='utf-8') as file: Status = file.read() return Status

def MicButtonInitialized(): SetMicrophoneStatus("False") def MicButtonClosed(): SetMicrophoneStatus("True")

def GraphicsDirectoryPath(Filename): path =rf'{GraphicsDirPath}{Filename}' return path

def TempDirectoryPath(Filename): Path = rf'{TempDirPath}{Filename}' return Path

def ShowTextToScreen(Text): with open(rf'{TempDirPath}\Responses.data', "w", encoding='utf-8') as file: file.write(Text)

class ChatSection(QWidget):

def __init__(self):
    super().__init__()
    layout = QVBoxLayout(self)
    layout.setContentsMargins(-10, 40, 40, 100)
    layout.setSpacing(-100)

    self.chat_text_edit = QTextEdit()
    self.chat_text_edit.setReadOnly(True)
    self.chat_text_edit.setTextInteractionFlags(Qt.NoTextInteraction)  # No text interaction
    self.chat_text_edit.setFrameStyle(QFrame.NoFrame)
    layout.addWidget(self.chat_text_edit)

    self.setStyleSheet("background-color: black;")
    layout.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
    layout.setStretch(1, 1)
    self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))

    text_color = QColor(Qt.blue)
    text_color_text = QTextCharFormat()
    text_color_text.setForeground(text_color)
    self.chat_text_edit.setCurrentCharFormat(text_color_text)

    self.gif_label = QLabel()
    self.gif_label.setStyleSheet("border: none;")
    
    movie = QMovie(GraphicsDirectoryPath("Jarvis.gif"))
    max_gif_size_W = 480
    max_gif_size_H = 270
    movie.setScaledSize(QSize(max_gif_size_W, max_gif_size_H))
    self.gif_label.setAlignment(Qt.AlignRight | Qt.AlignBottom)
    self.gif_label.setMovie(movie)
    movie.start()

    layout.addWidget(self.gif_label)
    
    self.label = QLabel("")
    self.label.setStyleSheet("color: white; font-size:16px; margin-right: 195px; border: none; margin-top: -30px;")
    self.label.setAlignment(Qt.AlignRight)
    layout.addWidget(self.label)
    layout.setSpacing(-10)
    layout.addWidget(self.gif_label)

    font = QFont()
    font.setPointSize(13)
    self.chat_text_edit.setFont(font)

    self.timer = QTimer(self)
    self.timer.timeout.connect(self.LoadMessages)
    self.timer.timeout.connect(self.SpeechRecogText)
    self.timer.start(5)

    self.chat_text_edit.viewport().installEventFilter(self)

    self.setStyleSheet("""
        QScrollBar:vertical {
            background: black;
            width: 10px;
            margin: 0px 0px 0px 0px;
        }

        QScrollBar::handle:vertical {
            background: white;
            min-height: 20px;
        }

        QScrollBar::add-line:vertical {
            background: black;
            subcontrol-position: bottom;
            subcontrol-origin: margin;
            height: 10px;
        }

        QScrollBar::sub-line:vertical {
            background: black;
            subcontrol-position: top;
            subcontrol-origin: margin;
            height: 10px;
        }

        QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {
            border: none;
            background: none;
            color: none;
        }

        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
    """)



def loadMessages(self):
    global old_chat_message

    with open(TempDirectoryPath('Responses.data'), "r", encoding='utf-8') as file:
        messages = file.read()

        if messages is None:
            pass
        elif len(messages) < 1:
            pass
        elif str(old_chat_message) == str(messages):
            pass
        else:
            self.addMessage(message=messages, color='White')
            old_chat_message = messages



def SpeechRecogText(self):
    with open(TempDirectoryPath('Status.data'), "r", encoding='utf-8') as file:
        messages = file.read()
        self.label.setText(messages)

def load_icon(self, path, width=60, height=60):
    pixmap = QPixmap(path)
    new_pixmap = pixmap.scaled(width, height)
    self.icon_label.setPixmap(new_pixmap)

def toggle_icon(self, event=None):
    if self.toggled:
        self.load_icon(GraphicsDirectoryPath('voice.png'), 60, 60)
        MicButtonInitialized
    else:
        self.load_icon(GraphicsDirectoryPath('mic.png'), 60, 60)
        MicButtonClosed

    self.toggled = not self.toggled

def addMessage(self, message, color):
    cursor = self.chat_text_edit.textCursor()
    format = QTextCharFormat()
    formatm = QTextBlockFormat()
    formatm.setTopMargin(10)
    formatm.setBottomMargin(10)
    format.setForeground(QColor(color))
    cursor.setBlockFormat(formatm)
    cursor.setCharFormat(format)
    cursor.insertText(message + "\n")
    self.chat_text_edit.setTextCursor(cursor)

class InitialScreen(QWidget): def init(self, parent=None): super().init(parent) desktop = QApplication.desktop() screen_width = desktop.screenGeometry().width() screen_height = desktop.screenGeometry().height() content_layout = QVBoxLayout() content_layout.setContentsMargins(0, 0, 0, 0)

    gif_label = QLabel()
    movie = QMovie(GraphicsDirectoryPath('Jarvis.gif'))
    gif_label.setMovie(movie)
    max_gif_size_H = int(screen_width / 16 * 9)
    movie.setScaledSize(QSize(screen_width, max_gif_size_H))
    gif_label.setAlignment(Qt.AlignCenter)
    movie.start()
    gif_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    self.icon_label = QLabel()
    pixmap = QPixmap(GraphicsDirectoryPath('Mic_on.png'))
    new_pixmap = pixmap.scaled(60, 60)
    self.icon_label.setPixmap(new_pixmap)
    self.icon_label.setFixedSize(150, 150)
    self.icon_label.setAlignment(Qt.AlignCenter)

    self.toggled = True
    self.toggle_icon()
    self.icon_label.mousePressEvent = self.toggle_icon

    self.label = QLabel("")
    self.label.setStyleSheet("color: white; font-size:16px ; margin-bottom:0;")
    
    content_layout.addWidget(gif_label, alignment=Qt.AlignCenter)
    content_layout.addWidget(self.label, alignment=Qt.AlignCenter)
    content_layout.addWidget(self.icon_label, alignment=Qt.AlignCenter)
    content_layout.setContentsMargins(0, 0, 150)

    self.setLayout(content_layout)
    self.setFixedHeight(screen_height)
    self.setFixedWidth(screen_width)
    self.setStyleSheet("background-color: black;")

    self.timer = QTimer(self)
    self.timer.timeout.connect(self.SpeechRecogText)
    self.timer.start(5)

def SpeechRecogText(self): with open(TempDirectoryPath('Status.data'), "r", encoding='utf-8') as file: messages = file.read() self.label.setText(messages)

def load_icon(self, path, width=60, height=60): pixmap = QPixmap(path) new_pixmap = pixmap.scaled(width, height) self.icon_label.setPixmap(new_pixmap)

def toggle_icon(self, event=None): if self.toggled: self.load_icon(GraphicsDirectoryPath('Mic_on.png'), 60, 60) MicButtonInitialized else: self.load_icon(GraphicsDirectoryPath('Mic_off.png'), 60, 60) MicButtonClosed

self.toggled = not self.toggled

class MessageScreen(QWidget): def init(self, parent=None): super().init(parent) desktop = QApplication.desktop() screen_width = desktop.screenGeometry().width() screen_height = desktop.screenGeometry().height() layout = QVBoxLayout()

    label = QLabel("")
    layout.addWidget(label)
    
    chat_section = ChatSection()
    layout.addWidget(chat_section)

    self.setLayout(layout)
    self.setStyleSheet("background-color: black;")
    self.setFixedHeight(screen_height)
    self.setFixedWidth(screen_width)

class CustomTopBar(QWidget): def init(self, parent, stacked_widget): super().init(parent) self.current_screen = None self.stacked_widget = stacked_widget def init(self): self.setFixedHeight(50) layout = QHBoxLayout(self) layout.setAlignment(Qt.AlignRight)

    home_button = QPushButton()
    home_icon = QIcon(GraphicsDirectoryPath("Home.png"))
    home_button.setIcon(home_icon)
    home_button.setText("  Home  ")
    home_button.setStyleSheet("height:40px; line-height:40px; background-color:white ; color: black")

    message_button = QPushButton()
    message_icon = QIcon(GraphicsDirectoryPath("Chats.png"))
    message_button.setIcon(message_icon)
    message_button.setText("  Chat  ")
    message_button.setStyleSheet("height:40px; line-height:40px; background-color:white ; color: black")

    minimize_button = QPushButton()
    minimize_icon = QIcon(GraphicsDirectoryPath("Minimize2.png"))
    minimize_button.setIcon(minimize_icon)
    minimize_button.setStyleSheet("background-color:white")
    minimize_button.clicked.connect(self.minimizeWindow)

    self.maximize_button = QPushButton()
    self.maximize_icon = QIcon(GraphicsDirectoryPath("Maximize.png"))
    self.restore_icon = QIcon(GraphicsDirectoryPath("Minimize.png"))
    self.maximize_button.setIcon(self.maximize_icon)
    self.maximize_button.setFlat(True)
    self.maximize_button.setStyleSheet("background-color:white")
    self.maximize_button.clicked.connect(self.maximizeWindow)

    close_button = QPushButton()
    close_icon = QIcon(GraphicsDirectoryPath("Close.png"))
    close_button.setIcon(close_icon)
    close_button.setStyleSheet("background-color:white")
    close_button.clicked.connect(self.closeWindow)

    line_frame = QFrame()
    line_frame.setFixedHeight(1)
    line_frame.setFrameShape(QFrame.HLine)
    line_frame.setFrameShadow(QFrame.Sunken)
    line_frame.setStyleSheet("border-color: black;")

    title_label = QLabel(f"{AssistantName}.capitalize() AI")
    title_label.setStyleSheet("color: black; font-size: 18px; background-color:white")

    home_button.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(0))
    message_button.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(1))

    layout.addWidget(title_label)
    layout.addStretch(1)
    layout.addWidget(home_button)
    layout.addWidget(message_button)
    layout.addWidget(minimize_button)
    layout.addWidget(self.maximize_button)
    layout.addWidget(close_button)
    layout.addWidget(line_frame)
    self.offset = None

def paintEvent(self, event):
    painter = QPainter(self)
    painter.fillRect(self.rect(), Qt.white)
    super().paintEvent(event)

def minimizeWindow(self):
    self.parent().showMinimized()

def maximizeWindow(self):
    
    if self.parent().isMaximized():
        self.parent().showNormal()
        self.maximize_button.setIcon(self.maximize_icon)
    else:
        self.parent().showMaximized()
        self.maximize_button.setIcon(self.restore_icon)

def closeWindow(self):
    self.parent().close()

def mousePressEvent(self, event):
    if self.draggable:
        self.offset = event.globalPos() - self.pos()

def mouseMoveEvent(self, event):
    if self.offset is not None:
        new_pos = event.globalPos() - self.offset
        self.parent().move(new_pos)

def showMessageScreen(self):
    if self.current_screen is not None:
        self.current_screen.hide()

    message_screen = MessageScreen(self)
    layout = self.layout()
    
    if layout is not None:
        layout.addWidget(message_screen)
        
    self.current_screen = message_screen

def showInitialScreen(self):
    if self.current_screen is not None:
        self.current_screen.hide()

    initial_screen = InitialScreen(self)
    layout = self.parent().layout()
    
    if layout is not None:
        layout.addWidget(initial_screen)
        
    self.current_screen = initial_screen

class MainWindow(QMainWindow): def init(self): super().init() self.setWindowFlags(Qt.FramelessWindowHint) self.initUI()

def initUI(self):
    desktop = QApplication.desktop()
    screen_width = desktop.screenGeometry().width()
    screen_height = desktop.screenGeometry().height()

    stacked_widget = QStackedWidget(self)
    initial_screen = InitialScreen()
    message_screen = MessageScreen()
    
    stacked_widget.addWidget(initial_screen)
    stacked_widget.addWidget(message_screen)

    self.setGeometry(0, 0, screen_width, screen_height)
    self.setStyleSheet("background-color: black;")
    
    top_bar = CustomTopBar(self, stacked_widget)
    self.setMenuWidget(top_bar)
    self.setCentralWidget(stacked_widget)

def GraphicalUserInterface(): app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_())

if name == "main": GraphicalUserInterface()

if name == "main": GraphicalUserInterface()

from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QStackedWidget, QWidget, QVBoxLayout, QPushButton, QLabel, QSizePolicy, QFrame, QHBoxLayout
from PyQt5.QtGui import QIcon, QMovie, QColor, QTextCharFormat, QFont, QPixmap, QTextBlockFormat,QPainter
from PyQt5.QtCore import Qt, QSize, QTimer
from dotenv import dotenv_values
import sys
import os

env_vars = dotenv_values(".env")
AssistantName = env_vars.get("AssistantName", "Assistant")
current_dir = os.getcwd()
old_chat_message = ""
TempDirPath = rf"{current_dir}\Frontend\Files"
GraphicsDirPath = rf"{current_dir}\Frontend\Graphics"

Function to modify answers

def AnswerModifier(Answer):
lines = Answer.split('\n')
non_empty_lines = [line for line in lines if line.strip()]
return '\n'.join(non_empty_lines)

Function to modify queries

def QueryModifier(Query):
new_query = Query.lower().strip()
query_words = new_query.split()
question_words = ["how", "what", "who", "where", "when", "why", "which", "whose", "whom", "can you", "what's", "where's", "how's"]

if any(word + " " in new_query for word in question_words):
    if query_words[-1][-1] in ['.', '?', '!']:
        new_query = new_query[:-1] + "?"
    else:
        new_query += "?"
else:
    if query_words[-1][-1] in ['.', '?', '!']:
        new_query = new_query[:-1] + "."
    else:
        new_query += "."

return new_query.capitalize()

def SetMicrophoneStatus(Command):
with open(rf'{TempDirPath}\Mic.data', "w", encoding='utf-8') as file:
file.write(Command)

def GetMicrophoneStatus():
with open(rf'{TempDirPath}\Mic.data', "r", encoding='utf-8') as file:
Status = file.read()
return Status

def SetAssistantStatus(Status):
with open(rf'{TempDirPath}\Status.data', "w", encoding='utf-8') as file:
file.write(Status)

def GetAssistantStatus():
with open(rf'{TempDirPath}\Status.data', "r", encoding='utf-8') as file:
Status = file.read()
return Status

def MicButtonInitialized():
SetMicrophoneStatus("False")

def MicButtonClosed():
SetMicrophoneStatus("True")

def GraphicsDirectoryPath(Filename):
path =rf'{GraphicsDirPath}{Filename}'
return path

def TempDirectoryPath(Filename):
Path = rf'{TempDirPath}{Filename}'
return Path

def ShowTextToScreen(Text):
with open(rf'{TempDirPath}\Responses.data', "w", encoding='utf-8') as file:
file.write(Text)

class ChatSection(QWidget):

def __init__(self):
    super(ChatSection, self).__init__()
    layout = QVBoxLayout(self)
    # layout.setContentsMargins(-10, 40, 40, 100)
    layout.setContentsMargins(0, 0, 150, 0)
    layout.setSpacing(-100)

    self.chat_text_edit = QTextEdit()
    self.chat_text_edit.setReadOnly(True)
    self.chat_text_edit.setTextInteractionFlags(Qt.NoTextInteraction)  # No text interaction
    self.chat_text_edit.setFrameStyle(QFrame.NoFrame)
    layout.addWidget(self.chat_text_edit)

    self.setStyleSheet("background-color: black;")
    layout.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
    layout.setStretch(1, 1)
    self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))

    text_color = QColor(Qt.blue)
    text_color_text = QTextCharFormat()
    text_color_text.setForeground(text_color)
    self.chat_text_edit.setCurrentCharFormat(text_color_text)

    self.gif_label = QLabel()
    self.gif_label.setStyleSheet("border: none;")
    
    movie = QMovie(GraphicsDirectoryPath("Jarvis.gif"))
    # print(GraphicsDirectoryPath("Jarvis.gif"))
    max_gif_size_W = 480
    max_gif_size_H = 270
    movie.setScaledSize(QSize(max_gif_size_W, max_gif_size_H))
    self.gif_label.setAlignment(Qt.AlignRight | Qt.AlignBottom)
    self.gif_label.setMovie(movie)
    movie.start()

    layout.addWidget(self.gif_label)
    
    self.label = QLabel("")
    self.label.setStyleSheet("color: white; font-size:16px; margin-right: 195px; border: none; margin-top: -30px;")
    self.label.setAlignment(Qt.AlignRight)
    layout.addWidget(self.label)
    layout.setSpacing(-10)
    layout.addWidget(self.gif_label)

    font = QFont()
    font.setPointSize(13)
    self.chat_text_edit.setFont(font)

    self.timer = QTimer(self)
    self.timer.timeout.connect(self.LoadMessages)
    self.timer.timeout.connect(self.SpeechRecogText)
    self.timer.start(5)

    self.chat_text_edit.viewport().installEventFilter(self)

    self.setStyleSheet("""
        QScrollBar:vertical {
            background: black;
            width: 10px;
            margin: 0px 0px 0px 0px;
        }

        QScrollBar::handle:vertical {
            background: white;
            min-height: 20px;
        }

        QScrollBar::add-line:vertical {
            background: black;
            subcontrol-position: bottom;
            subcontrol-origin: margin;
            height: 10px;
        }

        QScrollBar::sub-line:vertical {
            background: black;
            subcontrol-position: top;
            subcontrol-origin: margin;
            height: 10px;
        }

        QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {
            border: none;
            background: none;
            color: none;
        }

        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
    """)



def LoadMessages(self):
    global old_chat_message

    with open(TempDirectoryPath('Responses.data'), "r", encoding='utf-8') as file:
        messages = file.read()

        if messages is None:
            pass
        elif len(messages) < 1:
            pass
        elif str(old_chat_message) == str(messages):
            pass
        else:
            self.addMessage(message=messages, color='White')
            old_chat_message = messages



def SpeechRecogText(self):
    with open(TempDirectoryPath('Status.data'), "r", encoding='utf-8') as file:
        messages = file.read()
        self.label.setText(messages)

def load_icon(self, path, width=60, height=60):
    pixmap = QPixmap(path)
    new_pixmap = pixmap.scaled(width, height)
    self.icon_label.setPixmap(new_pixmap)

def toggle_icon(self, event=None):
    if self.toggled:
        self.load_icon(GraphicsDirectoryPath('voice.png'), 60, 60)
        MicButtonInitialized
    else:
        self.load_icon(GraphicsDirectoryPath('mic.png'), 60, 60)
        MicButtonClosed

    self.toggled = not self.toggled

def addMessage(self, message, color):
    cursor = self.chat_text_edit.textCursor()
    format = QTextCharFormat()
    formatm = QTextBlockFormat()
    formatm.setTopMargin(10)
    formatm.setBottomMargin(10)
    format.setForeground(QColor(color))
    cursor.setBlockFormat(formatm)
    cursor.setCharFormat(format)
    cursor.insertText(message + "\n")
    self.chat_text_edit.setTextCursor(cursor)

class InitialScreen(QWidget):
def init(self, parent=None):
super().init(parent)
desktop = QApplication.desktop()
screen_width = desktop.screenGeometry().width()
screen_height = desktop.screenGeometry().height()
content_layout = QVBoxLayout()
content_layout.setContentsMargins(0, 0, 0, 0)

    gif_label = QLabel()
    movie = QMovie(GraphicsDirectoryPath('Jarvis.gif'))
    gif_label.setMovie(movie)
    max_gif_size_H = int(screen_width / 16 * 9)
    movie.setScaledSize(QSize(screen_width, max_gif_size_H))
    gif_label.setAlignment(Qt.AlignCenter)
    movie.start()
    gif_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    self.icon_label = QLabel()
    pixmap = QPixmap(GraphicsDirectoryPath('Mic_on.png'))
    new_pixmap = pixmap.scaled(60, 60)
    self.icon_label.setPixmap(new_pixmap)
    self.icon_label.setFixedSize(150, 150)
    self.icon_label.setAlignment(Qt.AlignCenter)

    self.toggled = True
    self.toggle_icon()
    self.icon_label.mousePressEvent = self.toggle_icon

    self.label = QLabel("")
    self.label.setStyleSheet("color: white; font-size:16px ; margin-bottom:0;")
    
    content_layout.addWidget(gif_label, alignment=Qt.AlignCenter)
    content_layout.addWidget(self.label, alignment=Qt.AlignCenter)
    content_layout.addWidget(self.icon_label, alignment=Qt.AlignCenter)
    content_layout.setContentsMargins(0, 0, 150, 0)

    self.setLayout(content_layout)
    self.setFixedHeight(screen_height)
    self.setFixedWidth(screen_width)
    self.setStyleSheet("background-color: black;")

    self.timer = QTimer(self)
    self.timer.timeout.connect(self.SpeechRecogText)
    self.timer.start(5)

def SpeechRecogText(self):
    with open(TempDirectoryPath('Status.data'), "r", encoding='utf-8') as file:
        messages = file.read()
        self.label.setText(messages)

def load_icon(self, path, width=60, height=60):
    pixmap = QPixmap(path)
    new_pixmap = pixmap.scaled(width, height)
    self.icon_label.setPixmap(new_pixmap)

def toggle_icon(self, event=None):
    if self.toggled:
        self.load_icon(GraphicsDirectoryPath('Mic_on.png'), 60, 60)
        MicButtonInitialized
    else:
        self.load_icon(GraphicsDirectoryPath('Mic_off.png'), 60, 60)
        MicButtonClosed

    self.toggled = not self.toggled

class MessageScreen(QWidget):
def init(self, parent=None):
super().init(parent)
desktop = QApplication.desktop()
screen_width = desktop.screenGeometry().width()
screen_height = desktop.screenGeometry().height()
layout = QVBoxLayout()

    label = QLabel("")
    layout.addWidget(label)
    
    chat_section = ChatSection()
    layout.addWidget(chat_section)

    self.setLayout(layout)
    self.setStyleSheet("background-color: black;")
    self.setFixedHeight(screen_height)
    self.setFixedWidth(screen_width)

class CustomTopBar(QWidget):
def init(self, parent, stacked_widget):
super().init(parent)
self.initUI()
self.current_screen = None
self.stacked_widget = stacked_widget
self.draggable = False

def initUI(self):
    self.setFixedHeight(50)
    layout = QHBoxLayout(self)
    layout.setAlignment(Qt.AlignRight)

    home_button = QPushButton()
    home_icon = QIcon(GraphicsDirectoryPath("Home.png"))
    home_button.setIcon(home_icon)
    home_button.setText("  Home  ")
    home_button.setStyleSheet("height:40px; line-height:40px; background-color:white ; color: black")

    message_button = QPushButton()
    message_icon = QIcon(GraphicsDirectoryPath("Chats.png"))
    message_button.setIcon(message_icon)
    message_button.setText("  Chat  ")
    message_button.setStyleSheet("height:40px; line-height:40px; background-color:white ; color: black")

    minimize_button = QPushButton()
    minimize_icon = QIcon(GraphicsDirectoryPath("Minimize2.png"))
    minimize_button.setIcon(minimize_icon)
    minimize_button.setStyleSheet("background-color:white")
    minimize_button.clicked.connect(self.minimizeWindow)

    self.maximize_button = QPushButton()
    self.maximize_icon = QIcon(GraphicsDirectoryPath("Maximize.png"))
    self.restore_icon = QIcon(GraphicsDirectoryPath("Minimize.png"))
    self.maximize_button.setIcon(self.maximize_icon)
    self.maximize_button.setFlat(True)
    self.maximize_button.setStyleSheet("background-color:white")
    self.maximize_button.clicked.connect(self.maximizeWindow)

    close_button = QPushButton()
    close_icon = QIcon(GraphicsDirectoryPath("Close.png"))
    close_button.setIcon(close_icon)
    close_button.setStyleSheet("background-color:white")
    close_button.clicked.connect(self.closeWindow)

    line_frame = QFrame()
    line_frame.setFixedHeight(1)
    line_frame.setFrameShape(QFrame.HLine)
    line_frame.setFrameShadow(QFrame.Sunken)
    line_frame.setStyleSheet("border-color: black;")

    title_label = QLabel(f"{AssistantName}.capitalize() AI")
    title_label.setStyleSheet("color: black; font-size: 18px; background-color:white")

    home_button.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(0))
    message_button.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(1))

    layout.addWidget(title_label)
    layout.addStretch(1)
    layout.addWidget(home_button)
    layout.addWidget(message_button)
    layout.addWidget(minimize_button)
    layout.addWidget(self.maximize_button)
    layout.addWidget(close_button)
    layout.addWidget(line_frame)
    self.offset = None

def paintEvent(self, event):
    painter = QPainter(self)
    painter.fillRect(self.rect(), Qt.white)
    super().paintEvent(event)

def minimizeWindow(self):
    self.parent().showMinimized()

def maximizeWindow(self):
    
    if self.parent().isMaximized():
        self.parent().showNormal()
        self.maximize_button.setIcon(self.maximize_icon)
    else:
        self.parent().showMaximized()
        self.maximize_button.setIcon(self.restore_icon)

def closeWindow(self):
    self.parent().close()

def mousePressEvent(self, event):
    if self.draggable:
        self.offset = event.globalPos() - self.pos()

def mouseMoveEvent(self, event):
    if self.offset is not None:
        new_pos = event.globalPos() - self.offset
        self.parent().move(new_pos)

def showMessageScreen(self):
    if self.current_screen is not None:
        self.current_screen.hide()

    message_screen = MessageScreen(self)
    layout = self.layout()
    
    if layout is not None:
        layout.addWidget(message_screen)
        
    self.current_screen = message_screen

def showInitialScreen(self):
    if self.current_screen is not None:
        self.current_screen.hide()

    initial_screen = InitialScreen(self)
    layout = self.parent().layout()
    
    if layout is not None:
        layout.addWidget(initial_screen)
        
    self.current_screen = initial_screen

class MainWindow(QMainWindow):
def init(self):
super().init()
self.setWindowFlags(Qt.FramelessWindowHint)
self.initUI()

def initUI(self):
    desktop = QApplication.desktop()
    screen_width = desktop.screenGeometry().width()
    screen_height = desktop.screenGeometry().height()

    stacked_widget = QStackedWidget(self)
    initial_screen = InitialScreen()
    message_screen = MessageScreen()
    
    stacked_widget.addWidget(initial_screen)
    stacked_widget.addWidget(message_screen)

    self.setGeometry(0, 0, screen_width, screen_height)
    self.setStyleSheet("background-color: black;")
    
    top_bar = CustomTopBar(self, stacked_widget)
    self.setMenuWidget(top_bar)
    self.setCentralWidget(stacked_widget)

def GraphicalUserInterface():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

if name == "main":
GraphicalUserInterface()

@aniway89
Copy link

aniway89 commented Feb 9, 2025

Hey bro the code you write is right or is it giving some error.
And if you can provide the assets it will also help me a lot
Here is my grail >>> [email protected]

And I will also give the main.py in few days so don't worry.

@nuxo-bie
Copy link

nuxo-bie commented Feb 9, 2025 via email

@aniway89
Copy link

i got all the images let i share you the link

https://drive.google.com/drive/folders/1Dgo4m0hKnWCvig8fJbSDjKejAVYJUDcB?usp=sharing
this is the google drive link

@aniway89
Copy link

hey if any one want the gui.py or the full jarvis code just go to youtube and take the full code

@aniway89
Copy link

someone please help my image generation code is nto giveing me the imagess it give only unsupported file error
here is the code

==========\
==imggen.py==||
==========//

          import asyncio
          from random import randint
          from PIL import Image
          import requests
          from dotenv import get_key
          import os
          from time import sleep 
          
        def open_images(prompt):
            folder_path = "Data"  # Folder where the images are stored
            prompt = prompt.replace(" ", "_")  # Replace spaces in prompt with underscores
        
            # Generate the filenames for the images
            files = [f"{prompt}{i}.jpg" for i in range(1, 5)]
        
            for jpg_file in files:
                image_path = os.path.join(folder_path, jpg_file)
        
                try:
                    # Try to open and display the image
                    img = Image.open(image_path)
                    print(f"Opening image: {image_path}")
                    img.show()
                    sleep(1)  # Pause for 1 second before showing the next image
        
                except IOError:
                    print(f"Unable to open {image_path}")
        
        API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
        headers = {"Authorization": f"Bearer {get_key('.env', 'HuggingFaceAPIKey')}"}
        
        # Async function to send a query to the Hugging Face API
        async def query(payload):
            response = await asyncio.to_thread(requests.post, API_URL, headers=headers, json=payload)
            return response.content
        
        # Async function to generate images based on the given prompt
        async def generate_images(prompt: str):
            tasks = []
        
            # Create 4 image generation tasks
            for _ in range(4):
                payload = {
                    "inputs": [prompt],
                    "quality": "4K",
                    "sharpness": "maximum",
                    "Ultra High details": "high resolution",
                    "seed": randint(0, 1000000)
                }
                task = asyncio.create_task(query(payload))
                tasks.append(task)
        
            # Wait for all tasks to complete
            image_bytes_list = await asyncio.gather(*tasks)
        
            # Save the generated images to files
            for i, image_bytes in enumerate(image_bytes_list):
                with open( fr"Data\{prompt.replace(' ','_')}{i + 1}.jpg", "wb" ) as f:
                    f.write(image_bytes)
        
        def GenerateImages(prompt: str):
            asyncio.run(generate_images(prompt))  # Run the async image generation
            open_images(prompt)  # Open the generated images
        
        # Main loop to monitor for image generation requests
        while True:
            try:
                # Read the status and prompt from the data file
                with open(r"Frontend/Files/ImageGeneration.data", "r") as f:
                    Data: str = f.read()
        
                Prompt, Status = Data.split(",")
        
                # If the status indicates an image generation request
                if Status.strip() == "True":
                    print("Generating Images ....")
                    ImageStatus = GenerateImages(prompt=Prompt)
        
        
                    with open(r"Frontend\Files\ImageGeneration.data", "w") as f:
                        f.write("False,False")
                        break
        
                else:
                    sleep(1)  # Wait for 1 second before checking again
        
            except:
                pass

@axinyyyx
Copy link

axinyyyx commented Feb 11, 2025

DM whoever wants the full Jarvis code I.g id:- axinyyyx
@aniway89 @klsatapathy @kartick-code @nuxo-bie @abidora999

@Niloy441
Copy link

আপনার কোড ঠিক করে দেওয়া হয়েচে

import asyncio
from random import randint
from PIL import Image
import requests
import io
import os
from time import sleep
from dotenv import get_key

✅ Data ফোল্ডার যদি না থাকে, তাহলে তৈরি করো

os.makedirs("Data", exist_ok=True)

✅ Hugging Face API সেটআপ

API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
headers = {"Authorization": f"Bearer {get_key('.env', 'HuggingFaceAPIKey')}"}

✅ API-তে রিকুয়েস্ট পাঠিয়ে রেসপন্স যাচাই করা

async def query(payload):
response = await asyncio.to_thread(requests.post, API_URL, headers=headers, json=payload)

if response.status_code != 200:
    print(f"❌ API Error: {response.status_code}, Message: {response.text}")
    return None  # ব্যর্থ হলে কিছু ফেরত দেবে না

return response.content

✅ ইমেজ জেনারেট করার ফাংশন

async def generate_images(prompt: str):
tasks = []

for _ in range(4):  # ৪টি ইমেজ জেনারেট করবো
    payload = {
        "inputs": prompt,  # 🔹 লিস্ট না দিয়ে সরাসরি স্ট্রিং পাঠাচ্ছি
        "quality": "4K",
        "sharpness": "maximum",
        "Ultra High details": "high resolution",
        "seed": randint(0, 1000000)
    }
    task = asyncio.create_task(query(payload))
    tasks.append(task)

image_bytes_list = await asyncio.gather(*tasks)

for i, image_bytes in enumerate(image_bytes_list):
    if image_bytes is None:
        print(f"⚠️ Skipping Image {i + 1} due to API error")
        continue

    try:
        # ✅ ইমেজ ভ্যালিড কিনা চেক করা
        image = Image.open(io.BytesIO(image_bytes))
        image_path = fr"Data\{prompt.replace(' ', '_')}{i + 1}.jpg"
        image.save(image_path)
        print(f"✅ Image {i + 1} saved: {image_path}")
    except Exception as e:
        print(f"❌ Error while saving image {i + 1}: {e}")

✅ সেভ হওয়া ইমেজ ওপেন করার ফাংশন

def open_images(prompt):
folder_path = "Data"
prompt = prompt.replace(" ", "_") # স্পেস বাদ দিয়ে ফাইলনেম তৈরি করা

files = [f"{prompt}{i}.jpg" for i in range(1, 5)]

for jpg_file in files:
    image_path = os.path.join(folder_path, jpg_file)

    try:
        img = Image.open(image_path)
        print(f"📂 Opening image: {image_path}")
        img.show()
        sleep(1)  # ১ সেকেন্ড বিরতি দিয়ে দেখাবে
    except IOError:
        print(f"❌ Unable to open {image_path}")

✅ মেইন ফাংশন

def GenerateImages(prompt: str):
asyncio.run(generate_images(prompt)) # ইমেজ জেনারেট করা
open_images(prompt) # ইমেজ ওপেন করা

✅ ফাইল থেকে স্ট্যাটাস চেক করে ইমেজ জেনারেট করা

while True:
try:
with open(r"Frontend/Files/ImageGeneration.data", "r") as f:
Data: str = f.read()

    Prompt, Status = Data.split(",")

    if Status.strip() == "True":
        print("🚀 Generating Images ....")
        GenerateImages(prompt=Prompt)

        with open(r"Frontend\Files\ImageGeneration.data", "w") as f:
            f.write("False,False")
            break
    else:
        sleep(1)

except Exception as e:
    print(f"⚠️ Error: {e}")
    sleep(1)

@abidora999
Copy link

abidora999 commented Feb 13, 2025 via email

@aniway89
Copy link

aniway89 commented Feb 13, 2025

ok guys i made it every code is ok with out any problem
tell me which code file you want i will paste it here

btw and dont forget to install all the imp packeges use in this code
====================
====imagegeneration.py====|
====================/

import asyncio
from random import randint
from PIL import Image
import requests
from dotenv import get_key
import os
from time import sleep



def open_images(prompt):
    folder_path = r"Data"  # Folder where the images are stored
    prompt = prompt.replace(" ", "_")  # Replace spaces in prompt with underscores

    # Generate the filenames for the images
    Files = [f"{prompt}{i}.jpg" for i in range(1, 5)]

    for jpg_file in Files:
        image_path = os.path.join(folder_path, jpg_file)

        try:
            # Try to open and display the image
            img = Image.open(image_path)
            print(f"Opening image: {image_path}")
            img.show()
            sleep(5)  # Pause for 1 second before showing the next image

        except IOError:
            print(f"Unable to open {image_path}")



API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
headers = {"Authorization": f"Bearer {get_key('.env', 'HuggingFaceAPIKey')}"}

# Async function to send a query to the Hugging Face API
async def query(payload):
    response = await asyncio.to_thread(requests.post, API_URL, headers=headers, json=payload)
    return response.content

# Async function to generate images based on the given prompt
async def generate_images(prompt: str):
    tasks = []

    # Create 4 image generation tasks
    for _ in range(4):
        payload = {
            "inputs": f"{prompt}, quality=4K, sharpness=maximum, Ultra High details, high resolution, seed = {randint(0, 1000000)}",
        }
        task = asyncio.create_task(query(payload))
        tasks.append(task)

    # Wait for all tasks to complete
    image_bytes_list = await asyncio.gather(*tasks)

    # Save the generated images to files
    for i, image_bytes in enumerate(image_bytes_list):
        with open(fr"Data\{prompt.replace(' ', '_')}{i + 1}.jpg", "wb") as f:
            f.write(image_bytes)

# Wrapper function to generate and open images
def GenerateImages(prompt: str):
    asyncio.run(generate_images(prompt))  # Run the async image generation
    open_images(prompt)  # Open the generated images

# Main loop to monitor for image generation requests
while True:

    try:
        # Read the status and prompt from the data file
        with open(r"Frontend\Files\ImageGeneration.data", "r") as f:
            Data: str = f.read()

        Prompt, Status = Data.split(",")

        # If the status indicates an image generation request
        if Status == "True":
            print("Generating Images...")
            ImageStatus = GenerateImages(prompt=Prompt)

            # Reset the status in the file after generating images
            with open(r"Frontend\Files\ImageGeneration.data", "w") as f:
              f.write("False,False")
            break  # Exit the loop after processing the request

        else:
                sleep(1)  # Wait for 1 second before checking again

    except :
        pass

@Pavitroo
Copy link

hey if any one want the gui.py or the full jarvis code just go to youtube and take the full code
bro can you help me where i can get all files source code as i completed writing model.py,chatbot.py,realtimesearchengine.py,texttospeech.py,speechtotext.py but i want code of automation.py and main.py and gui.py! Can you kindly Help me and give them in the chat? Please Help me

@Pavitroo
Copy link

hey if any one want the gui.py or the full jarvis code just go to youtube and take the full code
bro can you help me where i can get all files source code as i completed writing model.py,chatbot.py,realtimesearchengine.py,texttospeech.py,speechtotext.py but i want code of automation.py and main.py and gui.py! Can you kindly Help me and give them in the chat? Please Help me

@Thechallangers
Copy link

hey everyone i wrote the Gui.py code from his video but i got error please look at this code written below and the error i got is

====>ERROR<===== QPixmap::scaled: Pixmap is a null pixmap Traceback (most recent call last): File "d:\Uka\A-ver1\Frontend\GUI.py", line 454, in GraphicalUserInterface() ~~~~~~~~~~~~~~~~~~~~~~^^ File "d:\Uka\A-ver1\Frontend\GUI.py", line 449, in GraphicalUserInterface window = MainWindow() File "d:\Uka\A-ver1\Frontend\GUI.py", line 426, in init self.initUI() ~~~~~~~~~~~^^ File "d:\Uka\A-ver1\Frontend\GUI.py", line 434, in initUI initial_screen = InitialScreen() File "d:\Uka\A-ver1\Frontend\GUI.py", line 247, in init self.toggle_icon() ^^^^^^^^^^^^^^^^ AttributeError: 'InitialScreen' object has no attribute 'toggle_icon'

====================\ =====>GUI.PY code<======| ====================/

from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit,QStackedWidget, QWidget, QLineEdit,QGridLayout,QVBoxLayout,QHBoxLayout,QPushButton,QFrame,QLabel,QSizePolicy from PyQt5.QtGui import QIcon, QPainter,QMovie,QColor,QTextCharFormat,QFont,QPixmap,QTextBlockFormat from PyQt5.QtCore import Qt , QSize,QTimer from dotenv import dotenv_values import sys import os

env_vars = dotenv_values(".env") AssistantName = env_vars.get("AssistantName") current_dir = os.getcwd() old_chat_messages = "" TempDirPath = rf"{current_dir}/Frontend/Files" GraphicsDirPath = rf"{current_dir}/Frontend/Graphics"

def AnswerModifier(Answer): lines = Answer.split('\n') non_empty_lines = [line for line in lines if line.strip()] modified_answer = '\n'.join(non_empty_lines) return modified_answer

def QueryModifier(Query): new_query = Query.lower().strip() query_words = new_query.split() question_words = ["how", "what", "who", "where", "when", "why", "which", "whose", "whom", "can you", "what's", "where's", "how's"]

if any(word + " " in new_query for word in question_words):
    if query_words[-1][-1] in ['.', '?', '!']:
        new_query = new_query[:-1] + "?"
    else:
        new_query += "?"
else:
    if query_words[-1][-1] in ['.', '?', '!']:
        new_query = new_query[:-1] + "."
    else:
        new_query += "."

return new_query.capitalize()

def SetMicrophoneStatus(Command): with open(rf'{TempDirPath}\Mic.data', "w", encoding='utf-8') as file: file.write(Command)

def GetMicrophoneStatus(): with open(rf'{TempDirPath}\Mic.data', "r", encoding='utf-8') as file: Status = file.read() return Status

def SetAssistantStatus(Status): with open(rf'{TempDirPath}\Status.data', "w", encoding='utf-8') as file: file.write(Status)

def GetAssistantStatus(): with open(rf'{TempDirPath}\Status.data', "r", encoding='utf-8') as file: Status = file.read() return Status

def MicButtonInitialized(): SetMicrophoneStatus("False") def MicButtonClosed(): SetMicrophoneStatus("True")

def GraphicsDirectoryPath(Filename): path =rf'{GraphicsDirPath}{Filename}' return path

def TempDirectoryPath(Filename): Path = rf'{TempDirPath}{Filename}' return Path

def ShowTextToScreen(Text): with open(rf'{TempDirPath}\Responses.data', "w", encoding='utf-8') as file: file.write(Text)

class ChatSection(QWidget):

def __init__(self):
    super().__init__()
    layout = QVBoxLayout(self)
    layout.setContentsMargins(-10, 40, 40, 100)
    layout.setSpacing(-100)

    self.chat_text_edit = QTextEdit()
    self.chat_text_edit.setReadOnly(True)
    self.chat_text_edit.setTextInteractionFlags(Qt.NoTextInteraction)  # No text interaction
    self.chat_text_edit.setFrameStyle(QFrame.NoFrame)
    layout.addWidget(self.chat_text_edit)

    self.setStyleSheet("background-color: black;")
    layout.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
    layout.setStretch(1, 1)
    self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))

    text_color = QColor(Qt.blue)
    text_color_text = QTextCharFormat()
    text_color_text.setForeground(text_color)
    self.chat_text_edit.setCurrentCharFormat(text_color_text)

    self.gif_label = QLabel()
    self.gif_label.setStyleSheet("border: none;")
    
    movie = QMovie(GraphicsDirectoryPath("Jarvis.gif"))
    max_gif_size_W = 480
    max_gif_size_H = 270
    movie.setScaledSize(QSize(max_gif_size_W, max_gif_size_H))
    self.gif_label.setAlignment(Qt.AlignRight | Qt.AlignBottom)
    self.gif_label.setMovie(movie)
    movie.start()

    layout.addWidget(self.gif_label)
    
    self.label = QLabel("")
    self.label.setStyleSheet("color: white; font-size:16px; margin-right: 195px; border: none; margin-top: -30px;")
    self.label.setAlignment(Qt.AlignRight)
    layout.addWidget(self.label)
    layout.setSpacing(-10)
    layout.addWidget(self.gif_label)

    font = QFont()
    font.setPointSize(13)
    self.chat_text_edit.setFont(font)

    self.timer = QTimer(self)
    self.timer.timeout.connect(self.LoadMessages)
    self.timer.timeout.connect(self.SpeechRecogText)
    self.timer.start(5)

    self.chat_text_edit.viewport().installEventFilter(self)

    self.setStyleSheet("""
        QScrollBar:vertical {
            background: black;
            width: 10px;
            margin: 0px 0px 0px 0px;
        }

        QScrollBar::handle:vertical {
            background: white;
            min-height: 20px;
        }

        QScrollBar::add-line:vertical {
            background: black;
            subcontrol-position: bottom;
            subcontrol-origin: margin;
            height: 10px;
        }

        QScrollBar::sub-line:vertical {
            background: black;
            subcontrol-position: top;
            subcontrol-origin: margin;
            height: 10px;
        }

        QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {
            border: none;
            background: none;
            color: none;
        }

        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
    """)



def loadMessages(self):
    global old_chat_message

    with open(TempDirectoryPath('Responses.data'), "r", encoding='utf-8') as file:
        messages = file.read()

        if messages is None:
            pass
        elif len(messages) < 1:
            pass
        elif str(old_chat_message) == str(messages):
            pass
        else:
            self.addMessage(message=messages, color='White')
            old_chat_message = messages



def SpeechRecogText(self):
    with open(TempDirectoryPath('Status.data'), "r", encoding='utf-8') as file:
        messages = file.read()
        self.label.setText(messages)

def load_icon(self, path, width=60, height=60):
    pixmap = QPixmap(path)
    new_pixmap = pixmap.scaled(width, height)
    self.icon_label.setPixmap(new_pixmap)

def toggle_icon(self, event=None):
    if self.toggled:
        self.load_icon(GraphicsDirectoryPath('voice.png'), 60, 60)
        MicButtonInitialized
    else:
        self.load_icon(GraphicsDirectoryPath('mic.png'), 60, 60)
        MicButtonClosed

    self.toggled = not self.toggled

def addMessage(self, message, color):
    cursor = self.chat_text_edit.textCursor()
    format = QTextCharFormat()
    formatm = QTextBlockFormat()
    formatm.setTopMargin(10)
    formatm.setBottomMargin(10)
    format.setForeground(QColor(color))
    cursor.setBlockFormat(formatm)
    cursor.setCharFormat(format)
    cursor.insertText(message + "\n")
    self.chat_text_edit.setTextCursor(cursor)

class InitialScreen(QWidget): def init(self, parent=None): super().init(parent) desktop = QApplication.desktop() screen_width = desktop.screenGeometry().width() screen_height = desktop.screenGeometry().height() content_layout = QVBoxLayout() content_layout.setContentsMargins(0, 0, 0, 0)

    gif_label = QLabel()
    movie = QMovie(GraphicsDirectoryPath('Jarvis.gif'))
    gif_label.setMovie(movie)
    max_gif_size_H = int(screen_width / 16 * 9)
    movie.setScaledSize(QSize(screen_width, max_gif_size_H))
    gif_label.setAlignment(Qt.AlignCenter)
    movie.start()
    gif_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    self.icon_label = QLabel()
    pixmap = QPixmap(GraphicsDirectoryPath('Mic_on.png'))
    new_pixmap = pixmap.scaled(60, 60)
    self.icon_label.setPixmap(new_pixmap)
    self.icon_label.setFixedSize(150, 150)
    self.icon_label.setAlignment(Qt.AlignCenter)

    self.toggled = True
    self.toggle_icon()
    self.icon_label.mousePressEvent = self.toggle_icon

    self.label = QLabel("")
    self.label.setStyleSheet("color: white; font-size:16px ; margin-bottom:0;")
    
    content_layout.addWidget(gif_label, alignment=Qt.AlignCenter)
    content_layout.addWidget(self.label, alignment=Qt.AlignCenter)
    content_layout.addWidget(self.icon_label, alignment=Qt.AlignCenter)
    content_layout.setContentsMargins(0, 0, 150)

    self.setLayout(content_layout)
    self.setFixedHeight(screen_height)
    self.setFixedWidth(screen_width)
    self.setStyleSheet("background-color: black;")

    self.timer = QTimer(self)
    self.timer.timeout.connect(self.SpeechRecogText)
    self.timer.start(5)

def SpeechRecogText(self): with open(TempDirectoryPath('Status.data'), "r", encoding='utf-8') as file: messages = file.read() self.label.setText(messages)

def load_icon(self, path, width=60, height=60): pixmap = QPixmap(path) new_pixmap = pixmap.scaled(width, height) self.icon_label.setPixmap(new_pixmap)

def toggle_icon(self, event=None): if self.toggled: self.load_icon(GraphicsDirectoryPath('Mic_on.png'), 60, 60) MicButtonInitialized else: self.load_icon(GraphicsDirectoryPath('Mic_off.png'), 60, 60) MicButtonClosed

self.toggled = not self.toggled

class MessageScreen(QWidget): def init(self, parent=None): super().init(parent) desktop = QApplication.desktop() screen_width = desktop.screenGeometry().width() screen_height = desktop.screenGeometry().height() layout = QVBoxLayout()

    label = QLabel("")
    layout.addWidget(label)
    
    chat_section = ChatSection()
    layout.addWidget(chat_section)

    self.setLayout(layout)
    self.setStyleSheet("background-color: black;")
    self.setFixedHeight(screen_height)
    self.setFixedWidth(screen_width)

class CustomTopBar(QWidget): def init(self, parent, stacked_widget): super().init(parent) self.current_screen = None self.stacked_widget = stacked_widget def init(self): self.setFixedHeight(50) layout = QHBoxLayout(self) layout.setAlignment(Qt.AlignRight)

    home_button = QPushButton()
    home_icon = QIcon(GraphicsDirectoryPath("Home.png"))
    home_button.setIcon(home_icon)
    home_button.setText("  Home  ")
    home_button.setStyleSheet("height:40px; line-height:40px; background-color:white ; color: black")

    message_button = QPushButton()
    message_icon = QIcon(GraphicsDirectoryPath("Chats.png"))
    message_button.setIcon(message_icon)
    message_button.setText("  Chat  ")
    message_button.setStyleSheet("height:40px; line-height:40px; background-color:white ; color: black")

    minimize_button = QPushButton()
    minimize_icon = QIcon(GraphicsDirectoryPath("Minimize2.png"))
    minimize_button.setIcon(minimize_icon)
    minimize_button.setStyleSheet("background-color:white")
    minimize_button.clicked.connect(self.minimizeWindow)

    self.maximize_button = QPushButton()
    self.maximize_icon = QIcon(GraphicsDirectoryPath("Maximize.png"))
    self.restore_icon = QIcon(GraphicsDirectoryPath("Minimize.png"))
    self.maximize_button.setIcon(self.maximize_icon)
    self.maximize_button.setFlat(True)
    self.maximize_button.setStyleSheet("background-color:white")
    self.maximize_button.clicked.connect(self.maximizeWindow)

    close_button = QPushButton()
    close_icon = QIcon(GraphicsDirectoryPath("Close.png"))
    close_button.setIcon(close_icon)
    close_button.setStyleSheet("background-color:white")
    close_button.clicked.connect(self.closeWindow)

    line_frame = QFrame()
    line_frame.setFixedHeight(1)
    line_frame.setFrameShape(QFrame.HLine)
    line_frame.setFrameShadow(QFrame.Sunken)
    line_frame.setStyleSheet("border-color: black;")

    title_label = QLabel(f"{AssistantName}.capitalize() AI")
    title_label.setStyleSheet("color: black; font-size: 18px; background-color:white")

    home_button.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(0))
    message_button.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(1))

    layout.addWidget(title_label)
    layout.addStretch(1)
    layout.addWidget(home_button)
    layout.addWidget(message_button)
    layout.addWidget(minimize_button)
    layout.addWidget(self.maximize_button)
    layout.addWidget(close_button)
    layout.addWidget(line_frame)
    self.offset = None

def paintEvent(self, event):
    painter = QPainter(self)
    painter.fillRect(self.rect(), Qt.white)
    super().paintEvent(event)

def minimizeWindow(self):
    self.parent().showMinimized()

def maximizeWindow(self):
    
    if self.parent().isMaximized():
        self.parent().showNormal()
        self.maximize_button.setIcon(self.maximize_icon)
    else:
        self.parent().showMaximized()
        self.maximize_button.setIcon(self.restore_icon)

def closeWindow(self):
    self.parent().close()

def mousePressEvent(self, event):
    if self.draggable:
        self.offset = event.globalPos() - self.pos()

def mouseMoveEvent(self, event):
    if self.offset is not None:
        new_pos = event.globalPos() - self.offset
        self.parent().move(new_pos)

def showMessageScreen(self):
    if self.current_screen is not None:
        self.current_screen.hide()

    message_screen = MessageScreen(self)
    layout = self.layout()
    
    if layout is not None:
        layout.addWidget(message_screen)
        
    self.current_screen = message_screen

def showInitialScreen(self):
    if self.current_screen is not None:
        self.current_screen.hide()

    initial_screen = InitialScreen(self)
    layout = self.parent().layout()
    
    if layout is not None:
        layout.addWidget(initial_screen)
        
    self.current_screen = initial_screen

class MainWindow(QMainWindow): def init(self): super().init() self.setWindowFlags(Qt.FramelessWindowHint) self.initUI()

def initUI(self):
    desktop = QApplication.desktop()
    screen_width = desktop.screenGeometry().width()
    screen_height = desktop.screenGeometry().height()

    stacked_widget = QStackedWidget(self)
    initial_screen = InitialScreen()
    message_screen = MessageScreen()
    
    stacked_widget.addWidget(initial_screen)
    stacked_widget.addWidget(message_screen)

    self.setGeometry(0, 0, screen_width, screen_height)
    self.setStyleSheet("background-color: black;")
    
    top_bar = CustomTopBar(self, stacked_widget)
    self.setMenuWidget(top_bar)
    self.setCentralWidget(stacked_widget)

def GraphicalUserInterface(): app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_())

if name == "main": GraphicalUserInterface()

if name == "main": GraphicalUserInterface()

@Thechallangers
Copy link

try using pyqt6 instead of pyqt5 i had the same error then i used pyqt6 and it worked for me

@uttammahto
Copy link

@klsatapathy @aniway89 hello i want a full source code of jarvis can anyone give me

@Abhay7760
Copy link

bhaiya apne itna accha project kiya but hume source code nahi diya aisa kyu..??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment