master 42c1bb587771 cached
15 files
38.8 KB
9.0k tokens
58 symbols
1 requests
Download .txt
Repository: tomzhu0225/oral_practice_with_openai
Branch: master
Commit: 42c1bb587771
Files: 15
Total size: 38.8 KB

Directory structure:
gitextract_izn_nl_w/

├── .gitignore
├── LICENSE
├── README.md
├── TODO
└── src/
    ├── main.py
    ├── model/
    │   ├── chatsession.py
    │   ├── core.py
    │   └── settings.py
    ├── test.py
    ├── utils.py
    └── view/
        ├── components.py
        ├── controller.py
        ├── dialogues.py
        ├── mainwindow.py
        └── qt_style_sheet.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
settings.json
*__pycache__*


================================================
FILE: LICENSE
================================================
Mozilla Public License Version 2.0
==================================

1. Definitions
--------------

1.1. "Contributor"
    means each individual or legal entity that creates, contributes to
    the creation of, or owns Covered Software.

1.2. "Contributor Version"
    means the combination of the Contributions of others (if any) used
    by a Contributor and that particular Contributor's Contribution.

1.3. "Contribution"
    means Covered Software of a particular Contributor.

1.4. "Covered Software"
    means Source Code Form to which the initial Contributor has attached
    the notice in Exhibit A, the Executable Form of such Source Code
    Form, and Modifications of such Source Code Form, in each case
    including portions thereof.

1.5. "Incompatible With Secondary Licenses"
    means

    (a) that the initial Contributor has attached the notice described
        in Exhibit B to the Covered Software; or

    (b) that the Covered Software was made available under the terms of
        version 1.1 or earlier of the License, but not also under the
        terms of a Secondary License.

1.6. "Executable Form"
    means any form of the work other than Source Code Form.

1.7. "Larger Work"
    means a work that combines Covered Software with other material, in
    a separate file or files, that is not Covered Software.

1.8. "License"
    means this document.

1.9. "Licensable"
    means having the right to grant, to the maximum extent possible,
    whether at the time of the initial grant or subsequently, any and
    all of the rights conveyed by this License.

1.10. "Modifications"
    means any of the following:

    (a) any file in Source Code Form that results from an addition to,
        deletion from, or modification of the contents of Covered
        Software; or

    (b) any new file in Source Code Form that contains any Covered
        Software.

1.11. "Patent Claims" of a Contributor
    means any patent claim(s), including without limitation, method,
    process, and apparatus claims, in any patent Licensable by such
    Contributor that would be infringed, but for the grant of the
    License, by the making, using, selling, offering for sale, having
    made, import, or transfer of either its Contributions or its
    Contributor Version.

1.12. "Secondary License"
    means either the GNU General Public License, Version 2.0, the GNU
    Lesser General Public License, Version 2.1, the GNU Affero General
    Public License, Version 3.0, or any later versions of those
    licenses.

1.13. "Source Code Form"
    means the form of the work preferred for making modifications.

1.14. "You" (or "Your")
    means an individual or a legal entity exercising rights under this
    License. For legal entities, "You" includes any entity that
    controls, is controlled by, or is under common control with You. For
    purposes of this definition, "control" means (a) the power, direct
    or indirect, to cause the direction or management of such entity,
    whether by contract or otherwise, or (b) ownership of more than
    fifty percent (50%) of the outstanding shares or beneficial
    ownership of such entity.

2. License Grants and Conditions
--------------------------------

2.1. Grants

Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:

(a) under intellectual property rights (other than patent or trademark)
    Licensable by such Contributor to use, reproduce, make available,
    modify, display, perform, distribute, and otherwise exploit its
    Contributions, either on an unmodified basis, with Modifications, or
    as part of a Larger Work; and

(b) under Patent Claims of such Contributor to make, use, sell, offer
    for sale, have made, import, and otherwise transfer either its
    Contributions or its Contributor Version.

2.2. Effective Date

The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.

2.3. Limitations on Grant Scope

The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:

(a) for any code that a Contributor has removed from Covered Software;
    or

(b) for infringements caused by: (i) Your and any other third party's
    modifications of Covered Software, or (ii) the combination of its
    Contributions with other software (except as part of its Contributor
    Version); or

(c) under Patent Claims infringed by Covered Software in the absence of
    its Contributions.

This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).

2.4. Subsequent Licenses

No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).

2.5. Representation

Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.

2.6. Fair Use

This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.

2.7. Conditions

Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.

3. Responsibilities
-------------------

3.1. Distribution of Source Form

All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.

3.2. Distribution of Executable Form

If You distribute Covered Software in Executable Form then:

(a) such Covered Software must also be made available in Source Code
    Form, as described in Section 3.1, and You must inform recipients of
    the Executable Form how they can obtain a copy of such Source Code
    Form by reasonable means in a timely manner, at a charge no more
    than the cost of distribution to the recipient; and

(b) You may distribute such Executable Form under the terms of this
    License, or sublicense it under different terms, provided that the
    license for the Executable Form does not attempt to limit or alter
    the recipients' rights in the Source Code Form under this License.

3.3. Distribution of a Larger Work

You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).

3.4. Notices

You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.

3.5. Application of Additional Terms

You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.

4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------

If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.

5. Termination
--------------

5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.

5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.

5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.

************************************************************************
*                                                                      *
*  6. Disclaimer of Warranty                                           *
*  -------------------------                                           *
*                                                                      *
*  Covered Software is provided under this License on an "as is"       *
*  basis, without warranty of any kind, either expressed, implied, or  *
*  statutory, including, without limitation, warranties that the       *
*  Covered Software is free of defects, merchantable, fit for a        *
*  particular purpose or non-infringing. The entire risk as to the     *
*  quality and performance of the Covered Software is with You.        *
*  Should any Covered Software prove defective in any respect, You     *
*  (not any Contributor) assume the cost of any necessary servicing,   *
*  repair, or correction. This disclaimer of warranty constitutes an   *
*  essential part of this License. No use of any Covered Software is   *
*  authorized under this License except under this disclaimer.         *
*                                                                      *
************************************************************************

************************************************************************
*                                                                      *
*  7. Limitation of Liability                                          *
*  --------------------------                                          *
*                                                                      *
*  Under no circumstances and under no legal theory, whether tort      *
*  (including negligence), contract, or otherwise, shall any           *
*  Contributor, or anyone who distributes Covered Software as          *
*  permitted above, be liable to You for any direct, indirect,         *
*  special, incidental, or consequential damages of any character      *
*  including, without limitation, damages for lost profits, loss of    *
*  goodwill, work stoppage, computer failure or malfunction, or any    *
*  and all other commercial damages or losses, even if such party      *
*  shall have been informed of the possibility of such damages. This   *
*  limitation of liability shall not apply to liability for death or   *
*  personal injury resulting from such party's negligence to the       *
*  extent applicable law prohibits such limitation. Some               *
*  jurisdictions do not allow the exclusion or limitation of           *
*  incidental or consequential damages, so this exclusion and          *
*  limitation may not apply to You.                                    *
*                                                                      *
************************************************************************

8. Litigation
-------------

Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.

9. Miscellaneous
----------------

This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.

10. Versions of the License
---------------------------

10.1. New Versions

Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.

10.2. Effect of New Versions

You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.

10.3. Modified Versions

If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).

10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses

If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.

Exhibit A - Source Code Form License Notice
-------------------------------------------

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.

If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.

You may add additional accurate notices of copyright ownership.

Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------

  This Source Code Form is "Incompatible With Secondary Licenses", as
  defined by the Mozilla Public License, v. 2.0.


================================================
FILE: README.md
================================================
# Introduction

[A video introduction in Chinese](https://www.bilibili.com/video/BV1Xs4y1p7t8/)

# Dependency

This application is based on [OpenAI APIs](https://openai.com/api/) and [Microsoft Azure Cognitive Services](https://azure.microsoft.com/en-us/products/cognitive-services/#overview).

API keys from both platforms are needed.

Additional needed python packages are: [OpenAI Python Library](https://github.com/openai/openai-python), [azure-cognitiveservices-speech](https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/), [PyQt5](https://www.riverbankcomputing.com/software/pyqt/)

```
pip install openai azure-cognitiveservices-speech PyQt5
```

# Usage

## Get API keys from OpenAI

1. Log in to [OpenAI](https://openai.com/api/).
2. In the overview page, click the upper right icon, and then click "View API keys".
3. In the API keys page, click "+ Create new secret key", which will generate the secret key. Be sure to save it because it cannot be seen a second time.

## Get API keys from Microsoft Microsoft Azure Cognitive Services

1. Log in to [Microsoft Azure](https://azure.microsoft.com/en-us/free/students/).
2. In the search banner, search "Speech Service".
3. Create an instance for Speech Service.
4. On the page of the instance you created, click "Keys and Endpoint" under "Resource Management" on the left.
5. Copy one of the keys and the "Location/Region".

## Application Usage

Under the root directory, run src/main.py by running:
```
python src/main.py
```

The first time you run the program, you need to enter OpenAI API keys, default language, Azure API keys, and Azure Region. The settings will be saved under the root directory so that you do not need to enter the settings the next time you run the program.

Click the "Speak" button below. Then SPEAK!

On the toolbar, click "Suggestion", which will show the suggested response generated by ChatGPT. However, this will lower the speed because you need one more access every time.

# Updates

Add hide text function (04/02/2023)

Web page version developed(07/02/2023):
[link](https://drawingsword-oral.streamlit.app/)
![Alt Text](./assets/dev_pic.png)

# TODO list

Under construction


================================================
FILE: TODO
================================================


================================================
FILE: src/main.py
================================================
import sys
from view.mainwindow import MainWindow
from model.chatsession import ChatSession
from view.controller import Controller
from PyQt5.QtWidgets import QApplication


def main():
    app = QApplication(sys.argv)
    chatsession = ChatSession()
    window = MainWindow()
    window.show()
    controller = Controller(model = chatsession, view = window)
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()


================================================
FILE: src/model/chatsession.py
================================================
from model.core import recognize_from_mic, synthesize_to_speaker, respond, concatenate, concatenate, suggestion
from model.settings import Settings



class ChatSession:
    def __init__(self, print_cmd = True, *args, **kwargs):
        self.settings = Settings()
        self.lang_tag = self.settings.default_lang

        self.conversation = ""
        self.is_background_set = False

        self.respond_mod = "text-davinci-003"

        self.is_suggestion = False
        self.sugg_mod = "text-davinci-003"

        self.print_cmd = print_cmd
    
    def _speak(self):
        if not self.is_background_set:
            self.conversation = ""
        
        if self.print_cmd:
            print("Speak into your microphone.\n")
        
        my_paragraph = recognize_from_mic(self.lang_tag, self.settings.azure_api, self.settings.azure_region)
        self.conversation = concatenate(self.conversation, "You: ", my_paragraph)

        if self.print_cmd:
            print(f"You: {my_paragraph}\n")
        
        return my_paragraph

    def _respond(self):
        ai_respond = respond(self.conversation, self.respond_mod, self.settings.openai_api)
        synthesize_to_speaker(ai_respond, self.lang_tag, self.settings.azure_api, self.settings.azure_region)
        self.conversation = self.conversation + ai_respond
        self.is_background_set = True

        if self.print_cmd:
            print(f"AI: {ai_respond}\n")
        
        return ai_respond

    def _suggestion(self):
        self.conversation_suggestion = self.conversation+'\nYou: '
        sugg = suggestion(self.conversation_suggestion, self.sugg_mod, self.settings.openai_api)
        if self.print_cmd:
            print(f"Suggestion: {sugg}")
        return sugg
    
    def forward(self):
        my_paragraph = self._speak()
        ai_respond = self._respond()

        suggestion = None
        if self.is_suggestion:
            suggestion = self._suggestion()
        return (my_paragraph, ai_respond, suggestion)

    def mode_changed(self, index):
        if index == 0:
            self.respond_mod = "text-davinci-003"
            self.sugg_mod = "text-davinci-003"
        elif index == 1:
            self.respond_mod = "text-davinci-003"
            self.sugg_mod = "text-curie-001"
        else:
            self.respond_mod = "text-curie-001"
            self.sugg_mod = "text-curie-001"



================================================
FILE: src/model/core.py
================================================
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 18 21:44:21 2023

@author: tomkeen
"""
import azure.cognitiveservices.speech as speechsdk
from azure.cognitiveservices.speech.audio import AudioOutputConfig
import os
import openai
import requests
import json



def recognize_from_mic(lang, key, region):
	#Find your key and resource region under the 'Keys and Endpoint' tab in your Speech resource in Azure Portal
	#Remember to delete the brackets <> when pasting your key and region!
    speech_config = speechsdk.SpeechConfig(subscription=key, region=region)
    speech_config.speech_recognition_language = lang
    # audio_config = speechsdk.AudioConfig(use_default_microphone=True)
    speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config)    
    #Asks user for mic input and prints transcription result on screen
    result = speech_recognizer.recognize_once()

    # Check the result
    # if result.reason == speechsdk.ResultReason.RecognizedSpeech:
    #     print("Recognized: {}".format(result.text))
    # elif result.reason == speechsdk.ResultReason.NoMatch:
    #     print("No speech could be recognized: {}".format(result.no_match_details))
    # elif result.reason == speechsdk.ResultReason.Canceled:
    #     cancellation_details = result.cancellation_details
    #     print("Speech Recognition canceled: {}".format(cancellation_details.reason))
    #     if cancellation_details.reason == speechsdk.CancellationReason.Error:
    #         print("Error details: {}".format(cancellation_details.error_details))

    return result.text

def synthesize_to_speaker(text,lang,key,region):
	#Find your key and resource region under the 'Keys and Endpoint' tab in your Speech resource in Azure Portal
	#Remember to delete the brackets <> when pasting your key and region!
    speech_config = speechsdk.SpeechConfig(subscription=key, region=region)
    speech_config.speech_synthesis_language = lang
    #In this sample we are using the default speaker 
    #Learn how to customize your speaker using SSML in Azure Cognitive Services Speech documentation
    audio_config = AudioOutputConfig(use_default_speaker=True)
    synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)
    synthesizer.speak_text_async(text)


def respond(conversation,mod,key):
    openai.api_key = key
    response = openai.Completion.create(
        model=mod,
        #model="text-curie-001",
        prompt=conversation,
        temperature=1,
        max_tokens=150,
        top_p=1,
        frequency_penalty=1,
        presence_penalty=0.1,
        stop=["YOU:", "AI:"]
    )
    return response.choices[0].text

def suggestion(conversation,mod,key):
    openai.api_key = key
    response = openai.Completion.create(
        model=mod,
        prompt=conversation,
        temperature=1,
        max_tokens=150,
        top_p=1,
        frequency_penalty=1,
        presence_penalty=0.1,
        stop=["YOU:", "AI:"]
    )
    return response.choices[0].text

def concatenate(original, person="You", paragraph=""):
    return f"{original}\n{person}: {paragraph}\n\nAI:"



================================================
FILE: src/model/settings.py
================================================
from view.dialogues import SettingsDialog
import json

class Settings():
    def __init__(self):
        self.has_settings = False
        self._settings = self._load_settings()
    
    @property
    def openai_api(self):
        return self._settings["openai_api"]
    
    @property
    def default_lang(self):
        return self._settings["default_lang"]
    
    @property
    def azure_api(self):
        return self._settings["azure_api"]
    
    @property
    def azure_region(self):
        return self._settings["azure_region"]

    def _update_settings(self):
        api_dialog = SettingsDialog()
        if self.has_settings:
            api_dialog.openai_api_edit.setText(self._settings["openai_api"])
            api_dialog.default_lang_edit.setCurrentText(self._settings["default_lang"])
            api_dialog.azure_api_edit.setText(self._settings["azure_api"])
            api_dialog.azure_region_edit.setText(self._settings["azure_region"])
            settings = self._settings
        if api_dialog.exec_() == api_dialog.Accepted:
            settings = {}
            settings["openai_api"] = api_dialog.openai_api_edit.text().strip()
            settings["default_lang"] = api_dialog.default_lang_edit.currentText()
            settings["azure_api"] = api_dialog.azure_api_edit.text().strip()
            settings["azure_region"] = api_dialog.azure_region_edit.text().strip()

            with open("settings.json", 'w') as f:
                json.dump(settings, f, indent=4)
        return settings
    
    def _load_settings(self):
        # load settings
        try:
            with open("settings.json", 'r') as f:
                settings = json.load(f)
            self.has_settings = True
        except FileNotFoundError:
            settings = self._update_settings()
        
        return settings


================================================
FILE: src/test.py
================================================


================================================
FILE: src/utils.py
================================================
import langcodes

def lang_to_code(language):
    if language == "Chinese":
        code = "zh-CN"
    elif language == "English":
        code = "en-US"
    elif language == "French":
        code = "fr-FR"
    elif language == "Japanese":
        code = "ja-JP"
    return code

================================================
FILE: src/view/components.py
================================================
from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtGui import QTextCursor, QFont, QBrush, QColor
from PyQt5.QtWidgets import QDockWidget, QTextEdit, QPushButton, QVBoxLayout, QHBoxLayout, QWidget, QLabel, QComboBox, QLineEdit, QToolBar, QAction

from . import qt_style_sheet



class BubbleLabel(QLabel):
    def __init__(self, parent=None, text='', color='white', alignment=Qt.AlignLeft):
        super().__init__(parent)
        self.setText(text)
        self.setWordWrap(True)
        self.setAlignment(alignment)
        self.setStyleSheet(f'background-color: {color};  color: white;font: bold 25px Arial; padding: 25px; border-radius: 25px;')



# Toolbar

class ToolBar(QToolBar):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.author_action = QAction("Author", self)
        self.addAction(self.author_action)

        self.text_vis = QAction("Text visibility", self)
        self.addAction(self.text_vis)

        self.mode_selector = QComboBox(self)
        self.mode_selector.addItems(["high Intelligence", "medium Intelligence", "low Intelligence"])
        self.addWidget(self.mode_selector)

        self.suggestion_action = QAction("Suggestion", self)
        self.suggestion_action.setCheckable(True)
        self.addAction(self.suggestion_action)

        self.settings_action = QAction("Settings", self)
        self.addAction(self.settings_action)


# Suggestion Bubble

class SuggestionDockWidget(QDockWidget):
    def __init__(self, *args, **kwargs):
        super().__init__("suggestion", *args, **kwargs)

        self.suggestion_widget = QWidget(self) #set layout
        layout = QVBoxLayout(self.suggestion_widget)
        self.suggestion_widget.setLayout(layout)
        self.setWidget(self.suggestion_widget)
        
        self.label = QLabel(self)
        self.suggestion_widget.layout().addWidget(self.label)

        self.suggestion_label = BubbleLabel(color='green')
        self.suggestion_label_layout = QHBoxLayout()
        self.suggestion_label_layout.addWidget(self.suggestion_label)

        self.suggestion_widget.layout().addLayout(self.suggestion_label_layout)
        # self.hide() # initial hide the suggestion



# Central text window

class TextEdit(QTextEdit):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setReadOnly(True)
        size_policy = self.sizePolicy()
        size_policy.setRetainSizeWhenHidden(True)
        self.setSizePolicy(size_policy)
        self.setStyleSheet(qt_style_sheet.text_edit)
    
    @pyqtSlot()
    def append_text(self, text, color):
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertBlock()
        charFormat = cursor.charFormat()
        charFormat.setForeground(QBrush(QColor(color)))
        font = QFont()
        font.setPointSize(14)
        font.setFamily("Arial")
        charFormat.setFont(font)
        cursor.setCharFormat(charFormat)
        cursor.insertText(text)
        self.setTextCursor(cursor)
        self.ensureCursorVisible()



# Background input

class BackgroundInput(QLineEdit):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setPlaceholderText("Enter the initial setting")
        self.setStyleSheet(qt_style_sheet.background_input)



# Lower buttons

class LanguageBox(QComboBox):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.language_list = ["zh-CN", "en-US", "en-GB", "fr-FR", "ja-JP"]
        self.addItems(self.language_list)
        self.setStyleSheet(qt_style_sheet.language_box)

class SpeakButton(QPushButton):
    def __init__(self, *args, **kwargs):
        super().__init__("Speak", *args, **kwargs)
        self.setStyleSheet(qt_style_sheet.speak_button)

class ClearButton(QPushButton):
    def __init__(self, *args, **kwargs):
        super().__init__("Clear", *args, **kwargs)

class LowerLayout(QHBoxLayout):
    def __init__(self, parent):
        super().__init__()
        self.language_box = LanguageBox(parent=parent)
        self.speak_button = SpeakButton(parent=parent)
        self.clear_button = ClearButton(parent=parent)
        self.addWidget(self.language_box)
        self.addWidget(self.speak_button)
        self.addWidget(self.clear_button)


================================================
FILE: src/view/controller.py
================================================
class Controller:
    def __init__(self, model, view):
        self._model = model
        self._view = view
        self._default_settings()
        self._connect_signals()
    
    
    # ToolBar
    def _display_author_info(self):
        from PyQt5.QtWidgets import QMessageBox
        QMessageBox.information(self._view, "Author Information", "Author: Bowen ZHU\nEmail: bowen.zhu@student-cs.fr\nContributor: Chuanqi XU\nEmail: chuanqi.xu@yale.edu")
    
    def _change_text_vis(self):
        self._view.text_edit.setVisible(not self._view.text_edit.isVisible())

    def _change_mode(self, index):
        if index == 0:
            self._model.respond_mod = "text-davinci-003"
            self._model.sugg_mod = "text-davinci-003"
        elif index == 1:
            self._model.respond_mod = "text-davinci-003"
            self._model.sugg_mod = "text-curie-001"
        else:
            self._model.respond_mod = "text-curie-001"
            self._model.sugg_mod = "text-curie-001"
    
    def _change_suggestion(self):
        self._model.is_suggestion = not self._model.is_suggestion
        if self._model.is_suggestion:
            self._view.suggestion_window.show()
        else:
            self._view.suggestion_window.hide()

    def _change_settings(self):
        self._model.settings._update_settings()


    
    # Background input
    # @pyqtSlot()
    def _update_background(self):
        self._model.conversation = self._view.background_input.text()
        self._model.is_background_set = True



    # Lower Buttons

    def _change_language(self):
        self._model.lang_tag = self._view.lower_layout.language_box.currentText()

    # @pyqtSlot()
    def _speak(self):
        my_paragraph, ai_respond, sugg = self._model.forward()
        self._view.text_edit.append_text("You: " + my_paragraph, "blue")
        self._view.text_edit.append_text("AI: " + ai_respond, "green")

        if self._model.is_suggestion:
            self._view.suggestion_window.suggestion_label.setText(sugg.replace('\n', ''))
    
    def _clear_text(self):
        self._model.conversation=''
        self._model.is_background_set = False
        self._view.text_edit.clear()
        self._view.background_input.clear()
        if self._model.is_suggestion:
            self._view.suggestion_window.suggestion_label.setText("")
    


    # Default settings when creating the objects
    def _default_settings(self):
        self._view.suggestion_window.hide()
        self._view.lower_layout.language_box.setCurrentText(self._model.lang_tag)

    # Connect all signals when creating the objects

    def _connect_signals(self):
        # ToolBar
        self._view.toolbar.author_action.triggered.connect(self._display_author_info)
        self._view.toolbar.text_vis.triggered.connect(self._change_text_vis)
        self._view.toolbar.mode_selector.currentIndexChanged.connect(self._change_mode)
        self._view.toolbar.suggestion_action.triggered.connect(self._change_suggestion)
        self._view.toolbar.settings_action.triggered.connect(self._change_settings)

        # Background input
        self._view.background_input.textChanged.connect(self._update_background)

        # Lower Buttons
        self._view.lower_layout.language_box.currentIndexChanged.connect(self._change_language)
        self._view.lower_layout.speak_button.clicked.connect(self._speak)
        self._view.lower_layout.clear_button.clicked.connect(self._clear_text)



================================================
FILE: src/view/dialogues.py
================================================
from PyQt5.QtWidgets import QFormLayout, QDialog, QPushButton, QLineEdit, QComboBox
from . import qt_style_sheet


class SettingsDialog(QDialog):
    def __init__(self, azure_api=None, azure_region=None, openai_api=None, default_lang=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle("Settings")

        self.azure_api = azure_api
        self.azure_region = azure_region
        self.openai_api = openai_api
        self.default_lang = default_lang

        layout = QFormLayout()

        self.openai_api_edit = QLineEdit(self.openai_api)
        layout.addRow("OpenAI API Key:", self.openai_api_edit)

        # self.default_lang_edit = QLineEdit(self.default_lang)
        # layout.addRow("Default Language:", self.default_lang_edit)
        self.default_lang_edit = QComboBox(self.default_lang)
        language_list = ["zh-CN", "en-US", "en-GB", "fr-FR", "ja-JP"]
        self.default_lang_edit.addItems(language_list)
        self.default_lang_edit.setStyleSheet(qt_style_sheet.language_box)
        layout.addRow("Default Language:", self.default_lang_edit)

        self.azure_api_edit = QLineEdit(self.azure_api)
        layout.addRow("Azure API Key:", self.azure_api_edit)

        self.azure_region_edit = QLineEdit(self.azure_region)
        layout.addRow("Azure Region:", self.azure_region_edit)

        save_button = QPushButton("Save")
        save_button.clicked.connect(self.accept)
        layout.addWidget(save_button)
        self.setLayout(layout)


================================================
FILE: src/view/mainwindow.py
================================================
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QVBoxLayout, QHBoxLayout, QWidget

from model.chatsession import ChatSession
from .components import ToolBar, SuggestionDockWidget, TextEdit, BackgroundInput, LowerLayout



class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.chat_session = ChatSession()

        # Size and Title
        self.setFixedSize(800, 900)
        self.setWindowTitle("ChatGPT Speaking Practice")

        # ToolBar
        self.toolbar = ToolBar(parent=self)
        self.addToolBar(self.toolbar)

        # Suggestion Window
        self.suggestion_window = SuggestionDockWidget()
        self.suggestion_window.setGeometry(self.x() + self.width(), self.y(), 400, 400)
        self.addDockWidget(Qt.TopDockWidgetArea, self.suggestion_window)
        
        # Create central widget, which contains:
        #   1. text_edit
        #   2. conversation backgound
        #   3. lower buttons
        self.central_widget = QWidget(parent=self)
        self.setCentralWidget(self.central_widget)
        
        self.layout = QVBoxLayout()
        self.text_edit = TextEdit(parent=self)
        self.background_input = BackgroundInput(parent=self)
        self.lower_layout = LowerLayout(parent=self)
        self.layout.addWidget(self.text_edit)
        self.layout.addWidget(self.background_input)
        self.layout.addLayout(self.lower_layout)

        self.central_widget.setLayout(self.layout)

        # creat bubble
        self.user_bubble = None
        self.ai_bubble = None



================================================
FILE: src/view/qt_style_sheet.py
================================================
conversation = """
    QLineEdit {
            background-color: white;
            color: black;
            font-size: 25px;
            padding: 10px;
            border: 2px solid gray;
            border-radius: 5px;
        }
    """

language_box = """
    QComboBox {
        background-color: white;
        color: black;
        padding: 5px;
        border: 1px solid gray;
        border-radius: 3px;
        min-width: 6em;
    }
    QComboBox::drop-down {
        subcontrol-origin: padding;
        subcontrol-position: top right;
        width: 15px;
        border-left-width: 1px;
        border-left-color: darkgray;
        border-left-style: solid;
        border-top-right-radius: 3px;
        border-bottom-right-radius: 3px;
    }
    QComboBox::down-arrow {
        image: url(down_arrow.png);
    }
    QComboBox QAbstractItemView {
        background-color: white;
        border: 1px solid gray;
        selection-background-color: lightgray;
    }
    """

text_edit = """
    QTextEdit {
        background-color: white;
        background-image: url(/test.jpg);
        color: black;
        font-size: 16px;
        padding: 10px;
        border: 1px solid gray;
        border-radius: 3px;
    }
    """

background_input = """
    QLineEdit {
            background-color: white;
            color: black;
            font-size: 25px;
            padding: 10px;
            border: 2px solid gray;
            border-radius: 5px;
        }
    """

speak_button = """
QPushButton { 
    background-color: grey; 
    border-radius: 20px; 
    padding: 10px; color:white; 
    font-size:20px;
} 
QPushButton:hover { 
    background-color: red; 
} 
QPushButton:pressed { 
    background-color: green; 
}
"""
Download .txt
gitextract_izn_nl_w/

├── .gitignore
├── LICENSE
├── README.md
├── TODO
└── src/
    ├── main.py
    ├── model/
    │   ├── chatsession.py
    │   ├── core.py
    │   └── settings.py
    ├── test.py
    ├── utils.py
    └── view/
        ├── components.py
        ├── controller.py
        ├── dialogues.py
        ├── mainwindow.py
        └── qt_style_sheet.py
Download .txt
SYMBOL INDEX (58 symbols across 9 files)

FILE: src/main.py
  function main (line 8) | def main():

FILE: src/model/chatsession.py
  class ChatSession (line 6) | class ChatSession:
    method __init__ (line 7) | def __init__(self, print_cmd = True, *args, **kwargs):
    method _speak (line 21) | def _speak(self):
    method _respond (line 36) | def _respond(self):
    method _suggestion (line 47) | def _suggestion(self):
    method forward (line 54) | def forward(self):
    method mode_changed (line 63) | def mode_changed(self, index):

FILE: src/model/core.py
  function recognize_from_mic (line 16) | def recognize_from_mic(lang, key, region):
  function synthesize_to_speaker (line 39) | def synthesize_to_speaker(text,lang,key,region):
  function respond (line 51) | def respond(conversation,mod,key):
  function suggestion (line 66) | def suggestion(conversation,mod,key):
  function concatenate (line 80) | def concatenate(original, person="You", paragraph=""):

FILE: src/model/settings.py
  class Settings (line 4) | class Settings():
    method __init__ (line 5) | def __init__(self):
    method openai_api (line 10) | def openai_api(self):
    method default_lang (line 14) | def default_lang(self):
    method azure_api (line 18) | def azure_api(self):
    method azure_region (line 22) | def azure_region(self):
    method _update_settings (line 25) | def _update_settings(self):
    method _load_settings (line 44) | def _load_settings(self):

FILE: src/utils.py
  function lang_to_code (line 3) | def lang_to_code(language):

FILE: src/view/components.py
  class BubbleLabel (line 9) | class BubbleLabel(QLabel):
    method __init__ (line 10) | def __init__(self, parent=None, text='', color='white', alignment=Qt.A...
  class ToolBar (line 21) | class ToolBar(QToolBar):
    method __init__ (line 22) | def __init__(self, *args, **kwargs):
  class SuggestionDockWidget (line 45) | class SuggestionDockWidget(QDockWidget):
    method __init__ (line 46) | def __init__(self, *args, **kwargs):
  class TextEdit (line 68) | class TextEdit(QTextEdit):
    method __init__ (line 69) | def __init__(self, *args, **kwargs):
    method append_text (line 79) | def append_text(self, text, color):
  class BackgroundInput (line 98) | class BackgroundInput(QLineEdit):
    method __init__ (line 99) | def __init__(self, *args, **kwargs):
  class LanguageBox (line 108) | class LanguageBox(QComboBox):
    method __init__ (line 109) | def __init__(self, *args, **kwargs):
  class SpeakButton (line 115) | class SpeakButton(QPushButton):
    method __init__ (line 116) | def __init__(self, *args, **kwargs):
  class ClearButton (line 120) | class ClearButton(QPushButton):
    method __init__ (line 121) | def __init__(self, *args, **kwargs):
  class LowerLayout (line 124) | class LowerLayout(QHBoxLayout):
    method __init__ (line 125) | def __init__(self, parent):

FILE: src/view/controller.py
  class Controller (line 1) | class Controller:
    method __init__ (line 2) | def __init__(self, model, view):
    method _display_author_info (line 10) | def _display_author_info(self):
    method _change_text_vis (line 14) | def _change_text_vis(self):
    method _change_mode (line 17) | def _change_mode(self, index):
    method _change_suggestion (line 28) | def _change_suggestion(self):
    method _change_settings (line 35) | def _change_settings(self):
    method _update_background (line 42) | def _update_background(self):
    method _change_language (line 50) | def _change_language(self):
    method _speak (line 54) | def _speak(self):
    method _clear_text (line 62) | def _clear_text(self):
    method _default_settings (line 73) | def _default_settings(self):
    method _connect_signals (line 79) | def _connect_signals(self):

FILE: src/view/dialogues.py
  class SettingsDialog (line 5) | class SettingsDialog(QDialog):
    method __init__ (line 6) | def __init__(self, azure_api=None, azure_region=None, openai_api=None,...

FILE: src/view/mainwindow.py
  class MainWindow (line 9) | class MainWindow(QMainWindow):
    method __init__ (line 11) | def __init__(self, *args, **kwargs):
Condensed preview — 15 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (42K chars).
[
  {
    "path": ".gitignore",
    "chars": 28,
    "preview": "settings.json\n*__pycache__*\n"
  },
  {
    "path": "LICENSE",
    "chars": 16725,
    "preview": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\""
  },
  {
    "path": "README.md",
    "chars": 2195,
    "preview": "# Introduction\n\n[A video introduction in Chinese](https://www.bilibili.com/video/BV1Xs4y1p7t8/)\n\n# Dependency\n\nThis appl"
  },
  {
    "path": "TODO",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "src/main.py",
    "chars": 424,
    "preview": "import sys\nfrom view.mainwindow import MainWindow\nfrom model.chatsession import ChatSession\nfrom view.controller import "
  },
  {
    "path": "src/model/chatsession.py",
    "chars": 2396,
    "preview": "from model.core import recognize_from_mic, synthesize_to_speaker, respond, concatenate, concatenate, suggestion\nfrom mod"
  },
  {
    "path": "src/model/core.py",
    "chars": 3128,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 18 21:44:21 2023\n\n@author: tomkeen\n\"\"\"\nimport azure.cognitiveservices.spe"
  },
  {
    "path": "src/model/settings.py",
    "chars": 1838,
    "preview": "from view.dialogues import SettingsDialog\nimport json\n\nclass Settings():\n    def __init__(self):\n        self.has_settin"
  },
  {
    "path": "src/test.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "src/utils.py",
    "chars": 279,
    "preview": "import langcodes\n\ndef lang_to_code(language):\n    if language == \"Chinese\":\n        code = \"zh-CN\"\n    elif language == "
  },
  {
    "path": "src/view/components.py",
    "chars": 4343,
    "preview": "from PyQt5.QtCore import pyqtSlot, Qt\nfrom PyQt5.QtGui import QTextCursor, QFont, QBrush, QColor\nfrom PyQt5.QtWidgets im"
  },
  {
    "path": "src/view/controller.py",
    "chars": 3469,
    "preview": "class Controller:\n    def __init__(self, model, view):\n        self._model = model\n        self._view = view\n        sel"
  },
  {
    "path": "src/view/dialogues.py",
    "chars": 1516,
    "preview": "from PyQt5.QtWidgets import QFormLayout, QDialog, QPushButton, QLineEdit, QComboBox\nfrom . import qt_style_sheet\n\n\nclass"
  },
  {
    "path": "src/view/mainwindow.py",
    "chars": 1612,
    "preview": "from PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QMainWindow, QVBoxLayout, QHBoxLayout, QWidget\n\nfrom model.chats"
  },
  {
    "path": "src/view/qt_style_sheet.py",
    "chars": 1739,
    "preview": "conversation = \"\"\"\n    QLineEdit {\n            background-color: white;\n            color: black;\n            font-size:"
  }
]

About this extraction

This page contains the full source code of the tomzhu0225/oral_practice_with_openai GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 15 files (38.8 KB), approximately 9.0k tokens, and a symbol index with 58 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!