Spaces:
Sleeping
Sleeping
Commit
·
18c0acd
1
Parent(s):
ad4d258
chore: first commit
Browse files- .gitignore +3 -0
- .pre-commit-config.yaml +78 -0
- .streamlit/config.toml +6 -0
- CHANGELOG.md +11 -0
- LICENSE.md +157 -0
- README.md +60 -1
- docs/images/header.png +0 -0
- docs/images/logo.png +0 -0
- docs/screenshots/app_screenshot_1.png +0 -0
- docs/screenshots/app_screenshot_qa_2.png +0 -0
- docs/screenshots/app_screenshot_qa_init.png +0 -0
- exam_guides/b2_fce_speaking_img_desc.txt +31 -0
- exam_guides/b2_fce_speaking_opinion.txt +6 -0
- exam_guides/b2_fce_speaking_questions.txt +33 -0
- exam_guides/lessons.json +23 -0
- poetry.lock +0 -0
- pyproject.toml +168 -0
- reports/mypy.xml +5 -0
- src/__init__.py +0 -0
- src/config.json +7 -0
- src/main.py +190 -0
- src/models/__init__.py +0 -0
- src/models/generator.py +205 -0
- src/models/lc_base_model.py +87 -0
- src/models/lc_img_desc_model.py +109 -0
- src/models/lc_qa_model.py +181 -0
- src/models/model_factory.py +77 -0
- src/utils.py +42 -0
- src/whisper_transcription.py +89 -0
.gitignore
CHANGED
@@ -158,3 +158,6 @@ cython_debug/
|
|
158 |
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
159 |
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
160 |
#.idea/
|
|
|
|
|
|
|
|
158 |
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
159 |
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
160 |
#.idea/
|
161 |
+
|
162 |
+
reports/
|
163 |
+
.ruff_cache/
|
.pre-commit-config.yaml
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# https://pre-commit.com
|
2 |
+
default_install_hook_types: [commit-msg, pre-commit]
|
3 |
+
default_stages: [commit, manual]
|
4 |
+
fail_fast: false
|
5 |
+
repos:
|
6 |
+
- repo: https://github.com/pre-commit/pygrep-hooks
|
7 |
+
rev: v1.9.0
|
8 |
+
hooks:
|
9 |
+
- id: python-check-mock-methods
|
10 |
+
- id: python-use-type-annotations
|
11 |
+
- id: text-unicode-replacement-char
|
12 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
13 |
+
rev: v4.3.0
|
14 |
+
hooks:
|
15 |
+
- id: check-added-large-files
|
16 |
+
- id: check-ast
|
17 |
+
- id: check-case-conflict
|
18 |
+
- id: check-builtin-literals
|
19 |
+
- id: check-json
|
20 |
+
- id: check-docstring-first
|
21 |
+
- id: check-merge-conflict
|
22 |
+
- id: check-shebang-scripts-are-executable
|
23 |
+
- id: check-toml
|
24 |
+
- id: check-vcs-permalinks
|
25 |
+
- id: check-yaml
|
26 |
+
- id: debug-statements
|
27 |
+
- id: end-of-file-fixer
|
28 |
+
- id: detect-private-key
|
29 |
+
types: [python]
|
30 |
+
- id: fix-byte-order-marker
|
31 |
+
- id: mixed-line-ending
|
32 |
+
- id: no-commit-to-branch
|
33 |
+
- id: trailing-whitespace
|
34 |
+
types: [python]
|
35 |
+
- repo: https://github.com/astral-sh/ruff-pre-commit
|
36 |
+
rev: v0.0.280
|
37 |
+
hooks:
|
38 |
+
- id: ruff
|
39 |
+
name: ruff
|
40 |
+
entry: ruff check
|
41 |
+
args: []
|
42 |
+
require_serial: true
|
43 |
+
language: system
|
44 |
+
types: [python]
|
45 |
+
exclude: ^tests/
|
46 |
+
- repo: https://github.com/psf/black
|
47 |
+
rev: 23.7.0
|
48 |
+
hooks:
|
49 |
+
- id: black
|
50 |
+
name: black
|
51 |
+
entry: black
|
52 |
+
require_serial: true
|
53 |
+
language: system
|
54 |
+
types: [python]
|
55 |
+
- repo: https://github.com/python-poetry/poetry
|
56 |
+
rev: 1.5.1
|
57 |
+
hooks:
|
58 |
+
- id: poetry-check
|
59 |
+
name: poetry check
|
60 |
+
entry: poetry check
|
61 |
+
language: system
|
62 |
+
files: pyproject.toml
|
63 |
+
pass_filenames: false
|
64 |
+
- id: poetry-lock
|
65 |
+
name: poetry lock check
|
66 |
+
entry: poetry lock
|
67 |
+
args: [--check]
|
68 |
+
language: system
|
69 |
+
pass_filenames: false
|
70 |
+
- repo: https://github.com/pre-commit/mirrors-mypy
|
71 |
+
rev: v1.4.1
|
72 |
+
hooks:
|
73 |
+
- id: mypy
|
74 |
+
name: mypy
|
75 |
+
entry: mypy
|
76 |
+
language: system
|
77 |
+
types: [python]
|
78 |
+
exclude: ^tests/
|
.streamlit/config.toml
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[theme]
|
2 |
+
primaryColor="#f33535"
|
3 |
+
backgroundColor="#33425b"
|
4 |
+
secondaryBackgroundColor="#212a3a"
|
5 |
+
textColor="#d8e9f0"
|
6 |
+
font="sans serif"
|
CHANGELOG.md
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Changelog
|
2 |
+
|
3 |
+
All notable changes to this project will be documented in this file.
|
4 |
+
|
5 |
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
6 |
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
7 |
+
|
8 |
+
|
9 |
+
## [0.1.0] - 2024-04-09
|
10 |
+
|
11 |
+
- First commit
|
LICENSE.md
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Attribution-NonCommercial-NoDerivatives 4.0 International
|
2 |
+
|
3 |
+
> *Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.*
|
4 |
+
>
|
5 |
+
> ### Using Creative Commons Public Licenses
|
6 |
+
>
|
7 |
+
> Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
|
8 |
+
>
|
9 |
+
> * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
|
10 |
+
>
|
11 |
+
> * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
|
12 |
+
|
13 |
+
## Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License
|
14 |
+
|
15 |
+
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
|
16 |
+
|
17 |
+
### Section 1 – Definitions.
|
18 |
+
|
19 |
+
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
|
20 |
+
|
21 |
+
b. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
|
22 |
+
|
23 |
+
e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
|
24 |
+
|
25 |
+
f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
|
26 |
+
|
27 |
+
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
28 |
+
|
29 |
+
i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
|
30 |
+
|
31 |
+
h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
|
32 |
+
|
33 |
+
i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
|
34 |
+
|
35 |
+
j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
|
36 |
+
|
37 |
+
k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
|
38 |
+
|
39 |
+
l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
|
40 |
+
|
41 |
+
### Section 2 – Scope.
|
42 |
+
|
43 |
+
a. ___License grant.___
|
44 |
+
|
45 |
+
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
|
46 |
+
|
47 |
+
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
|
48 |
+
|
49 |
+
B. produce and reproduce, but not Share, Adapted Material for NonCommercial purposes only.
|
50 |
+
|
51 |
+
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
|
52 |
+
|
53 |
+
3. __Term.__ The term of this Public License is specified in Section 6(a).
|
54 |
+
|
55 |
+
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
|
56 |
+
|
57 |
+
5. __Downstream recipients.__
|
58 |
+
|
59 |
+
A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
|
60 |
+
|
61 |
+
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
|
62 |
+
|
63 |
+
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
|
64 |
+
|
65 |
+
b. ___Other rights.___
|
66 |
+
|
67 |
+
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
|
68 |
+
|
69 |
+
2. Patent and trademark rights are not licensed under this Public License.
|
70 |
+
|
71 |
+
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
|
72 |
+
|
73 |
+
### Section 3 – License Conditions.
|
74 |
+
|
75 |
+
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
76 |
+
|
77 |
+
a. ___Attribution.___
|
78 |
+
|
79 |
+
1. If You Share the Licensed Material, You must:
|
80 |
+
|
81 |
+
A. retain the following if it is supplied by the Licensor with the Licensed Material:
|
82 |
+
|
83 |
+
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
|
84 |
+
|
85 |
+
ii. a copyright notice;
|
86 |
+
|
87 |
+
iii. a notice that refers to this Public License;
|
88 |
+
|
89 |
+
iv. a notice that refers to the disclaimer of warranties;
|
90 |
+
|
91 |
+
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
92 |
+
|
93 |
+
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
94 |
+
|
95 |
+
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
|
96 |
+
|
97 |
+
For the avoidance of doubt, You do not have permission under this Public License to Share Adapted Material.
|
98 |
+
|
99 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
|
100 |
+
|
101 |
+
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
|
102 |
+
|
103 |
+
### Section 4 – Sui Generis Database Rights.
|
104 |
+
|
105 |
+
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
106 |
+
|
107 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only and provided You do not Share Adapted Material;
|
108 |
+
|
109 |
+
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
|
110 |
+
|
111 |
+
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
|
112 |
+
|
113 |
+
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
|
114 |
+
|
115 |
+
### Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
116 |
+
|
117 |
+
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
|
118 |
+
|
119 |
+
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
|
120 |
+
|
121 |
+
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
|
122 |
+
|
123 |
+
### Section 6 – Term and Termination.
|
124 |
+
|
125 |
+
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
|
126 |
+
|
127 |
+
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
128 |
+
|
129 |
+
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
130 |
+
|
131 |
+
2. upon express reinstatement by the Licensor.
|
132 |
+
|
133 |
+
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
|
134 |
+
|
135 |
+
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
|
136 |
+
|
137 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
|
138 |
+
|
139 |
+
### Section 7 – Other Terms and Conditions.
|
140 |
+
|
141 |
+
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
142 |
+
|
143 |
+
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
|
144 |
+
|
145 |
+
### Section 8 – Interpretation.
|
146 |
+
|
147 |
+
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
|
148 |
+
|
149 |
+
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
|
150 |
+
|
151 |
+
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
|
152 |
+
|
153 |
+
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
|
154 |
+
|
155 |
+
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
|
156 |
+
>
|
157 |
+
> Creative Commons may be contacted at [creativecommons.org](http://creativecommons.org).
|
README.md
CHANGED
@@ -1 +1,60 @@
|
|
1 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# LinguAIcoach
|
2 |
+
|
3 |
+
<img src="./docs/images/header.png" alt="LingAIcoach" width="1000" style="display: block; margin: 0 auto"/>
|
4 |
+
|
5 |
+
|
6 |
+
## Description
|
7 |
+
LinguAIcoach is a project that helps to improve your English with the assistance of AI. It provides tools for practicing, testing, and learning English using AI chatbots and other language processing technologies. The LinguAIcoach project utilizes DALL-E, GPT-4V, Whisper and GPT models to enhance English language learning in a multimodal way. The project offers a variety of exercises to enhance your English skills. The exercises cover different types of exams.
|
8 |
+
|
9 |
+
At this moment, First Cambridge Exam (FCE) has been the reference exam used for the proposed exercises. In particular, speaking exercises have been adapted to a chatbot environment.
|
10 |
+
- B2 - FCE: Speaking QA: This covers questions answering exercises of Speaking in B2 - FCE.
|
11 |
+
- B2 - FCE: Speaking Img Desc: This covers image description exercises in B2 - FCE.
|
12 |
+
- B2 - FCE: Speaking Opinion: This covers opinion question exercises in B2 - FCE.
|
13 |
+
|
14 |
+
Each exercise is designed to help you practice and improve your English skills in specific areas. The exercises are based on real-life exam questions and provide a hands-on experience to help you improve your English proficiency.
|
15 |
+
|
16 |
+
The input can be inserted either through text input or voice input which will be processed with Whisper to get its transcription.
|
17 |
+
|
18 |
+
After answering, the response will be evaluated based on its grammar syntaxis and complexity and the following fields will be returned:
|
19 |
+
- Evaluation: This field summarizes the evaluation of the response. This is where it is detailed how well the response matches the expected criteria.
|
20 |
+
- Tips: Provides tips about complexity and detailed mistakes correction. This is where you can give guidance on how to improve responses or correct mistakes.
|
21 |
+
- Example: This field provides an example of a response. It showcases how an ideal response should look like.
|
22 |
+
|
23 |
+
### Question Answering Exercises Example
|
24 |
+
<img src="./docs/screenshots/app_screenshot_qa_init.png" alt="QA Exercise" width="500" style="display: block; margin: 0 auto"/>
|
25 |
+
|
26 |
+
### Image Description Exercises Example
|
27 |
+
<img src="./docs/screenshots/app_screenshot_1.png" alt="Img Desc Exercise" width="500" style="display: block; margin: 0 auto"/>
|
28 |
+
|
29 |
+
## Local Installation
|
30 |
+
To install this project, you will need to have Python 3.11, Poetry and poethepoet installed. Then, you can clone the repository and run `poe setup` to install the required dependencies.
|
31 |
+
|
32 |
+
If you would like to use langsmith with this project I recommend you to create a .env file with the following values:
|
33 |
+
```
|
34 |
+
LANGCHAIN_API_KEY="your-langsmith-api-key"
|
35 |
+
LANGCHAIN_TRACING_V2=true
|
36 |
+
LANGCHAIN_ENDPOINT="https://api.smith.langchain.com"
|
37 |
+
LANGCHAIN_PROJECT="your-project-name-from-langsmith"
|
38 |
+
OPENAI_API_KEY="your-openai-api-key"
|
39 |
+
```
|
40 |
+
|
41 |
+
After installing the project, you can run the main application using the command `poe start`. This will start the Streamlit application, which provides a user interface for interacting with the AI English teacher.
|
42 |
+
|
43 |
+
## Usage
|
44 |
+
You will need to provide an [OpenAI API Key](https://platform.openai.com/account/api-keys) in the interface or in the .env file like explained above.
|
45 |
+
|
46 |
+
Exercises are defined in exam_guides/lessons.json file. The amount of exercises will be expanded in future releases. The .txt files in exam_guides are examples of what it is expected in each kind of exercise. In future releases this will be used for generating examples for reference in Langchain.
|
47 |
+
|
48 |
+
## Contributing
|
49 |
+
If you would like to contribute to this project, please fork the repository, make your changes, and submit a pull request. Your contributions are welcome!
|
50 |
+
|
51 |
+
## License
|
52 |
+
This project is licensed under the CC-BY-NC-ND-4.0 license. See the [LICENSE.md](LICENSE.md) file for more details.
|
53 |
+
|
54 |
+
## Authors
|
55 |
+
- [alvaroalon2](https://github.com/alvaroalon2)
|
56 |
+
|
57 |
+
## Next Steps
|
58 |
+
- New kind of exercises.
|
59 |
+
- Guide content generation using examples extracted from real exams.
|
60 |
+
- Testing
|
docs/images/header.png
ADDED
![]() |
docs/images/logo.png
ADDED
![]() |
docs/screenshots/app_screenshot_1.png
ADDED
![]() |
docs/screenshots/app_screenshot_qa_2.png
ADDED
![]() |
docs/screenshots/app_screenshot_qa_init.png
ADDED
![]() |
exam_guides/b2_fce_speaking_img_desc.txt
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
- competition
|
2 |
+
- communication
|
3 |
+
- culture and customs
|
4 |
+
- daily life
|
5 |
+
- education
|
6 |
+
- entertainment and media
|
7 |
+
- environmental issues
|
8 |
+
- family and friends
|
9 |
+
- fashion
|
10 |
+
- feelings and emotions
|
11 |
+
- food and drink
|
12 |
+
- free time activities
|
13 |
+
- health, medicine and fitness
|
14 |
+
- hobbies and leisure
|
15 |
+
- house and home
|
16 |
+
- money
|
17 |
+
- obligations
|
18 |
+
- places and buildings
|
19 |
+
- relations with other people
|
20 |
+
- science and technology
|
21 |
+
- shopping
|
22 |
+
- social interaction
|
23 |
+
- society
|
24 |
+
- sport
|
25 |
+
- technology
|
26 |
+
- the natural world
|
27 |
+
- time
|
28 |
+
- transport
|
29 |
+
- travel and holidays
|
30 |
+
- weather
|
31 |
+
- work and jobs
|
exam_guides/b2_fce_speaking_opinion.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
- Do you think you have to spend a lot of money to have a good holiday? ... why? why not?
|
2 |
+
- Some people say we travel too much these days and should not go on so many holidays. Do you agree?
|
3 |
+
- What do you thinh is the biggest advantage of living in a place where there are a lot of tourists?
|
4 |
+
- What can people do to have a good holiday in yours country? ... (Why?)
|
5 |
+
- why do you think people like to go away on holiday?
|
6 |
+
- Do you think computers will replace newspapers and TV in the future?
|
exam_guides/b2_fce_speaking_questions.txt
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
- Could you tell me something about the area where you grew up? ... What did you like about living there?
|
2 |
+
- How much time do you spend at home nowadays?
|
3 |
+
- What do you most enjoy doing when you’re at home?
|
4 |
+
- Could you describe your family home to me?
|
5 |
+
- Who are the most important people in your life?
|
6 |
+
- Do you and your friends share the same ideas?
|
7 |
+
- Tell me about your best friend.
|
8 |
+
- What's the most exciting thing you've ever done?
|
9 |
+
- Is there anything you’d love to be able to do in the future?
|
10 |
+
- What's your favourite day of the week? ... Why?
|
11 |
+
- Can you remember your first English lessons? ... What were they like?
|
12 |
+
- What do you think were the most important things you learned at primary / elementary school?
|
13 |
+
- Do you plan to study anything in the future?
|
14 |
+
- Would you prefer to work for a big or a small company? ... Why?
|
15 |
+
- What do you think would be the most interesting job to do?
|
16 |
+
- Do you like reading books? ... What sort of books do you enjoy reading most?
|
17 |
+
- What sports do people play most in your country? ... And what do people enjoy watching?
|
18 |
+
- Is it easy to meet new people where you live?
|
19 |
+
- Do you normally go out with family or friends?
|
20 |
+
- What do you enjoy doing with your friends?
|
21 |
+
- Where's the best place to spend a free afternoon around here/in your town?
|
22 |
+
- How expensive is it to go out in the evening where you live?
|
23 |
+
- Do you like going to the cinema?
|
24 |
+
- Tell me about your favourite filmstar.
|
25 |
+
- What are you going to do this weekend?
|
26 |
+
- How do you find out what's happening in the world?
|
27 |
+
- Do you ever listen to the radio? ... What programmes do you like?
|
28 |
+
- How important is TV to you?
|
29 |
+
- Do you like the same TV programmes as your parents?
|
30 |
+
- How do you prefer to travel, by train or plane? ... Why's that?
|
31 |
+
- What's the longest journey you've ever been on?
|
32 |
+
- What's public transport like in your country?
|
33 |
+
- Where did you spend your last holiday? ... What did you do?
|
exam_guides/lessons.json
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"B2 - FCE: Speaking - Questions": {
|
3 |
+
"file": "exam_guides/b2_fce_speaking_questions.txt",
|
4 |
+
"level": "B2",
|
5 |
+
"type": "qa",
|
6 |
+
"description": "This covers questions answering exercises of Speaking in B2 - FCE. General questions about a bunch of topics in B2 FCE exam which force the user to answer personal questions. Do not make any opinion questions.",
|
7 |
+
"init_prompt": "Hi! This is your AI English teacher, some B2 FCE exam like questions will be evaluated."
|
8 |
+
},
|
9 |
+
"B2 - FCE: Speaking 2 - Image Description": {
|
10 |
+
"file": "exam_guides/b2_fce_speaking_img_desc.txt",
|
11 |
+
"level": "B2",
|
12 |
+
"type": "img_desc",
|
13 |
+
"description": "This covers image description Speaking exercises in B2 - FCE. Just images which force the user to describe an image in B2 FCE exam.",
|
14 |
+
"init_prompt": "Hi! This is your AI English teacher, some descriptions about iamges which could be found in B2 FCE exam will be evaluated."
|
15 |
+
},
|
16 |
+
"B2 - FCE: Speaking 3 - Opinion": {
|
17 |
+
"file": "exam_guides/b2_fce_speaking_opinion.txt",
|
18 |
+
"level": "B2",
|
19 |
+
"type": "qa",
|
20 |
+
"description": "This covers opinion question exercises in B2 - FCE english exam. Just questions which force you to evaluate your opinion in B2 FCE exam.",
|
21 |
+
"init_prompt": "Hi! This is your AI English teacher, some statements and questions will be made in order to evaluate your opinion in B2 FCE exam."
|
22 |
+
}
|
23 |
+
}
|
poetry.lock
ADDED
The diff for this file is too large to render.
See raw diff
|
|
pyproject.toml
ADDED
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[tool.poetry]
|
2 |
+
name = "LinguAIcoach"
|
3 |
+
version = "0.1.0"
|
4 |
+
description = "Help to improve your English with AI"
|
5 |
+
authors = ["alvaroalon2"]
|
6 |
+
readme = "README.md"
|
7 |
+
license = "LICENSE.md"
|
8 |
+
|
9 |
+
homepage = "https://github.com/alvaroalon2"
|
10 |
+
repository = "https://github.com/alvaroalon2/LinguAIcoach"
|
11 |
+
classifiers = [
|
12 |
+
'Development Status :: 2 - Pre-Alpha',
|
13 |
+
"Operating System :: Unix",
|
14 |
+
"Programming Language :: Python :: 3.12",
|
15 |
+
]
|
16 |
+
|
17 |
+
packages = [{ include = "src" }]
|
18 |
+
|
19 |
+
[build-system]
|
20 |
+
requires = ["poetry-core"]
|
21 |
+
build-backend = "poetry.core.masonry.api"
|
22 |
+
|
23 |
+
[tool.poetry.dependencies]
|
24 |
+
python = "^3.12"
|
25 |
+
langchain = "^0.1.12"
|
26 |
+
langchain-openai = "^0.0.6"
|
27 |
+
openai = "^1.12.0"
|
28 |
+
streamlit = "^1.31.1"
|
29 |
+
streamlit-mic-recorder = "*"
|
30 |
+
streamlit-extras = "*"
|
31 |
+
|
32 |
+
|
33 |
+
[tool.poetry.group.dev.dependencies]
|
34 |
+
boto3 = "*"
|
35 |
+
poethepoet = "*"
|
36 |
+
langsmith = "*"
|
37 |
+
black = "*"
|
38 |
+
pylint = "*"
|
39 |
+
bandit = "*"
|
40 |
+
ruff = ">=0.0.270"
|
41 |
+
isort = ">=5.10.1"
|
42 |
+
mypy = ">=1.3.0"
|
43 |
+
mkdocstrings = {version = ">=0.24.0", extras = ["python"]}
|
44 |
+
mkdocs = ">=1.5.3"
|
45 |
+
mkdocs-markdownextradata-plugin = ">=0.2.5"
|
46 |
+
mkdocs-material = ">=9.5.2"
|
47 |
+
mkdocs-minify-plugin = ">=0.7.2"
|
48 |
+
pymdown-extensions = ">=10.5"
|
49 |
+
pre-commit = ">=3.3.1"
|
50 |
+
|
51 |
+
[tool.poe]
|
52 |
+
envfile = ".env"
|
53 |
+
|
54 |
+
|
55 |
+
[tool.poe.tasks]
|
56 |
+
start = "python3 -m streamlit run src/main.py"
|
57 |
+
check = ["pylint", "bandit"]
|
58 |
+
setup = ["install", "install-precommit"]
|
59 |
+
|
60 |
+
[tool.poe.tasks.lint]
|
61 |
+
help = "Lint this package"
|
62 |
+
|
63 |
+
[[tool.poe.tasks.lint.sequence]]
|
64 |
+
cmd = """
|
65 |
+
pre-commit run
|
66 |
+
--all-files
|
67 |
+
--color always
|
68 |
+
"""
|
69 |
+
|
70 |
+
[tool.poe.tasks.install-precommit]
|
71 |
+
help = "Installing precommit hooks"
|
72 |
+
cmd = "poetry run pre-commit install"
|
73 |
+
|
74 |
+
[tool.poe.tasks.precommit]
|
75 |
+
help = "Run precommit checks on all project files"
|
76 |
+
cmd = "poetry run pre-commit run --all-files"
|
77 |
+
|
78 |
+
|
79 |
+
|
80 |
+
[tool.poe.tasks.pylint]
|
81 |
+
help = "Pass linter rules"
|
82 |
+
cmd = "ruff check --exit-zero src/"
|
83 |
+
|
84 |
+
[tool.poe.tasks.ci-pylint]
|
85 |
+
help = "Pass linter rules"
|
86 |
+
cmd = "ruff check --output-format pylint --output-file reports/pylint.txt --exit-zero src/"
|
87 |
+
|
88 |
+
[tool.poe.tasks.bandit]
|
89 |
+
help = "Find security issues!"
|
90 |
+
cmd = "bandit -r src"
|
91 |
+
|
92 |
+
[tool.poe.tasks.ci-bandit]
|
93 |
+
help = "Generate security report"
|
94 |
+
cmd = "bandit -r src -f json -o reports/bandit.json"
|
95 |
+
|
96 |
+
|
97 |
+
|
98 |
+
[tool.poe.tasks.install]
|
99 |
+
help = "Installing project (including dev dependencies)"
|
100 |
+
cmd = "poetry install --sync"
|
101 |
+
|
102 |
+
[tool.poe.tasks.install-nodev]
|
103 |
+
help = "Installing project (no dev dependencies)"
|
104 |
+
cmd = "poetry install --without dev"
|
105 |
+
|
106 |
+
[tool.poe.tasks.build]
|
107 |
+
help = "Build project's wheel"
|
108 |
+
cmd = "poetry build -f wheel"
|
109 |
+
|
110 |
+
[tool.poe.tasks.build_src]
|
111 |
+
help = "Build project's sdist"
|
112 |
+
cmd = "poetry build -f sdist"
|
113 |
+
|
114 |
+
|
115 |
+
[tool.poe.tasks.docs-build]
|
116 |
+
help = "Build MKdocs documentation"
|
117 |
+
cmd = "mkdocs build --clean"
|
118 |
+
|
119 |
+
[tool.poe.tasks.docs-serve]
|
120 |
+
help = "Start the development doc server"
|
121 |
+
cmd = "mkdocs serve"
|
122 |
+
|
123 |
+
[tool.poe.tasks.publish-ghdocs]
|
124 |
+
help = "Build and deploy the documentation to the gh-pages branch"
|
125 |
+
cmd = "mkdocs gh-deploy --clean --force"
|
126 |
+
|
127 |
+
|
128 |
+
[tool.isort]
|
129 |
+
profile = "black"
|
130 |
+
multi_line_output = 3
|
131 |
+
include_trailing_comma = true
|
132 |
+
force_grid_wrap = 0
|
133 |
+
use_parentheses = true
|
134 |
+
line_length = 120
|
135 |
+
|
136 |
+
[tool.black]
|
137 |
+
line-length = 120
|
138 |
+
include = '\.pyi?$'
|
139 |
+
|
140 |
+
[tool.mypy]
|
141 |
+
strict = true
|
142 |
+
disallow_subclassing_any = false
|
143 |
+
disallow_untyped_decorators = false
|
144 |
+
ignore_missing_imports = true
|
145 |
+
pretty = true
|
146 |
+
show_column_numbers = true
|
147 |
+
show_error_codes = true
|
148 |
+
show_error_context = true
|
149 |
+
warn_unreachable = true
|
150 |
+
warn_return_any = false
|
151 |
+
|
152 |
+
[tool.ruff]
|
153 |
+
fix = true
|
154 |
+
lint.ignore-init-module-imports = true
|
155 |
+
line-length = 120
|
156 |
+
lint.select = ["A", "B", "C4", "C90", "DTZ", "E", "F", "I", "ISC", "N", "NPY", "PGH", "PIE", "PLC", "PLE", "PLR", "PLW", "PT", "RET", "RUF", "RSE", "SIM", "TID", "UP", "W", "YTT"]
|
157 |
+
lint.ignore = ["E501", "PGH001", "PGH002", "PGH003", "RET504", "S101"]
|
158 |
+
lint.unfixable = ["F401", "F841"]
|
159 |
+
src = ["src"]
|
160 |
+
|
161 |
+
[tool.ruff.lint.flake8-tidy-imports]
|
162 |
+
ban-relative-imports = "all"
|
163 |
+
|
164 |
+
[tool.ruff.lint.pydocstyle]
|
165 |
+
convention = "numpy"
|
166 |
+
|
167 |
+
[tool.ruff.lint.pylint]
|
168 |
+
max-args = 9
|
reports/mypy.xml
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="utf-8"?>
|
2 |
+
<testsuite errors="0" failures="0" name="mypy" skips="0" tests="1" time="0.416">
|
3 |
+
<testcase classname="mypy" file="mypy" line="1" name="mypy-py3_12-darwin" time="0.416">
|
4 |
+
</testcase>
|
5 |
+
</testsuite>
|
src/__init__.py
ADDED
File without changes
|
src/config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"N_MAX_HISTORY": 20,
|
3 |
+
"N_MAX_RETRY": 3,
|
4 |
+
"OPENAI_TEMPERATURE_GEN": 0.8,
|
5 |
+
"OPENAI_TEMPERATURE_EVAL": 0.3,
|
6 |
+
"IMG_GEN_SIZE": "256x256"
|
7 |
+
}
|
src/main.py
ADDED
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import os
|
3 |
+
|
4 |
+
import streamlit as st
|
5 |
+
from langchain.schema import AIMessage, HumanMessage
|
6 |
+
from langchain_core.pydantic_v1 import SecretStr
|
7 |
+
|
8 |
+
from src.models.model_factory import EvaluationChatModelFactory, GeneratorModelFactory
|
9 |
+
from src.utils import convert_json_to_str, read_json, read_plain_text
|
10 |
+
from src.whisper_transcription import whisper_stt
|
11 |
+
|
12 |
+
logging.basicConfig(level=os.getenv("ENV", "INFO"))
|
13 |
+
|
14 |
+
start_container = st.container()
|
15 |
+
with start_container:
|
16 |
+
col1_head, col2_head = st.columns([0.15, 0.85])
|
17 |
+
|
18 |
+
col1_head.image("./docs/images/logo.png", width=80)
|
19 |
+
col2_head.title("LinguAIcoach")
|
20 |
+
|
21 |
+
st.subheader("_Your :red[AI] English Teacher_")
|
22 |
+
st.divider()
|
23 |
+
|
24 |
+
|
25 |
+
model_factory = EvaluationChatModelFactory()
|
26 |
+
gen_factory = GeneratorModelFactory()
|
27 |
+
exam_guides = read_json("./exam_guides/lessons.json")
|
28 |
+
config = read_json("./src/config.json")
|
29 |
+
|
30 |
+
input_text = None
|
31 |
+
input_voice = None
|
32 |
+
|
33 |
+
with st.sidebar as sidebar:
|
34 |
+
exam_selection = st.sidebar.selectbox("Select Exam type", list(exam_guides.keys()))
|
35 |
+
exam_selection = exam_selection if exam_selection else str(next(iter(exam_guides.keys())))
|
36 |
+
exam_info = exam_guides[exam_selection]
|
37 |
+
st.session_state.openai_api_key = SecretStr(
|
38 |
+
os.getenv(
|
39 |
+
"OPENAI_API_KEY",
|
40 |
+
st.text_input("OpenAI API Key", key="chatbot_api_key", type="password"),
|
41 |
+
)
|
42 |
+
)
|
43 |
+
|
44 |
+
st.markdown("[:red[Get your OpenAI API key]](https://platform.openai.com/account/api-keys)")
|
45 |
+
st.markdown(
|
46 |
+
"[](https://github.com/alvaroalon2/LinguAIcoach)"
|
47 |
+
)
|
48 |
+
|
49 |
+
logging.debug(f"Selected exam: {exam_selection}")
|
50 |
+
logging.debug(f"Exam guides: {exam_guides}")
|
51 |
+
|
52 |
+
exam_content = read_plain_text(exam_info["file"])
|
53 |
+
exam_desc = exam_info["description"]
|
54 |
+
init_prompt = exam_info["init_prompt"]
|
55 |
+
level = exam_info["level"]
|
56 |
+
|
57 |
+
if "current_exam" not in st.session_state:
|
58 |
+
st.session_state["current_exam"] = ""
|
59 |
+
if st.session_state["current_exam"] != exam_selection:
|
60 |
+
logging.debug("Resetting state")
|
61 |
+
input_text = None
|
62 |
+
input_voice = None
|
63 |
+
st.session_state["current_exam"] = exam_selection
|
64 |
+
st.session_state["messages"] = [AIMessage(content=init_prompt)]
|
65 |
+
st.session_state.first_run = True
|
66 |
+
st.session_state["image_url"] = None
|
67 |
+
st.session_state["question"] = []
|
68 |
+
st.session_state["exam_type"] = exam_info["type"]
|
69 |
+
|
70 |
+
response_container = st.container()
|
71 |
+
start_container = st.container()
|
72 |
+
with start_container:
|
73 |
+
col1_start, col2_start, col3_start = st.columns([0.4, 0.2, 0.4])
|
74 |
+
voice_container = st.container()
|
75 |
+
with voice_container:
|
76 |
+
col1_voice, col2_voice, col3_voice = st.columns([0.39, 0.22, 0.39])
|
77 |
+
|
78 |
+
if not st.session_state.openai_api_key:
|
79 |
+
logging.warning("Please add your OpenAI API key to continue.")
|
80 |
+
st.info("Please add your OpenAI API key to continue.")
|
81 |
+
st.stop()
|
82 |
+
|
83 |
+
model_eval = model_factory.create_model(
|
84 |
+
model_class=st.session_state["exam_type"],
|
85 |
+
openai_api_key=st.session_state.openai_api_key,
|
86 |
+
level=level,
|
87 |
+
chat_temperature=config["OPENAI_TEMPERATURE_EVAL"],
|
88 |
+
)
|
89 |
+
|
90 |
+
generator = gen_factory.create_model(
|
91 |
+
model_class=st.session_state["exam_type"],
|
92 |
+
openai_api_key=st.session_state.openai_api_key,
|
93 |
+
exam_prompt=exam_content,
|
94 |
+
level=level,
|
95 |
+
description=exam_desc,
|
96 |
+
chat_temperature=config["OPENAI_TEMPERATURE_GEN"],
|
97 |
+
history_chat=[
|
98 |
+
AIMessage(content=f"Previous question (Don't repeat): {q.content}")
|
99 |
+
for q in st.session_state["question"][-config["N_MAX_HISTORY"] :]
|
100 |
+
],
|
101 |
+
img_size=config["IMG_GEN_SIZE"],
|
102 |
+
)
|
103 |
+
|
104 |
+
if "messages" in st.session_state:
|
105 |
+
logging.debug(f"Starting exercises for exam_type: {st.session_state['exam_type']}")
|
106 |
+
placeholder_start = col2_start.empty()
|
107 |
+
start_button = placeholder_start.button("Start exercises!", disabled=not (st.session_state.first_run))
|
108 |
+
if start_button:
|
109 |
+
logging.debug("Start button clicked, running exercise")
|
110 |
+
st.session_state.first_run = False
|
111 |
+
if st.session_state["exam_type"] == "qa":
|
112 |
+
start_response = generator.generate()
|
113 |
+
logging.info(f"Generated first question: {start_response}")
|
114 |
+
st.session_state["question"].append(AIMessage(content=start_response))
|
115 |
+
st.session_state["messages"].append(st.session_state["question"][-1])
|
116 |
+
elif st.session_state["exam_type"] == "img_desc":
|
117 |
+
st.session_state["image_url"] = generator.generate()
|
118 |
+
logging.debug(f"Generated first image URL: {st.session_state['image_url']}")
|
119 |
+
st.session_state["messages"].append(
|
120 |
+
AIMessage(
|
121 |
+
content=st.session_state["image_url"],
|
122 |
+
response_metadata={"type": "image"},
|
123 |
+
)
|
124 |
+
)
|
125 |
+
|
126 |
+
if not st.session_state.first_run:
|
127 |
+
placeholder_start.empty()
|
128 |
+
|
129 |
+
for msg in st.session_state.messages:
|
130 |
+
if isinstance(msg, HumanMessage):
|
131 |
+
if getattr(msg, "response_metadata", None) and msg.response_metadata["type"] == "image":
|
132 |
+
with response_container.chat_message("user"):
|
133 |
+
response_container.image(str(msg.content), caption="AI generated image")
|
134 |
+
else:
|
135 |
+
response_container.chat_message("user").write(msg.content)
|
136 |
+
elif getattr(msg, "response_metadata", None) and msg.response_metadata["type"] == "image":
|
137 |
+
with response_container.chat_message("assistant"):
|
138 |
+
response_container.write("Describe what you can see in the following image: ")
|
139 |
+
response_container.image(msg.content, caption="AI generated image")
|
140 |
+
else:
|
141 |
+
response_container.chat_message("assistant").write(msg.content)
|
142 |
+
|
143 |
+
placeholder_input = st.empty()
|
144 |
+
if st.session_state.first_run:
|
145 |
+
placeholder_input.empty()
|
146 |
+
col2_voice.empty()
|
147 |
+
else:
|
148 |
+
input_text = placeholder_input.chat_input(disabled=st.session_state.first_run) or None
|
149 |
+
logging.debug(f"Input text: {input_text}")
|
150 |
+
with col2_voice:
|
151 |
+
input_voice = whisper_stt(language="en", n_max_retry=config["N_MAX_RETRY"])
|
152 |
+
logging.debug(f"Input voice: {input_voice}")
|
153 |
+
|
154 |
+
input_prompt = input_text or input_voice
|
155 |
+
|
156 |
+
if input_prompt := input_text or input_voice:
|
157 |
+
logging.info(f"Processing input: {input_prompt}")
|
158 |
+
|
159 |
+
match st.session_state["exam_type"]:
|
160 |
+
case "qa":
|
161 |
+
response = model_eval.predict(input_prompt, st.session_state["question"][-1].content)
|
162 |
+
logging.info(f"QA model response: {response}")
|
163 |
+
case "img_desc":
|
164 |
+
response = model_eval.predict(input_prompt, st.session_state["image_url"])
|
165 |
+
logging.info(f"Image description model response: {response}")
|
166 |
+
|
167 |
+
response_str = convert_json_to_str(response)
|
168 |
+
|
169 |
+
with response_container:
|
170 |
+
st.session_state.messages.append(HumanMessage(content=input_prompt))
|
171 |
+
logging.debug(f"Adding user message to session state: {input_prompt}")
|
172 |
+
response_container.chat_message("user").write(input_prompt)
|
173 |
+
|
174 |
+
st.session_state.messages.append(AIMessage(content=response_str))
|
175 |
+
logging.debug(f"Adding AI message to session state: {response_str}")
|
176 |
+
response_container.chat_message("assistant").write(response_str)
|
177 |
+
if st.session_state["exam_type"] == "qa":
|
178 |
+
new_question = generator.generate()
|
179 |
+
logging.info(f"Generated new question: {new_question}")
|
180 |
+
st.session_state["question"].append(AIMessage(content=new_question))
|
181 |
+
st.session_state.messages.append(AIMessage(content=new_question))
|
182 |
+
response_container.chat_message("assistant").write(new_question)
|
183 |
+
elif st.session_state["exam_type"] == "img_desc":
|
184 |
+
new_image = generator.generate()
|
185 |
+
st.session_state["image_url"] = new_image
|
186 |
+
st.session_state.messages.append(AIMessage(content=new_image))
|
187 |
+
logging.info(f"Generated new image URL: {st.session_state['image_url']}")
|
188 |
+
response_container.chat_message("assistant").write("Describe what you can see in the following image: ")
|
189 |
+
with response_container.chat_message("assistant"):
|
190 |
+
response_container.image(st.session_state["image_url"], caption="AI generated image")
|
src/models/__init__.py
ADDED
File without changes
|
src/models/generator.py
ADDED
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from operator import itemgetter
|
2 |
+
from typing import Any, List, Type
|
3 |
+
|
4 |
+
from langchain.memory import ChatMessageHistory, ConversationBufferWindowMemory
|
5 |
+
from langchain.output_parsers import PydanticOutputParser
|
6 |
+
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder, PromptTemplate
|
7 |
+
from langchain.schema import AIMessage, HumanMessage
|
8 |
+
from langchain_community.utilities.dalle_image_generator import DallEAPIWrapper
|
9 |
+
from langchain_core.output_parsers import StrOutputParser
|
10 |
+
from langchain_core.pydantic_v1 import BaseModel, Field, SecretStr
|
11 |
+
from langchain_core.runnables import Runnable, RunnableLambda, RunnablePassthrough
|
12 |
+
from langchain_openai import OpenAI
|
13 |
+
|
14 |
+
from src.models.lc_base_model import ContentGenerator
|
15 |
+
|
16 |
+
|
17 |
+
class QuestionGenerator(ContentGenerator):
|
18 |
+
class Question(BaseModel):
|
19 |
+
question: str = Field(alias="Question", description="A question based on the given guidelines")
|
20 |
+
|
21 |
+
def __init__(
|
22 |
+
self,
|
23 |
+
exam_prompt: str,
|
24 |
+
level: str,
|
25 |
+
description: str,
|
26 |
+
history_chat: List[HumanMessage | AIMessage],
|
27 |
+
openai_api_key: SecretStr,
|
28 |
+
chat_temperature: float = 0.3,
|
29 |
+
) -> None:
|
30 |
+
"""
|
31 |
+
Initializes the object with the given exam prompt, level, description, history chat, and OpenAI API key.
|
32 |
+
|
33 |
+
Parameters:
|
34 |
+
exam_prompt (str): The prompt for the exam.
|
35 |
+
level (str): The level of the exam.
|
36 |
+
description (str): The description of the exam.
|
37 |
+
history_chat (List[HumanMessage | AIMessage]): List of chat messages from history.
|
38 |
+
openai_api_key (SecretStr): The API key for OpenAI.
|
39 |
+
|
40 |
+
Returns:
|
41 |
+
None
|
42 |
+
"""
|
43 |
+
super().__init__(openai_api_key=openai_api_key, chat_temperature=chat_temperature)
|
44 |
+
self.level = level
|
45 |
+
self.exam_prompt = exam_prompt
|
46 |
+
self.description = description
|
47 |
+
self.memory = ConversationBufferWindowMemory(
|
48 |
+
chat_memory=ChatMessageHistory(messages=history_chat), return_messages=True, k=20
|
49 |
+
)
|
50 |
+
self.chain = self._create_chain()
|
51 |
+
|
52 |
+
def _get_system_prompt(self) -> ChatPromptTemplate:
|
53 |
+
prompt = ChatPromptTemplate.from_messages(
|
54 |
+
[
|
55 |
+
(
|
56 |
+
"system",
|
57 |
+
"{format_instructions}"
|
58 |
+
f"""
|
59 |
+
You are an excellent english teacher. You teach people to speak English by asking questions
|
60 |
+
to later evaluate its response.
|
61 |
+
You will do the following tasks for that purpose:
|
62 |
+
- Limit your questions to just once per interaction at a time.
|
63 |
+
- You will generate a question based on the following guidelines in order to
|
64 |
+
later evaluate the response given by the user.
|
65 |
+
- Don't repeat ANY previous question from the history.
|
66 |
+
- Don't ask too abstract or very specific questions.
|
67 |
+
- here below, some example structure questions are given. This is just a reference of
|
68 |
+
the kind of questions that is expected you provide. Feel free to ask another questions,
|
69 |
+
but always in the context of an {self.level} Speaking English exam. Remember to ask
|
70 |
+
just one question at a time and don't repeat ANY previous questions.
|
71 |
+
|
72 |
+
{self.description}
|
73 |
+
""",
|
74 |
+
),
|
75 |
+
MessagesPlaceholder(
|
76 |
+
variable_name="history",
|
77 |
+
),
|
78 |
+
(
|
79 |
+
"human",
|
80 |
+
"I'm ready to start, ask me a question. Do NOT repeat ANY previous AI questions from the history.",
|
81 |
+
),
|
82 |
+
]
|
83 |
+
)
|
84 |
+
return prompt
|
85 |
+
|
86 |
+
def _get_output_parser(self, pydantic_schema: Type[BaseModel]) -> PydanticOutputParser[Any]:
|
87 |
+
|
88 |
+
return PydanticOutputParser(pydantic_object=pydantic_schema)
|
89 |
+
|
90 |
+
def _create_chain(self) -> Runnable[Any, Any]:
|
91 |
+
response_parser = self._get_output_parser(self.Question)
|
92 |
+
|
93 |
+
memory_runable = RunnablePassthrough.assign(
|
94 |
+
history=RunnableLambda(self.memory.load_memory_variables) | itemgetter("history")
|
95 |
+
)
|
96 |
+
|
97 |
+
parsed_chain = (
|
98 |
+
memory_runable
|
99 |
+
| self._get_system_prompt().partial(format_instructions=response_parser.get_format_instructions())
|
100 |
+
| self.chat_llm
|
101 |
+
| response_parser
|
102 |
+
)
|
103 |
+
|
104 |
+
unparsed_chain = (
|
105 |
+
memory_runable
|
106 |
+
| self._get_system_prompt().partial(format_instructions="")
|
107 |
+
| self.chat_llm
|
108 |
+
| StrOutputParser()
|
109 |
+
)
|
110 |
+
|
111 |
+
chain = parsed_chain.with_fallbacks([unparsed_chain])
|
112 |
+
|
113 |
+
return chain
|
114 |
+
|
115 |
+
def generate(self) -> str:
|
116 |
+
"""
|
117 |
+
A function that generates a response by invoking a chain, adding the AI message to chat memory, and returning a question from the response.
|
118 |
+
"""
|
119 |
+
|
120 |
+
response = self.chain.invoke({})
|
121 |
+
|
122 |
+
if isinstance(response, BaseModel):
|
123 |
+
response = response.dict(by_alias=True)
|
124 |
+
response = response["Question"]
|
125 |
+
|
126 |
+
self.memory.chat_memory.add_ai_message(response)
|
127 |
+
|
128 |
+
return response
|
129 |
+
|
130 |
+
|
131 |
+
class ImgGenerator(ContentGenerator):
|
132 |
+
|
133 |
+
def __init__(
|
134 |
+
self,
|
135 |
+
exam_prompt: str,
|
136 |
+
level: str,
|
137 |
+
description: str,
|
138 |
+
openai_api_key: SecretStr,
|
139 |
+
chat_temperature: float = 0.3,
|
140 |
+
img_size: str = "256x256",
|
141 |
+
) -> None:
|
142 |
+
"""
|
143 |
+
Initializes the class with the exam prompt, level, description, OpenAI API key, and optional image size.
|
144 |
+
|
145 |
+
Parameters:
|
146 |
+
exam_prompt (str): The prompt for the exam.
|
147 |
+
level (str): The level of the exam.
|
148 |
+
description (str): Description of the exam.
|
149 |
+
openai_api_key (SecretStr): The OpenAI API key.
|
150 |
+
img_size (str, optional): The size of the image. Default is "256x256".
|
151 |
+
|
152 |
+
Returns:
|
153 |
+
None
|
154 |
+
"""
|
155 |
+
super().__init__(openai_api_key, chat_temperature)
|
156 |
+
self.level = level
|
157 |
+
self.exam_prompt = exam_prompt
|
158 |
+
self.description = description
|
159 |
+
self.dalle = DallEAPIWrapper(size=img_size, api_key=self.openai_api_key.get_secret_value()) # type: ignore[call-arg]
|
160 |
+
self.chain = self._create_chain()
|
161 |
+
|
162 |
+
def _get_system_prompt(self) -> ChatPromptTemplate:
|
163 |
+
|
164 |
+
return ChatPromptTemplate.from_messages(
|
165 |
+
[
|
166 |
+
(
|
167 |
+
"system",
|
168 |
+
f"""You will generate a short image description (one paragraph max)
|
169 |
+
which will be later used for generating an image taking into
|
170 |
+
account that this images will be used for evaluating the
|
171 |
+
user how well can describe this image in the context of
|
172 |
+
an {self.level} Speaking English exam.
|
173 |
+
|
174 |
+
{self.description}
|
175 |
+
|
176 |
+
Topics about image descriptions which can appear:
|
177 |
+
{self.exam_prompt}
|
178 |
+
""",
|
179 |
+
),
|
180 |
+
("human", "{base_input}"),
|
181 |
+
]
|
182 |
+
)
|
183 |
+
|
184 |
+
def _create_chain(self) -> Runnable[Any, Any]:
|
185 |
+
|
186 |
+
img_prompt = PromptTemplate(
|
187 |
+
input_variables=["image_desc"],
|
188 |
+
template="""You will now act as a prompt generator. I will describe an image to you, and you will create a prompt
|
189 |
+
that could be used for image-generation. The style must be realistic:
|
190 |
+
Description: {image_desc}""",
|
191 |
+
)
|
192 |
+
|
193 |
+
return (
|
194 |
+
{"image_desc": self._get_system_prompt() | self.chat_llm | StrOutputParser()}
|
195 |
+
| img_prompt
|
196 |
+
| OpenAI(temperature=0.7, api_key=self.openai_api_key)
|
197 |
+
| StrOutputParser()
|
198 |
+
)
|
199 |
+
|
200 |
+
def generate(self) -> str:
|
201 |
+
"""
|
202 |
+
Generate function to create and return an image URL based on input parameters.
|
203 |
+
"""
|
204 |
+
img_url = self.dalle.run(self.chain.invoke({"base_input": "Generate image description"})[:999])
|
205 |
+
return img_url
|
src/models/lc_base_model.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from abc import ABC, abstractmethod
|
2 |
+
from typing import Any, Dict, Type
|
3 |
+
|
4 |
+
from langchain.output_parsers import PydanticOutputParser
|
5 |
+
from langchain.prompts import ChatPromptTemplate
|
6 |
+
from langchain_core.pydantic_v1 import BaseModel, SecretStr
|
7 |
+
from langchain_core.runnables import Runnable
|
8 |
+
from langchain_openai import ChatOpenAI
|
9 |
+
|
10 |
+
|
11 |
+
class ChainGenerator(ABC):
|
12 |
+
|
13 |
+
def __init__(self, openai_api_key: SecretStr, chat_temperature: float = 0.3) -> None:
|
14 |
+
self.openai_api_key = openai_api_key
|
15 |
+
self.chat_temperature = chat_temperature
|
16 |
+
|
17 |
+
self._initialize_chat_llm()
|
18 |
+
|
19 |
+
@abstractmethod
|
20 |
+
def _get_system_prompt(self) -> ChatPromptTemplate:
|
21 |
+
"""Returns the system prompt for the exam.
|
22 |
+
|
23 |
+
Returns:
|
24 |
+
ChatPromptTemplate: System prompt.
|
25 |
+
"""
|
26 |
+
|
27 |
+
@abstractmethod
|
28 |
+
def _create_chain(self) -> Runnable[Any, Any]:
|
29 |
+
"""Creates the chain.
|
30 |
+
|
31 |
+
Returns:
|
32 |
+
RunnableSequence: Chain.
|
33 |
+
"""
|
34 |
+
|
35 |
+
def _initialize_chat_llm(self) -> None:
|
36 |
+
"""Initializes the ChatOpenAI language model."""
|
37 |
+
self.chat_llm = ChatOpenAI(
|
38 |
+
api_key=self.openai_api_key,
|
39 |
+
temperature=self.chat_temperature,
|
40 |
+
model="gpt-3.5-turbo-1106",
|
41 |
+
)
|
42 |
+
|
43 |
+
|
44 |
+
class EvaluationChatModel(ChainGenerator):
|
45 |
+
"""Abstract base class for evaluation chat models."""
|
46 |
+
|
47 |
+
def __init__(self, level: str, openai_api_key: SecretStr, chat_temperature: float) -> None:
|
48 |
+
"""Initialize the evaluation chat model.
|
49 |
+
|
50 |
+
Args:
|
51 |
+
level (str): Level of the exam.
|
52 |
+
"""
|
53 |
+
super().__init__(openai_api_key=openai_api_key, chat_temperature=chat_temperature)
|
54 |
+
self.level = level
|
55 |
+
|
56 |
+
@abstractmethod
|
57 |
+
def _get_output_parser(self, pydantic_schema: Type[BaseModel]) -> PydanticOutputParser[Any]:
|
58 |
+
"""Get the output parser for the model.
|
59 |
+
|
60 |
+
Args:
|
61 |
+
pydantic_schema (BaseModel): The output schema of the model.
|
62 |
+
|
63 |
+
Returns:
|
64 |
+
PydanticOutputParser: The output parser for the model.
|
65 |
+
"""
|
66 |
+
|
67 |
+
@abstractmethod
|
68 |
+
def predict(self, *args: Any, **kwargs: Any) -> Dict[str, str]:
|
69 |
+
"""
|
70 |
+
Defines how the chain should be called in the predict method.
|
71 |
+
|
72 |
+
Returns:
|
73 |
+
Dict: The return value of the predict method.
|
74 |
+
"""
|
75 |
+
|
76 |
+
|
77 |
+
class ContentGenerator(ChainGenerator):
|
78 |
+
"""Abstract base class for generating content"""
|
79 |
+
|
80 |
+
@abstractmethod
|
81 |
+
def generate(self) -> str:
|
82 |
+
"""
|
83 |
+
Defines how the chain should be called in the generate method.
|
84 |
+
|
85 |
+
Returns:
|
86 |
+
str: The return value of the generate method.
|
87 |
+
"""
|
src/models/lc_img_desc_model.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from operator import itemgetter
|
2 |
+
from typing import Any, Dict, override
|
3 |
+
|
4 |
+
from langchain.prompts import ChatPromptTemplate
|
5 |
+
from langchain.schema import HumanMessage
|
6 |
+
from langchain_core.output_parsers import StrOutputParser
|
7 |
+
from langchain_core.pydantic_v1 import BaseModel, Field, SecretStr
|
8 |
+
from langchain_openai import ChatOpenAI
|
9 |
+
|
10 |
+
from src.models.lc_qa_model import EvaluationChatModelQA
|
11 |
+
|
12 |
+
|
13 |
+
class EvaluationChatModelImg(EvaluationChatModelQA):
|
14 |
+
|
15 |
+
class Input(BaseModel):
|
16 |
+
image_url: str
|
17 |
+
user_desc: str
|
18 |
+
|
19 |
+
class Output(BaseModel):
|
20 |
+
evaluation: str = Field(
|
21 |
+
alias="Evaluation", description="Summarize evaluation of the response (just if there is)"
|
22 |
+
)
|
23 |
+
tips: str = Field(
|
24 |
+
alias="Tips", description="tips about complexity and detailed mistakes correction (just if there are)"
|
25 |
+
)
|
26 |
+
example: str = Field(
|
27 |
+
alias="Example",
|
28 |
+
description="Example of a response based on the AI image description following the given guidelines (just if there is)",
|
29 |
+
)
|
30 |
+
|
31 |
+
def __init__(self, level: str, openai_api_key: SecretStr, chat_temperature: float = 0.3) -> None:
|
32 |
+
self.gpt4v = ChatOpenAI(temperature=0.3, model="gpt-4-vision-preview", max_tokens=1024, api_key=openai_api_key)
|
33 |
+
super().__init__(level, openai_api_key=openai_api_key, chat_temperature=chat_temperature)
|
34 |
+
|
35 |
+
def _get_system_prompt(self) -> ChatPromptTemplate:
|
36 |
+
return ChatPromptTemplate.from_messages(
|
37 |
+
[
|
38 |
+
(
|
39 |
+
"system",
|
40 |
+
"{format_instructions}"
|
41 |
+
f"""You will evaluate how close is the the image
|
42 |
+
description given by the user compared to the image
|
43 |
+
description given by the ai vision model. Take into account
|
44 |
+
that this image description will be used for evaluating
|
45 |
+
the user how well can describe this image in the context
|
46 |
+
of an {self.level} Speaking English exam. An Example of
|
47 |
+
an image description will also be provided based on the AI image description.""",
|
48 |
+
),
|
49 |
+
("ai", "AI image description: {ai_img_desc}"),
|
50 |
+
("human", "User image description: {base_response}"),
|
51 |
+
("ai", "Tags:\n{tags}\n\\Extraction:\n{extraction}"),
|
52 |
+
(
|
53 |
+
"system",
|
54 |
+
f"""Generate a final response given the question, its response and the detected Tags and Extraction:
|
55 |
+
- correct mistakes (just if there are) based on the response
|
56 |
+
given by the MistakeExtractor according to the {self.level} english level.
|
57 |
+
- give relevant and related tips based on how complete the answer is given the punctuation of
|
58 |
+
the AnswerTagger. Best responses are 7, 8 point questions since they are neither too simple
|
59 |
+
nor too complex.
|
60 |
+
- With too simple questions (1, 2, 3, 4 points) you must suggest an alternative response with a higher
|
61 |
+
degree of complexity.
|
62 |
+
- With too complex questions (9, 10 points) you must highlight which part of the response should be ignored.
|
63 |
+
- An excellent response must be grammatically correct, complete and clear.
|
64 |
+
- Provide an example answer to the question given the above guidelines and the AI image description.
|
65 |
+
""",
|
66 |
+
),
|
67 |
+
]
|
68 |
+
)
|
69 |
+
|
70 |
+
def _get_multi_chain_dict(self) -> Dict[str, Any]:
|
71 |
+
multi_chain_dict = super()._get_multi_chain_dict()
|
72 |
+
multi_chain_dict = {key: multi_chain_dict[key] for key in ["tags", "extraction"]}
|
73 |
+
|
74 |
+
multi_chain_dict.update(
|
75 |
+
{
|
76 |
+
"ai_img_desc": itemgetter("image_url") | self.gpt4v | StrOutputParser(),
|
77 |
+
"base_response": itemgetter("base_response"),
|
78 |
+
}
|
79 |
+
)
|
80 |
+
|
81 |
+
return multi_chain_dict
|
82 |
+
|
83 |
+
@override
|
84 |
+
def predict(self, user_desc: str, image_url: str) -> Dict[str, str]:
|
85 |
+
"""Make a prediction using the provided input.
|
86 |
+
|
87 |
+
Args:
|
88 |
+
user_desc (str): The user description.
|
89 |
+
image_url (str): The image url.
|
90 |
+
|
91 |
+
Returns:
|
92 |
+
Dict: The output of the prediction.
|
93 |
+
"""
|
94 |
+
input_model = self.Input(user_desc=user_desc, image_url=image_url)
|
95 |
+
gpt4v_input = [
|
96 |
+
HumanMessage(
|
97 |
+
content=[
|
98 |
+
{"type": "text", "text": "What is this image showing?"},
|
99 |
+
{
|
100 |
+
"type": "image_url",
|
101 |
+
"image_url": {"url": input_model.image_url, "detail": "auto"},
|
102 |
+
},
|
103 |
+
]
|
104 |
+
)
|
105 |
+
]
|
106 |
+
result = self.chain.invoke(
|
107 |
+
{"base_response": input_model.user_desc, "image_url": gpt4v_input}, config=self.config
|
108 |
+
)
|
109 |
+
return result.dict(by_alias=True)
|
src/models/lc_qa_model.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
from operator import itemgetter
|
3 |
+
from typing import Any, Dict, Optional, Type
|
4 |
+
|
5 |
+
# from langchain.callbacks.tracers import ConsoleCallbackHandler
|
6 |
+
from langchain.chains import create_extraction_chain_pydantic, create_tagging_chain_pydantic
|
7 |
+
from langchain.output_parsers import PydanticOutputParser
|
8 |
+
from langchain.prompts import ChatPromptTemplate, PromptTemplate
|
9 |
+
from langchain_core.pydantic_v1 import BaseModel, Field, SecretStr
|
10 |
+
from langchain_core.runnables import Runnable, RunnableConfig
|
11 |
+
from langchain_openai import ChatOpenAI
|
12 |
+
|
13 |
+
from src.models.lc_base_model import EvaluationChatModel
|
14 |
+
|
15 |
+
logger = logging.getLogger(__name__)
|
16 |
+
|
17 |
+
|
18 |
+
class EvaluationChatModelQA(EvaluationChatModel):
|
19 |
+
|
20 |
+
class Input(BaseModel):
|
21 |
+
response: str
|
22 |
+
question: Optional[str] = Field(default="")
|
23 |
+
|
24 |
+
class Output(BaseModel):
|
25 |
+
evaluation: str = Field(
|
26 |
+
alias="Evaluation",
|
27 |
+
description="Summarize evaluation of the response (just if there is)",
|
28 |
+
default="",
|
29 |
+
)
|
30 |
+
tips: str = Field(
|
31 |
+
alias="Tips",
|
32 |
+
description="tips about complexity and detailed mistakes correction (just if there are)",
|
33 |
+
default="",
|
34 |
+
)
|
35 |
+
example: str = Field(
|
36 |
+
alias="Example",
|
37 |
+
description="Example of the response following the given guidelines (just if there is)",
|
38 |
+
default="",
|
39 |
+
)
|
40 |
+
|
41 |
+
class AnswerTagger(BaseModel):
|
42 |
+
"""
|
43 |
+
Tags the answer considering the following aspects:
|
44 |
+
|
45 |
+
- complexity
|
46 |
+
"""
|
47 |
+
|
48 |
+
answer_complexity: int = Field(
|
49 |
+
description="describes how complex the answer is. It is a number between 0 (simpler) and 10 (more complex)",
|
50 |
+
enum=list(range(11)),
|
51 |
+
)
|
52 |
+
|
53 |
+
class MistakeExtractor(BaseModel):
|
54 |
+
"""
|
55 |
+
Extracts the mistakes from the text.
|
56 |
+
"""
|
57 |
+
|
58 |
+
grammar_mistake: Optional[str] = Field(
|
59 |
+
description="Grammar syntax mistakes detected in text, just if there are, if not return empty string.",
|
60 |
+
default="",
|
61 |
+
)
|
62 |
+
|
63 |
+
def __init__(self, level: str, openai_api_key: SecretStr, chat_temperature: float = 0.3) -> None:
|
64 |
+
"""
|
65 |
+
Initializes the class with the given parameters.
|
66 |
+
|
67 |
+
Args:
|
68 |
+
exam_prompt (str): The prompt for the exam.
|
69 |
+
level (str): The level of the exam.
|
70 |
+
openai_api_key (SecretStr): The API key for OpenAI.
|
71 |
+
|
72 |
+
Returns:
|
73 |
+
None
|
74 |
+
"""
|
75 |
+
super().__init__(level=level, openai_api_key=openai_api_key, chat_temperature=chat_temperature)
|
76 |
+
|
77 |
+
self.checker_llm = ChatOpenAI(api_key=self.openai_api_key, temperature=0, model="gpt-3.5-turbo")
|
78 |
+
self.prompt = self._get_system_prompt()
|
79 |
+
|
80 |
+
self.chain = self._create_chain()
|
81 |
+
|
82 |
+
self.config = RunnableConfig({})
|
83 |
+
# {"callbacks": [ConsoleCallbackHandler()]}
|
84 |
+
|
85 |
+
def _get_multi_chain_dict(self) -> Dict[str, Any]:
|
86 |
+
"""
|
87 |
+
Returns a dictionary containing three chains for extracting mistakes, tagging responses, and retrieving relevant information from an item.
|
88 |
+
|
89 |
+
The dictionary has the following keys:
|
90 |
+
- "tags": A chain for tagging responses.
|
91 |
+
- "extraction": A chain for extracting mistakes.
|
92 |
+
- "base_response": A function that retrieves the "base_response" field from an item.
|
93 |
+
- "question": A function that retrieves the "question" field from an item.
|
94 |
+
|
95 |
+
The "tags" chain is created using the `create_tagging_chain_pydantic` function, with the `AnswerTagger` pydantic schema and a prompt template.
|
96 |
+
The "extraction" chain is created using the `create_extraction_chain_pydantic` function, with the `MistakeExtractor` pydantic schema and a prompt template.
|
97 |
+
|
98 |
+
Returns:
|
99 |
+
dict: A dictionary containing the three chains and the relevant item getter functions.
|
100 |
+
"""
|
101 |
+
chain_extractor = create_extraction_chain_pydantic(
|
102 |
+
pydantic_schema=self.MistakeExtractor,
|
103 |
+
llm=self.checker_llm,
|
104 |
+
prompt=PromptTemplate(
|
105 |
+
template="Extract the mistakes found on: {base_response}", input_variables=["base_response"]
|
106 |
+
),
|
107 |
+
)
|
108 |
+
|
109 |
+
chain_tagger = create_tagging_chain_pydantic(
|
110 |
+
pydantic_schema=self.AnswerTagger,
|
111 |
+
llm=self.checker_llm,
|
112 |
+
prompt=PromptTemplate(
|
113 |
+
template="Tag the given response: {base_response}", input_variables=["base_response"]
|
114 |
+
),
|
115 |
+
)
|
116 |
+
|
117 |
+
return {
|
118 |
+
"tags": chain_tagger,
|
119 |
+
"extraction": chain_extractor,
|
120 |
+
"base_response": itemgetter("base_response"),
|
121 |
+
"question": itemgetter("question"),
|
122 |
+
}
|
123 |
+
|
124 |
+
def _get_system_prompt(self) -> ChatPromptTemplate:
|
125 |
+
prompt = ChatPromptTemplate.from_messages(
|
126 |
+
[
|
127 |
+
(
|
128 |
+
"system",
|
129 |
+
"{format_instructions}"
|
130 |
+
"""You are an excellent english teacher. You teach spanish people to speak English.
|
131 |
+
You will do the following tasks for that purpose:
|
132 |
+
- You will evaluate the quality of the responses given by the user.
|
133 |
+
- if a non-related text is asked you will politely decline to answer and you will
|
134 |
+
suggest to stay on the topic.
|
135 |
+
- Limit your evaluation to just once per interaction at a time.
|
136 |
+
- guide client to adquire fluency for English exams.
|
137 |
+
""",
|
138 |
+
),
|
139 |
+
("ai", "AI Question: {question}"),
|
140 |
+
("human", "Human Response: {base_response}"),
|
141 |
+
("ai", "Tags:\n{tags}\n\\Extraction:\n{extraction}"),
|
142 |
+
(
|
143 |
+
"system",
|
144 |
+
f"""Generate a final response given the AI Question, the Human Response and the detected Tags and Extraction:
|
145 |
+
- correct mistakes (just if there are) based on the Human Response
|
146 |
+
given by the MistakeExtractor according to the {self.level} english level.
|
147 |
+
- give relevant and related tips based on how complete the Human Response is given the punctuation of
|
148 |
+
the answer_complexity AnswerTagger Tags. Best responses are 7, 8 point responses since they are neither too simple
|
149 |
+
nor too complex.
|
150 |
+
- With too simple responses (1, 2, 3, 4 points) you must suggest an alternative response with a higher
|
151 |
+
degree of complexity.
|
152 |
+
- With too complex responses (9, 10 points) you must highlight which part of the response should be ignored.
|
153 |
+
- An excellent response must be grammatically correct, complete and clear.
|
154 |
+
- You will propose an excellent example answer to the AI Question given the above guidelines.
|
155 |
+
""",
|
156 |
+
),
|
157 |
+
]
|
158 |
+
)
|
159 |
+
return prompt
|
160 |
+
|
161 |
+
def _get_output_parser(self, pydantic_schema: Type[BaseModel]) -> PydanticOutputParser[Any]:
|
162 |
+
|
163 |
+
return PydanticOutputParser(pydantic_object=pydantic_schema)
|
164 |
+
|
165 |
+
def _create_chain(self) -> Runnable[Any, Any]:
|
166 |
+
response_parser = self._get_output_parser(self.Output)
|
167 |
+
prompt = self.prompt.partial(format_instructions=response_parser.get_format_instructions())
|
168 |
+
|
169 |
+
final_responder = prompt | self.chat_llm | response_parser
|
170 |
+
|
171 |
+
return self._get_multi_chain_dict() | final_responder
|
172 |
+
|
173 |
+
def predict(self, response: str, question: str) -> Dict[str, str]:
|
174 |
+
|
175 |
+
input_model = self.Input(response=response, question=question)
|
176 |
+
|
177 |
+
result = self.chain.invoke(
|
178 |
+
{"base_response": input_model.response, "question": input_model.question}, config=self.config
|
179 |
+
)
|
180 |
+
|
181 |
+
return result.dict(by_alias=True)
|
src/models/model_factory.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from abc import ABC, abstractmethod
|
2 |
+
from typing import Any, List, Optional
|
3 |
+
|
4 |
+
from langchain.schema import AIMessage, HumanMessage
|
5 |
+
from langchain_core.pydantic_v1 import SecretStr
|
6 |
+
|
7 |
+
from src.models.generator import ImgGenerator, QuestionGenerator
|
8 |
+
from src.models.lc_base_model import ChainGenerator, ContentGenerator, EvaluationChatModel
|
9 |
+
from src.models.lc_img_desc_model import EvaluationChatModelImg
|
10 |
+
from src.models.lc_qa_model import EvaluationChatModelQA
|
11 |
+
|
12 |
+
|
13 |
+
class ModelFactory(ABC):
|
14 |
+
|
15 |
+
@abstractmethod
|
16 |
+
def create_model(self, *args: Any, **kwargs: Any) -> ChainGenerator:
|
17 |
+
"""
|
18 |
+
An abstract method to create a model, with the return types EvaluationChatModel or ChainGenerator.
|
19 |
+
"""
|
20 |
+
|
21 |
+
|
22 |
+
class EvaluationChatModelFactory(ModelFactory):
|
23 |
+
|
24 |
+
def create_model(self, model_class: str, openai_api_key: SecretStr, **kwargs: Any) -> EvaluationChatModel:
|
25 |
+
"""
|
26 |
+
Create a model based on the provided model class and OpenAI API key.
|
27 |
+
|
28 |
+
Args:
|
29 |
+
model_class (str): The type of model to create.
|
30 |
+
openai_api_key (SecretStr): The API key for OpenAI.
|
31 |
+
**kwargs (Any): Additional keyword arguments.
|
32 |
+
|
33 |
+
Returns:
|
34 |
+
EvaluationChatModel: The created evaluation chat model.
|
35 |
+
|
36 |
+
Raises:
|
37 |
+
ValueError: If an invalid model class is provided.
|
38 |
+
"""
|
39 |
+
match model_class:
|
40 |
+
case "qa":
|
41 |
+
return EvaluationChatModelQA(openai_api_key=openai_api_key, **kwargs)
|
42 |
+
case "img_desc":
|
43 |
+
return EvaluationChatModelImg(openai_api_key=openai_api_key, **kwargs)
|
44 |
+
case _:
|
45 |
+
raise ValueError("Invalid model class provided")
|
46 |
+
|
47 |
+
|
48 |
+
class GeneratorModelFactory(ModelFactory):
|
49 |
+
|
50 |
+
def create_model(
|
51 |
+
self,
|
52 |
+
model_class: str,
|
53 |
+
openai_api_key: SecretStr,
|
54 |
+
history_chat: Optional[List[HumanMessage | AIMessage]] = None,
|
55 |
+
img_size: str = "256x256",
|
56 |
+
**kwargs: Any,
|
57 |
+
) -> ContentGenerator:
|
58 |
+
"""
|
59 |
+
Generate a model based on the specified model class and parameters.
|
60 |
+
|
61 |
+
Parameters:
|
62 |
+
model_class (str): The class of the model to create.
|
63 |
+
openai_api_key (SecretStr): The API key for OpenAI.
|
64 |
+
history_chat (Optional[list], optional): List of chat history. Defaults to None.
|
65 |
+
img_size (str, optional): The size of the image. Defaults to "256x256".
|
66 |
+
**kwargs (Any): Additional keyword arguments.
|
67 |
+
|
68 |
+
Returns:
|
69 |
+
ContentGenerator: A generator for the specified model class.
|
70 |
+
"""
|
71 |
+
match model_class:
|
72 |
+
case "qa":
|
73 |
+
return QuestionGenerator(openai_api_key=openai_api_key, history_chat=history_chat or [], **kwargs)
|
74 |
+
case "img_desc":
|
75 |
+
return ImgGenerator(openai_api_key=openai_api_key, img_size=img_size, **kwargs)
|
76 |
+
case _:
|
77 |
+
raise ValueError("Invalid model class provided")
|
src/utils.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Dict
|
2 |
+
|
3 |
+
|
4 |
+
def convert_json_to_str(x: Dict[str, str]) -> str:
|
5 |
+
"""
|
6 |
+
A function that converts a JSON object to a formatted string.
|
7 |
+
|
8 |
+
Parameters:
|
9 |
+
x (dict): A dictionary representing a JSON object.
|
10 |
+
|
11 |
+
Returns:
|
12 |
+
str: A formatted string with key-value pairs from the JSON object.
|
13 |
+
"""
|
14 |
+
return " \n\n ".join(f"**{k}**" + ": " + val for k, val in x.items() if val != "")
|
15 |
+
|
16 |
+
|
17 |
+
def read_json(file_path: str) -> Dict[str, Any]:
|
18 |
+
"""
|
19 |
+
A function that reads a JSON file and returns its contents as a dictionary.
|
20 |
+
|
21 |
+
Parameters:
|
22 |
+
file_path (str): The path to the JSON file.
|
23 |
+
|
24 |
+
Returns:
|
25 |
+
dict: A dictionary containing the contents of the JSON file.
|
26 |
+
"""
|
27 |
+
with open(file_path) as f:
|
28 |
+
return dict(eval(f.read()))
|
29 |
+
|
30 |
+
|
31 |
+
def read_plain_text(file_path: str) -> str:
|
32 |
+
"""
|
33 |
+
A function that reads a plain text file and returns its contents as a string.
|
34 |
+
|
35 |
+
Parameters:
|
36 |
+
file_path (str): The path to the plain text file.
|
37 |
+
|
38 |
+
Returns:
|
39 |
+
str: A string containing the contents of the plain text file.
|
40 |
+
"""
|
41 |
+
with open(file_path) as f:
|
42 |
+
return f.read()
|
src/whisper_transcription.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import io
|
2 |
+
from typing import Any, Callable, Dict, Optional, Tuple
|
3 |
+
|
4 |
+
import streamlit as st
|
5 |
+
from openai import OpenAI
|
6 |
+
from streamlit_mic_recorder import mic_recorder
|
7 |
+
|
8 |
+
|
9 |
+
def whisper_stt( # noqa: C901, PLR0912
|
10 |
+
start_prompt: str = "Start recording ⏺️",
|
11 |
+
stop_prompt: str = "Stop recording ⏹️",
|
12 |
+
just_once: bool = False,
|
13 |
+
key: Optional[str] = None,
|
14 |
+
use_container_width: bool = False,
|
15 |
+
language: Optional[str] = None,
|
16 |
+
callback: Optional[Callable[..., None]] = None,
|
17 |
+
n_max_retry: int = 3,
|
18 |
+
*args: Tuple[Any, ...],
|
19 |
+
**kwargs: Dict[str, Any]
|
20 |
+
) -> Optional[str]:
|
21 |
+
"""
|
22 |
+
Generate speech-to-text (STT) from recorded audio using OpenAI.
|
23 |
+
|
24 |
+
Args:
|
25 |
+
start_prompt (str): The prompt to start recording.
|
26 |
+
stop_prompt (str): The prompt to stop recording.
|
27 |
+
just_once (bool): Flag to record audio just once or continuously.
|
28 |
+
use_container_width (bool): Flag to use container width for the recording interface.
|
29 |
+
language (Optional[str]): The language for the text transcription.
|
30 |
+
callback (Optional[Callable[..., None]]): Callback function to execute after new output is generated.
|
31 |
+
args (Tuple[Any, ...]): Positional arguments to pass to the callback function.
|
32 |
+
kwargs (Dict[str, Any]): Keyword arguments to pass to the callback function.
|
33 |
+
key (Optional[str]): Key to store the output in the session state.
|
34 |
+
|
35 |
+
Returns:
|
36 |
+
Optional[str]: The generated speech-to-text output or None if unsuccessful.
|
37 |
+
"""
|
38 |
+
if "openai_client" not in st.session_state:
|
39 |
+
st.session_state.openai_client = OpenAI(api_key=st.session_state.openai_api_key.get_secret_value())
|
40 |
+
if "_last_speech_to_text_transcript_id" not in st.session_state:
|
41 |
+
st.session_state._last_speech_to_text_transcript_id = 0
|
42 |
+
if "_last_speech_to_text_transcript" not in st.session_state:
|
43 |
+
st.session_state._last_speech_to_text_transcript = None
|
44 |
+
if key and key + "_output" not in st.session_state:
|
45 |
+
st.session_state[key + "_output"] = None
|
46 |
+
|
47 |
+
audio = mic_recorder(
|
48 |
+
start_prompt=start_prompt,
|
49 |
+
stop_prompt=stop_prompt,
|
50 |
+
just_once=just_once,
|
51 |
+
use_container_width=use_container_width,
|
52 |
+
key=key,
|
53 |
+
)
|
54 |
+
|
55 |
+
new_output = False
|
56 |
+
if audio is None:
|
57 |
+
output = None
|
58 |
+
else:
|
59 |
+
audio_id = audio["id"]
|
60 |
+
new_output = audio_id > st.session_state._last_speech_to_text_transcript_id
|
61 |
+
if new_output:
|
62 |
+
output = None
|
63 |
+
st.session_state._last_speech_to_text_transcript_id = audio_id
|
64 |
+
audio_bio = io.BytesIO(audio["bytes"])
|
65 |
+
audio_bio.name = "audio.mp3"
|
66 |
+
success = False
|
67 |
+
err = 0
|
68 |
+
while not success and err < n_max_retry:
|
69 |
+
try:
|
70 |
+
transcript = st.session_state.openai_client.audio.transcriptions.create(
|
71 |
+
model="whisper-1", file=audio_bio, language=language
|
72 |
+
)
|
73 |
+
except Exception as e:
|
74 |
+
print(str(e))
|
75 |
+
err += 1
|
76 |
+
else:
|
77 |
+
success = True
|
78 |
+
output = transcript.text
|
79 |
+
st.session_state._last_speech_to_text_transcript = output
|
80 |
+
elif not just_once:
|
81 |
+
output = st.session_state._last_speech_to_text_transcript
|
82 |
+
else:
|
83 |
+
output = None
|
84 |
+
|
85 |
+
if key:
|
86 |
+
st.session_state[key + "_output"] = output
|
87 |
+
if new_output and callback:
|
88 |
+
callback(*args, **kwargs)
|
89 |
+
return output
|