[
  {
    "path": ".gitignore",
    "content": "settings.json\n*__pycache__*\n"
  },
  {
    "path": "LICENSE",
    "content": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\"\n    means each individual or legal entity that creates, contributes to\n    the creation of, or owns Covered Software.\n\n1.2. \"Contributor Version\"\n    means the combination of the Contributions of others (if any) used\n    by a Contributor and that particular Contributor's Contribution.\n\n1.3. \"Contribution\"\n    means Covered Software of a particular Contributor.\n\n1.4. \"Covered Software\"\n    means Source Code Form to which the initial Contributor has attached\n    the notice in Exhibit A, the Executable Form of such Source Code\n    Form, and Modifications of such Source Code Form, in each case\n    including portions thereof.\n\n1.5. \"Incompatible With Secondary Licenses\"\n    means\n\n    (a) that the initial Contributor has attached the notice described\n        in Exhibit B to the Covered Software; or\n\n    (b) that the Covered Software was made available under the terms of\n        version 1.1 or earlier of the License, but not also under the\n        terms of a Secondary License.\n\n1.6. \"Executable Form\"\n    means any form of the work other than Source Code Form.\n\n1.7. \"Larger Work\"\n    means a work that combines Covered Software with other material, in\n    a separate file or files, that is not Covered Software.\n\n1.8. \"License\"\n    means this document.\n\n1.9. \"Licensable\"\n    means having the right to grant, to the maximum extent possible,\n    whether at the time of the initial grant or subsequently, any and\n    all of the rights conveyed by this License.\n\n1.10. \"Modifications\"\n    means any of the following:\n\n    (a) any file in Source Code Form that results from an addition to,\n        deletion from, or modification of the contents of Covered\n        Software; or\n\n    (b) any new file in Source Code Form that contains any Covered\n        Software.\n\n1.11. \"Patent Claims\" of a Contributor\n    means any patent claim(s), including without limitation, method,\n    process, and apparatus claims, in any patent Licensable by such\n    Contributor that would be infringed, but for the grant of the\n    License, by the making, using, selling, offering for sale, having\n    made, import, or transfer of either its Contributions or its\n    Contributor Version.\n\n1.12. \"Secondary License\"\n    means either the GNU General Public License, Version 2.0, the GNU\n    Lesser General Public License, Version 2.1, the GNU Affero General\n    Public License, Version 3.0, or any later versions of those\n    licenses.\n\n1.13. \"Source Code Form\"\n    means the form of the work preferred for making modifications.\n\n1.14. \"You\" (or \"Your\")\n    means an individual or a legal entity exercising rights under this\n    License. For legal entities, \"You\" includes any entity that\n    controls, is controlled by, or is under common control with You. For\n    purposes of this definition, \"control\" means (a) the power, direct\n    or indirect, to cause the direction or management of such entity,\n    whether by contract or otherwise, or (b) ownership of more than\n    fifty percent (50%) of the outstanding shares or beneficial\n    ownership of such entity.\n\n2. License Grants and Conditions\n--------------------------------\n\n2.1. Grants\n\nEach Contributor hereby grants You a world-wide, royalty-free,\nnon-exclusive license:\n\n(a) under intellectual property rights (other than patent or trademark)\n    Licensable by such Contributor to use, reproduce, make available,\n    modify, display, perform, distribute, and otherwise exploit its\n    Contributions, either on an unmodified basis, with Modifications, or\n    as part of a Larger Work; and\n\n(b) under Patent Claims of such Contributor to make, use, sell, offer\n    for sale, have made, import, and otherwise transfer either its\n    Contributions or its Contributor Version.\n\n2.2. Effective Date\n\nThe licenses granted in Section 2.1 with respect to any Contribution\nbecome effective for each Contribution on the date the Contributor first\ndistributes such Contribution.\n\n2.3. Limitations on Grant Scope\n\nThe licenses granted in this Section 2 are the only rights granted under\nthis License. No additional rights or licenses will be implied from the\ndistribution or licensing of Covered Software under this License.\nNotwithstanding Section 2.1(b) above, no patent license is granted by a\nContributor:\n\n(a) for any code that a Contributor has removed from Covered Software;\n    or\n\n(b) for infringements caused by: (i) Your and any other third party's\n    modifications of Covered Software, or (ii) the combination of its\n    Contributions with other software (except as part of its Contributor\n    Version); or\n\n(c) under Patent Claims infringed by Covered Software in the absence of\n    its Contributions.\n\nThis License does not grant any rights in the trademarks, service marks,\nor logos of any Contributor (except as may be necessary to comply with\nthe notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\nNo Contributor makes additional grants as a result of Your choice to\ndistribute the Covered Software under a subsequent version of this\nLicense (see Section 10.2) or under the terms of a Secondary License (if\npermitted under the terms of Section 3.3).\n\n2.5. Representation\n\nEach Contributor represents that the Contributor believes its\nContributions are its original creation(s) or it has sufficient rights\nto grant the rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\nThis License is not intended to limit any rights You have under\napplicable copyright doctrines of fair use, fair dealing, or other\nequivalents.\n\n2.7. Conditions\n\nSections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted\nin Section 2.1.\n\n3. Responsibilities\n-------------------\n\n3.1. Distribution of Source Form\n\nAll distribution of Covered Software in Source Code Form, including any\nModifications that You create or to which You contribute, must be under\nthe terms of this License. You must inform recipients that the Source\nCode Form of the Covered Software is governed by the terms of this\nLicense, and how they can obtain a copy of this License. You may not\nattempt to alter or restrict the recipients' rights in the Source Code\nForm.\n\n3.2. Distribution of Executable Form\n\nIf You distribute Covered Software in Executable Form then:\n\n(a) such Covered Software must also be made available in Source Code\n    Form, as described in Section 3.1, and You must inform recipients of\n    the Executable Form how they can obtain a copy of such Source Code\n    Form by reasonable means in a timely manner, at a charge no more\n    than the cost of distribution to the recipient; and\n\n(b) You may distribute such Executable Form under the terms of this\n    License, or sublicense it under different terms, provided that the\n    license for the Executable Form does not attempt to limit or alter\n    the recipients' rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\nYou may create and distribute a Larger Work under terms of Your choice,\nprovided that You also comply with the requirements of this License for\nthe Covered Software. If the Larger Work is a combination of Covered\nSoftware with a work governed by one or more Secondary Licenses, and the\nCovered Software is not Incompatible With Secondary Licenses, this\nLicense permits You to additionally distribute such Covered Software\nunder the terms of such Secondary License(s), so that the recipient of\nthe Larger Work may, at their option, further distribute the Covered\nSoftware under the terms of either this License or such Secondary\nLicense(s).\n\n3.4. Notices\n\nYou may not remove or alter the substance of any license notices\n(including copyright notices, patent notices, disclaimers of warranty,\nor limitations of liability) contained within the Source Code Form of\nthe Covered Software, except that You may alter any license notices to\nthe extent required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\nYou may choose to offer, and to charge a fee for, warranty, support,\nindemnity or liability obligations to one or more recipients of Covered\nSoftware. However, You may do so only on Your own behalf, and not on\nbehalf of any Contributor. You must make it absolutely clear that any\nsuch warranty, support, indemnity, or liability obligation is offered by\nYou alone, and You hereby agree to indemnify every Contributor for any\nliability incurred by such Contributor as a result of warranty, support,\nindemnity or liability terms You offer. You may include additional\ndisclaimers of warranty and limitations of liability specific to any\njurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n---------------------------------------------------\n\nIf it is impossible for You to comply with any of the terms of this\nLicense with respect to some or all of the Covered Software due to\nstatute, judicial order, or regulation then You must: (a) comply with\nthe terms of this License to the maximum extent possible; and (b)\ndescribe the limitations and the code they affect. Such description must\nbe placed in a text file included with all distributions of the Covered\nSoftware under this License. Except to the extent prohibited by statute\nor regulation, such description must be sufficiently detailed for a\nrecipient of ordinary skill to be able to understand it.\n\n5. Termination\n--------------\n\n5.1. The rights granted under this License will terminate automatically\nif You fail to comply with any of its terms. However, if You become\ncompliant, then the rights granted under this License from a particular\nContributor are reinstated (a) provisionally, unless and until such\nContributor explicitly and finally terminates Your grants, and (b) on an\nongoing basis, if such Contributor fails to notify You of the\nnon-compliance by some reasonable means prior to 60 days after You have\ncome back into compliance. Moreover, Your grants from a particular\nContributor are reinstated on an ongoing basis if such Contributor\nnotifies You of the non-compliance by some reasonable means, this is the\nfirst time You have received notice of non-compliance with this License\nfrom such Contributor, and You become compliant prior to 30 days after\nYour receipt of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\ninfringement claim (excluding declaratory judgment actions,\ncounter-claims, and cross-claims) alleging that a Contributor Version\ndirectly or indirectly infringes any patent, then the rights granted to\nYou by any and all Contributors for the Covered Software under Section\n2.1 of this License shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all\nend user license agreements (excluding distributors and resellers) which\nhave been validly granted by You or Your distributors under this License\nprior to termination shall survive termination.\n\n************************************************************************\n*                                                                      *\n*  6. Disclaimer of Warranty                                           *\n*  -------------------------                                           *\n*                                                                      *\n*  Covered Software is provided under this License on an \"as is\"       *\n*  basis, without warranty of any kind, either expressed, implied, or  *\n*  statutory, including, without limitation, warranties that the       *\n*  Covered Software is free of defects, merchantable, fit for a        *\n*  particular purpose or non-infringing. The entire risk as to the     *\n*  quality and performance of the Covered Software is with You.        *\n*  Should any Covered Software prove defective in any respect, You     *\n*  (not any Contributor) assume the cost of any necessary servicing,   *\n*  repair, or correction. This disclaimer of warranty constitutes an   *\n*  essential part of this License. No use of any Covered Software is   *\n*  authorized under this License except under this disclaimer.         *\n*                                                                      *\n************************************************************************\n\n************************************************************************\n*                                                                      *\n*  7. Limitation of Liability                                          *\n*  --------------------------                                          *\n*                                                                      *\n*  Under no circumstances and under no legal theory, whether tort      *\n*  (including negligence), contract, or otherwise, shall any           *\n*  Contributor, or anyone who distributes Covered Software as          *\n*  permitted above, be liable to You for any direct, indirect,         *\n*  special, incidental, or consequential damages of any character      *\n*  including, without limitation, damages for lost profits, loss of    *\n*  goodwill, work stoppage, computer failure or malfunction, or any    *\n*  and all other commercial damages or losses, even if such party      *\n*  shall have been informed of the possibility of such damages. This   *\n*  limitation of liability shall not apply to liability for death or   *\n*  personal injury resulting from such party's negligence to the       *\n*  extent applicable law prohibits such limitation. Some               *\n*  jurisdictions do not allow the exclusion or limitation of           *\n*  incidental or consequential damages, so this exclusion and          *\n*  limitation may not apply to You.                                    *\n*                                                                      *\n************************************************************************\n\n8. Litigation\n-------------\n\nAny litigation relating to this License may be brought only in the\ncourts of a jurisdiction where the defendant maintains its principal\nplace of business and such litigation shall be governed by laws of that\njurisdiction, without reference to its conflict-of-law provisions.\nNothing in this Section shall prevent a party's ability to bring\ncross-claims or counter-claims.\n\n9. Miscellaneous\n----------------\n\nThis License represents the complete agreement concerning the subject\nmatter hereof. If any provision of this License is held to be\nunenforceable, such provision shall be reformed only to the extent\nnecessary to make it enforceable. Any law or regulation which provides\nthat the language of a contract shall be construed against the drafter\nshall not be used to construe this License against a Contributor.\n\n10. Versions of the License\n---------------------------\n\n10.1. New Versions\n\nMozilla Foundation is the license steward. Except as provided in Section\n10.3, no one other than the license steward has the right to modify or\npublish new versions of this License. Each version will be given a\ndistinguishing version number.\n\n10.2. Effect of New Versions\n\nYou may distribute the Covered Software under the terms of the version\nof the License under which You originally received the Covered Software,\nor under the terms of any subsequent version published by the license\nsteward.\n\n10.3. Modified Versions\n\nIf you create software not governed by this License, and you want to\ncreate a new license for such software, you may create and use a\nmodified version of this License if you rename the license and remove\nany references to the name of the license steward (except to note that\nsuch modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary\nLicenses\n\nIf You choose to distribute Source Code Form that is Incompatible With\nSecondary Licenses under the terms of this version of the License, the\nnotice described in Exhibit B of this License must be attached.\n\nExhibit A - Source Code Form License Notice\n-------------------------------------------\n\n  This Source Code Form is subject to the terms of the Mozilla Public\n  License, v. 2.0. If a copy of the MPL was not distributed with this\n  file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular\nfile, then You may include the notice in a location (such as a LICENSE\nfile in a relevant directory) where a recipient would be likely to look\nfor such a notice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - \"Incompatible With Secondary Licenses\" Notice\n---------------------------------------------------------\n\n  This Source Code Form is \"Incompatible With Secondary Licenses\", as\n  defined by the Mozilla Public License, v. 2.0.\n"
  },
  {
    "path": "README.md",
    "content": "# Introduction\n\n[A video introduction in Chinese](https://www.bilibili.com/video/BV1Xs4y1p7t8/)\n\n# Dependency\n\nThis 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).\n\nAPI keys from both platforms are needed.\n\nAdditional 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/)\n\n```\npip install openai azure-cognitiveservices-speech PyQt5\n```\n\n# Usage\n\n## Get API keys from OpenAI\n\n1. Log in to [OpenAI](https://openai.com/api/).\n2. In the overview page, click the upper right icon, and then click \"View API keys\".\n3. 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.\n\n## Get API keys from Microsoft Microsoft Azure Cognitive Services\n\n1. Log in to [Microsoft Azure](https://azure.microsoft.com/en-us/free/students/).\n2. In the search banner, search \"Speech Service\".\n3. Create an instance for Speech Service.\n4. On the page of the instance you created, click \"Keys and Endpoint\" under \"Resource Management\" on the left.\n5. Copy one of the keys and the \"Location/Region\".\n\n## Application Usage\n\nUnder the root directory, run src/main.py by running:\n```\npython src/main.py\n```\n\nThe 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.\n\nClick the \"Speak\" button below. Then SPEAK!\n\nOn 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.\n\n# Updates\n\nAdd hide text function (04/02/2023)\n\nWeb page version developed(07/02/2023):\n[link](https://drawingsword-oral.streamlit.app/)\n![Alt Text](./assets/dev_pic.png)\n\n# TODO list\n\nUnder construction\n"
  },
  {
    "path": "TODO",
    "content": ""
  },
  {
    "path": "src/main.py",
    "content": "import sys\nfrom view.mainwindow import MainWindow\nfrom model.chatsession import ChatSession\nfrom view.controller import Controller\nfrom PyQt5.QtWidgets import QApplication\n\n\ndef main():\n    app = QApplication(sys.argv)\n    chatsession = ChatSession()\n    window = MainWindow()\n    window.show()\n    controller = Controller(model = chatsession, view = window)\n    sys.exit(app.exec_())\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/model/chatsession.py",
    "content": "from model.core import recognize_from_mic, synthesize_to_speaker, respond, concatenate, concatenate, suggestion\nfrom model.settings import Settings\n\n\n\nclass ChatSession:\n    def __init__(self, print_cmd = True, *args, **kwargs):\n        self.settings = Settings()\n        self.lang_tag = self.settings.default_lang\n\n        self.conversation = \"\"\n        self.is_background_set = False\n\n        self.respond_mod = \"text-davinci-003\"\n\n        self.is_suggestion = False\n        self.sugg_mod = \"text-davinci-003\"\n\n        self.print_cmd = print_cmd\n    \n    def _speak(self):\n        if not self.is_background_set:\n            self.conversation = \"\"\n        \n        if self.print_cmd:\n            print(\"Speak into your microphone.\\n\")\n        \n        my_paragraph = recognize_from_mic(self.lang_tag, self.settings.azure_api, self.settings.azure_region)\n        self.conversation = concatenate(self.conversation, \"You: \", my_paragraph)\n\n        if self.print_cmd:\n            print(f\"You: {my_paragraph}\\n\")\n        \n        return my_paragraph\n\n    def _respond(self):\n        ai_respond = respond(self.conversation, self.respond_mod, self.settings.openai_api)\n        synthesize_to_speaker(ai_respond, self.lang_tag, self.settings.azure_api, self.settings.azure_region)\n        self.conversation = self.conversation + ai_respond\n        self.is_background_set = True\n\n        if self.print_cmd:\n            print(f\"AI: {ai_respond}\\n\")\n        \n        return ai_respond\n\n    def _suggestion(self):\n        self.conversation_suggestion = self.conversation+'\\nYou: '\n        sugg = suggestion(self.conversation_suggestion, self.sugg_mod, self.settings.openai_api)\n        if self.print_cmd:\n            print(f\"Suggestion: {sugg}\")\n        return sugg\n    \n    def forward(self):\n        my_paragraph = self._speak()\n        ai_respond = self._respond()\n\n        suggestion = None\n        if self.is_suggestion:\n            suggestion = self._suggestion()\n        return (my_paragraph, ai_respond, suggestion)\n\n    def mode_changed(self, index):\n        if index == 0:\n            self.respond_mod = \"text-davinci-003\"\n            self.sugg_mod = \"text-davinci-003\"\n        elif index == 1:\n            self.respond_mod = \"text-davinci-003\"\n            self.sugg_mod = \"text-curie-001\"\n        else:\n            self.respond_mod = \"text-curie-001\"\n            self.sugg_mod = \"text-curie-001\"\n\n"
  },
  {
    "path": "src/model/core.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 18 21:44:21 2023\n\n@author: tomkeen\n\"\"\"\nimport azure.cognitiveservices.speech as speechsdk\nfrom azure.cognitiveservices.speech.audio import AudioOutputConfig\nimport os\nimport openai\nimport requests\nimport json\n\n\n\ndef recognize_from_mic(lang, key, region):\n\t#Find your key and resource region under the 'Keys and Endpoint' tab in your Speech resource in Azure Portal\n\t#Remember to delete the brackets <> when pasting your key and region!\n    speech_config = speechsdk.SpeechConfig(subscription=key, region=region)\n    speech_config.speech_recognition_language = lang\n    # audio_config = speechsdk.AudioConfig(use_default_microphone=True)\n    speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config)    \n    #Asks user for mic input and prints transcription result on screen\n    result = speech_recognizer.recognize_once()\n\n    # Check the result\n    # if result.reason == speechsdk.ResultReason.RecognizedSpeech:\n    #     print(\"Recognized: {}\".format(result.text))\n    # elif result.reason == speechsdk.ResultReason.NoMatch:\n    #     print(\"No speech could be recognized: {}\".format(result.no_match_details))\n    # elif result.reason == speechsdk.ResultReason.Canceled:\n    #     cancellation_details = result.cancellation_details\n    #     print(\"Speech Recognition canceled: {}\".format(cancellation_details.reason))\n    #     if cancellation_details.reason == speechsdk.CancellationReason.Error:\n    #         print(\"Error details: {}\".format(cancellation_details.error_details))\n\n    return result.text\n\ndef synthesize_to_speaker(text,lang,key,region):\n\t#Find your key and resource region under the 'Keys and Endpoint' tab in your Speech resource in Azure Portal\n\t#Remember to delete the brackets <> when pasting your key and region!\n    speech_config = speechsdk.SpeechConfig(subscription=key, region=region)\n    speech_config.speech_synthesis_language = lang\n    #In this sample we are using the default speaker \n    #Learn how to customize your speaker using SSML in Azure Cognitive Services Speech documentation\n    audio_config = AudioOutputConfig(use_default_speaker=True)\n    synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)\n    synthesizer.speak_text_async(text)\n\n\ndef respond(conversation,mod,key):\n    openai.api_key = key\n    response = openai.Completion.create(\n        model=mod,\n        #model=\"text-curie-001\",\n        prompt=conversation,\n        temperature=1,\n        max_tokens=150,\n        top_p=1,\n        frequency_penalty=1,\n        presence_penalty=0.1,\n        stop=[\"YOU:\", \"AI:\"]\n    )\n    return response.choices[0].text\n\ndef suggestion(conversation,mod,key):\n    openai.api_key = key\n    response = openai.Completion.create(\n        model=mod,\n        prompt=conversation,\n        temperature=1,\n        max_tokens=150,\n        top_p=1,\n        frequency_penalty=1,\n        presence_penalty=0.1,\n        stop=[\"YOU:\", \"AI:\"]\n    )\n    return response.choices[0].text\n\ndef concatenate(original, person=\"You\", paragraph=\"\"):\n    return f\"{original}\\n{person}: {paragraph}\\n\\nAI:\"\n\n"
  },
  {
    "path": "src/model/settings.py",
    "content": "from view.dialogues import SettingsDialog\nimport json\n\nclass Settings():\n    def __init__(self):\n        self.has_settings = False\n        self._settings = self._load_settings()\n    \n    @property\n    def openai_api(self):\n        return self._settings[\"openai_api\"]\n    \n    @property\n    def default_lang(self):\n        return self._settings[\"default_lang\"]\n    \n    @property\n    def azure_api(self):\n        return self._settings[\"azure_api\"]\n    \n    @property\n    def azure_region(self):\n        return self._settings[\"azure_region\"]\n\n    def _update_settings(self):\n        api_dialog = SettingsDialog()\n        if self.has_settings:\n            api_dialog.openai_api_edit.setText(self._settings[\"openai_api\"])\n            api_dialog.default_lang_edit.setCurrentText(self._settings[\"default_lang\"])\n            api_dialog.azure_api_edit.setText(self._settings[\"azure_api\"])\n            api_dialog.azure_region_edit.setText(self._settings[\"azure_region\"])\n            settings = self._settings\n        if api_dialog.exec_() == api_dialog.Accepted:\n            settings = {}\n            settings[\"openai_api\"] = api_dialog.openai_api_edit.text().strip()\n            settings[\"default_lang\"] = api_dialog.default_lang_edit.currentText()\n            settings[\"azure_api\"] = api_dialog.azure_api_edit.text().strip()\n            settings[\"azure_region\"] = api_dialog.azure_region_edit.text().strip()\n\n            with open(\"settings.json\", 'w') as f:\n                json.dump(settings, f, indent=4)\n        return settings\n    \n    def _load_settings(self):\n        # load settings\n        try:\n            with open(\"settings.json\", 'r') as f:\n                settings = json.load(f)\n            self.has_settings = True\n        except FileNotFoundError:\n            settings = self._update_settings()\n        \n        return settings\n"
  },
  {
    "path": "src/test.py",
    "content": ""
  },
  {
    "path": "src/utils.py",
    "content": "import langcodes\n\ndef lang_to_code(language):\n    if language == \"Chinese\":\n        code = \"zh-CN\"\n    elif language == \"English\":\n        code = \"en-US\"\n    elif language == \"French\":\n        code = \"fr-FR\"\n    elif language == \"Japanese\":\n        code = \"ja-JP\"\n    return code"
  },
  {
    "path": "src/view/components.py",
    "content": "from PyQt5.QtCore import pyqtSlot, Qt\nfrom PyQt5.QtGui import QTextCursor, QFont, QBrush, QColor\nfrom PyQt5.QtWidgets import QDockWidget, QTextEdit, QPushButton, QVBoxLayout, QHBoxLayout, QWidget, QLabel, QComboBox, QLineEdit, QToolBar, QAction\n\nfrom . import qt_style_sheet\n\n\n\nclass BubbleLabel(QLabel):\n    def __init__(self, parent=None, text='', color='white', alignment=Qt.AlignLeft):\n        super().__init__(parent)\n        self.setText(text)\n        self.setWordWrap(True)\n        self.setAlignment(alignment)\n        self.setStyleSheet(f'background-color: {color};  color: white;font: bold 25px Arial; padding: 25px; border-radius: 25px;')\n\n\n\n# Toolbar\n\nclass ToolBar(QToolBar):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self.author_action = QAction(\"Author\", self)\n        self.addAction(self.author_action)\n\n        self.text_vis = QAction(\"Text visibility\", self)\n        self.addAction(self.text_vis)\n\n        self.mode_selector = QComboBox(self)\n        self.mode_selector.addItems([\"high Intelligence\", \"medium Intelligence\", \"low Intelligence\"])\n        self.addWidget(self.mode_selector)\n\n        self.suggestion_action = QAction(\"Suggestion\", self)\n        self.suggestion_action.setCheckable(True)\n        self.addAction(self.suggestion_action)\n\n        self.settings_action = QAction(\"Settings\", self)\n        self.addAction(self.settings_action)\n\n\n# Suggestion Bubble\n\nclass SuggestionDockWidget(QDockWidget):\n    def __init__(self, *args, **kwargs):\n        super().__init__(\"suggestion\", *args, **kwargs)\n\n        self.suggestion_widget = QWidget(self) #set layout\n        layout = QVBoxLayout(self.suggestion_widget)\n        self.suggestion_widget.setLayout(layout)\n        self.setWidget(self.suggestion_widget)\n        \n        self.label = QLabel(self)\n        self.suggestion_widget.layout().addWidget(self.label)\n\n        self.suggestion_label = BubbleLabel(color='green')\n        self.suggestion_label_layout = QHBoxLayout()\n        self.suggestion_label_layout.addWidget(self.suggestion_label)\n\n        self.suggestion_widget.layout().addLayout(self.suggestion_label_layout)\n        # self.hide() # initial hide the suggestion\n\n\n\n# Central text window\n\nclass TextEdit(QTextEdit):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self.setReadOnly(True)\n        size_policy = self.sizePolicy()\n        size_policy.setRetainSizeWhenHidden(True)\n        self.setSizePolicy(size_policy)\n        self.setStyleSheet(qt_style_sheet.text_edit)\n    \n    @pyqtSlot()\n    def append_text(self, text, color):\n        cursor = self.textCursor()\n        cursor.movePosition(QTextCursor.End)\n        cursor.insertBlock()\n        charFormat = cursor.charFormat()\n        charFormat.setForeground(QBrush(QColor(color)))\n        font = QFont()\n        font.setPointSize(14)\n        font.setFamily(\"Arial\")\n        charFormat.setFont(font)\n        cursor.setCharFormat(charFormat)\n        cursor.insertText(text)\n        self.setTextCursor(cursor)\n        self.ensureCursorVisible()\n\n\n\n# Background input\n\nclass BackgroundInput(QLineEdit):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.setPlaceholderText(\"Enter the initial setting\")\n        self.setStyleSheet(qt_style_sheet.background_input)\n\n\n\n# Lower buttons\n\nclass LanguageBox(QComboBox):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.language_list = [\"zh-CN\", \"en-US\", \"en-GB\", \"fr-FR\", \"ja-JP\"]\n        self.addItems(self.language_list)\n        self.setStyleSheet(qt_style_sheet.language_box)\n\nclass SpeakButton(QPushButton):\n    def __init__(self, *args, **kwargs):\n        super().__init__(\"Speak\", *args, **kwargs)\n        self.setStyleSheet(qt_style_sheet.speak_button)\n\nclass ClearButton(QPushButton):\n    def __init__(self, *args, **kwargs):\n        super().__init__(\"Clear\", *args, **kwargs)\n\nclass LowerLayout(QHBoxLayout):\n    def __init__(self, parent):\n        super().__init__()\n        self.language_box = LanguageBox(parent=parent)\n        self.speak_button = SpeakButton(parent=parent)\n        self.clear_button = ClearButton(parent=parent)\n        self.addWidget(self.language_box)\n        self.addWidget(self.speak_button)\n        self.addWidget(self.clear_button)\n"
  },
  {
    "path": "src/view/controller.py",
    "content": "class Controller:\n    def __init__(self, model, view):\n        self._model = model\n        self._view = view\n        self._default_settings()\n        self._connect_signals()\n    \n    \n    # ToolBar\n    def _display_author_info(self):\n        from PyQt5.QtWidgets import QMessageBox\n        QMessageBox.information(self._view, \"Author Information\", \"Author: Bowen ZHU\\nEmail: bowen.zhu@student-cs.fr\\nContributor: Chuanqi XU\\nEmail: chuanqi.xu@yale.edu\")\n    \n    def _change_text_vis(self):\n        self._view.text_edit.setVisible(not self._view.text_edit.isVisible())\n\n    def _change_mode(self, index):\n        if index == 0:\n            self._model.respond_mod = \"text-davinci-003\"\n            self._model.sugg_mod = \"text-davinci-003\"\n        elif index == 1:\n            self._model.respond_mod = \"text-davinci-003\"\n            self._model.sugg_mod = \"text-curie-001\"\n        else:\n            self._model.respond_mod = \"text-curie-001\"\n            self._model.sugg_mod = \"text-curie-001\"\n    \n    def _change_suggestion(self):\n        self._model.is_suggestion = not self._model.is_suggestion\n        if self._model.is_suggestion:\n            self._view.suggestion_window.show()\n        else:\n            self._view.suggestion_window.hide()\n\n    def _change_settings(self):\n        self._model.settings._update_settings()\n\n\n    \n    # Background input\n    # @pyqtSlot()\n    def _update_background(self):\n        self._model.conversation = self._view.background_input.text()\n        self._model.is_background_set = True\n\n\n\n    # Lower Buttons\n\n    def _change_language(self):\n        self._model.lang_tag = self._view.lower_layout.language_box.currentText()\n\n    # @pyqtSlot()\n    def _speak(self):\n        my_paragraph, ai_respond, sugg = self._model.forward()\n        self._view.text_edit.append_text(\"You: \" + my_paragraph, \"blue\")\n        self._view.text_edit.append_text(\"AI: \" + ai_respond, \"green\")\n\n        if self._model.is_suggestion:\n            self._view.suggestion_window.suggestion_label.setText(sugg.replace('\\n', ''))\n    \n    def _clear_text(self):\n        self._model.conversation=''\n        self._model.is_background_set = False\n        self._view.text_edit.clear()\n        self._view.background_input.clear()\n        if self._model.is_suggestion:\n            self._view.suggestion_window.suggestion_label.setText(\"\")\n    \n\n\n    # Default settings when creating the objects\n    def _default_settings(self):\n        self._view.suggestion_window.hide()\n        self._view.lower_layout.language_box.setCurrentText(self._model.lang_tag)\n\n    # Connect all signals when creating the objects\n\n    def _connect_signals(self):\n        # ToolBar\n        self._view.toolbar.author_action.triggered.connect(self._display_author_info)\n        self._view.toolbar.text_vis.triggered.connect(self._change_text_vis)\n        self._view.toolbar.mode_selector.currentIndexChanged.connect(self._change_mode)\n        self._view.toolbar.suggestion_action.triggered.connect(self._change_suggestion)\n        self._view.toolbar.settings_action.triggered.connect(self._change_settings)\n\n        # Background input\n        self._view.background_input.textChanged.connect(self._update_background)\n\n        # Lower Buttons\n        self._view.lower_layout.language_box.currentIndexChanged.connect(self._change_language)\n        self._view.lower_layout.speak_button.clicked.connect(self._speak)\n        self._view.lower_layout.clear_button.clicked.connect(self._clear_text)\n\n"
  },
  {
    "path": "src/view/dialogues.py",
    "content": "from PyQt5.QtWidgets import QFormLayout, QDialog, QPushButton, QLineEdit, QComboBox\nfrom . import qt_style_sheet\n\n\nclass SettingsDialog(QDialog):\n    def __init__(self, azure_api=None, azure_region=None, openai_api=None, default_lang=None, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.setWindowTitle(\"Settings\")\n\n        self.azure_api = azure_api\n        self.azure_region = azure_region\n        self.openai_api = openai_api\n        self.default_lang = default_lang\n\n        layout = QFormLayout()\n\n        self.openai_api_edit = QLineEdit(self.openai_api)\n        layout.addRow(\"OpenAI API Key:\", self.openai_api_edit)\n\n        # self.default_lang_edit = QLineEdit(self.default_lang)\n        # layout.addRow(\"Default Language:\", self.default_lang_edit)\n        self.default_lang_edit = QComboBox(self.default_lang)\n        language_list = [\"zh-CN\", \"en-US\", \"en-GB\", \"fr-FR\", \"ja-JP\"]\n        self.default_lang_edit.addItems(language_list)\n        self.default_lang_edit.setStyleSheet(qt_style_sheet.language_box)\n        layout.addRow(\"Default Language:\", self.default_lang_edit)\n\n        self.azure_api_edit = QLineEdit(self.azure_api)\n        layout.addRow(\"Azure API Key:\", self.azure_api_edit)\n\n        self.azure_region_edit = QLineEdit(self.azure_region)\n        layout.addRow(\"Azure Region:\", self.azure_region_edit)\n\n        save_button = QPushButton(\"Save\")\n        save_button.clicked.connect(self.accept)\n        layout.addWidget(save_button)\n        self.setLayout(layout)\n"
  },
  {
    "path": "src/view/mainwindow.py",
    "content": "from PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QMainWindow, QVBoxLayout, QHBoxLayout, QWidget\n\nfrom model.chatsession import ChatSession\nfrom .components import ToolBar, SuggestionDockWidget, TextEdit, BackgroundInput, LowerLayout\n\n\n\nclass MainWindow(QMainWindow):\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self.chat_session = ChatSession()\n\n        # Size and Title\n        self.setFixedSize(800, 900)\n        self.setWindowTitle(\"ChatGPT Speaking Practice\")\n\n        # ToolBar\n        self.toolbar = ToolBar(parent=self)\n        self.addToolBar(self.toolbar)\n\n        # Suggestion Window\n        self.suggestion_window = SuggestionDockWidget()\n        self.suggestion_window.setGeometry(self.x() + self.width(), self.y(), 400, 400)\n        self.addDockWidget(Qt.TopDockWidgetArea, self.suggestion_window)\n        \n        # Create central widget, which contains:\n        #   1. text_edit\n        #   2. conversation backgound\n        #   3. lower buttons\n        self.central_widget = QWidget(parent=self)\n        self.setCentralWidget(self.central_widget)\n        \n        self.layout = QVBoxLayout()\n        self.text_edit = TextEdit(parent=self)\n        self.background_input = BackgroundInput(parent=self)\n        self.lower_layout = LowerLayout(parent=self)\n        self.layout.addWidget(self.text_edit)\n        self.layout.addWidget(self.background_input)\n        self.layout.addLayout(self.lower_layout)\n\n        self.central_widget.setLayout(self.layout)\n\n        # creat bubble\n        self.user_bubble = None\n        self.ai_bubble = None\n\n"
  },
  {
    "path": "src/view/qt_style_sheet.py",
    "content": "conversation = \"\"\"\n    QLineEdit {\n            background-color: white;\n            color: black;\n            font-size: 25px;\n            padding: 10px;\n            border: 2px solid gray;\n            border-radius: 5px;\n        }\n    \"\"\"\n\nlanguage_box = \"\"\"\n    QComboBox {\n        background-color: white;\n        color: black;\n        padding: 5px;\n        border: 1px solid gray;\n        border-radius: 3px;\n        min-width: 6em;\n    }\n    QComboBox::drop-down {\n        subcontrol-origin: padding;\n        subcontrol-position: top right;\n        width: 15px;\n        border-left-width: 1px;\n        border-left-color: darkgray;\n        border-left-style: solid;\n        border-top-right-radius: 3px;\n        border-bottom-right-radius: 3px;\n    }\n    QComboBox::down-arrow {\n        image: url(down_arrow.png);\n    }\n    QComboBox QAbstractItemView {\n        background-color: white;\n        border: 1px solid gray;\n        selection-background-color: lightgray;\n    }\n    \"\"\"\n\ntext_edit = \"\"\"\n    QTextEdit {\n        background-color: white;\n        background-image: url(/test.jpg);\n        color: black;\n        font-size: 16px;\n        padding: 10px;\n        border: 1px solid gray;\n        border-radius: 3px;\n    }\n    \"\"\"\n\nbackground_input = \"\"\"\n    QLineEdit {\n            background-color: white;\n            color: black;\n            font-size: 25px;\n            padding: 10px;\n            border: 2px solid gray;\n            border-radius: 5px;\n        }\n    \"\"\"\n\nspeak_button = \"\"\"\nQPushButton { \n    background-color: grey; \n    border-radius: 20px; \n    padding: 10px; color:white; \n    font-size:20px;\n} \nQPushButton:hover { \n    background-color: red; \n} \nQPushButton:pressed { \n    background-color: green; \n}\n\"\"\"\n"
  }
]