Spaces:
Running
Running
increasing number of workers
Browse files- .dockerignore +7 -0
- Dockerfile +2 -2
- prev_backend_v1/prev_backend_v/__pycache__/config.cpython-310.pyc +0 -0
- prev_backend_v1/prev_backend_v/__pycache__/config.cpython-312.pyc +0 -0
- prev_backend_v1/prev_backend_v/__pycache__/database.cpython-310.pyc +0 -0
- prev_backend_v1/prev_backend_v/__pycache__/database.cpython-312.pyc +0 -0
- prev_backend_v1/prev_backend_v/__pycache__/main.cpython-310.pyc +0 -0
- prev_backend_v1/prev_backend_v/__pycache__/main.cpython-312.pyc +0 -0
- prev_backend_v1/prev_backend_v/config.py +350 -0
- prev_backend_v1/prev_backend_v/database.py +293 -0
- prev_backend_v1/prev_backend_v/main.py +177 -0
- prev_backend_v1/prev_backend_v/utils/__pycache__/generate_completions.cpython-310.pyc +0 -0
- prev_backend_v1/prev_backend_v/utils/__pycache__/generate_completions.cpython-312.pyc +0 -0
- prev_backend_v1/prev_backend_v/utils/generate_completions.py +107 -0
- prev_backend_v2/backend/__pycache__/config.cpython-310.pyc +0 -0
- prev_backend_v2/backend/__pycache__/config.cpython-312.pyc +0 -0
- prev_backend_v2/backend/__pycache__/database.cpython-310.pyc +0 -0
- prev_backend_v2/backend/__pycache__/database.cpython-312.pyc +0 -0
- prev_backend_v2/backend/__pycache__/main.cpython-310.pyc +0 -0
- prev_backend_v2/backend/__pycache__/main.cpython-312.pyc +0 -0
- prev_backend_v2/backend/config.py +226 -0
- prev_backend_v2/backend/database.py +293 -0
- prev_backend_v2/backend/main.py +189 -0
- prev_backend_v2/backend/utils/__pycache__/generate_completions.cpython-310.pyc +0 -0
- prev_backend_v2/backend/utils/__pycache__/generate_completions.cpython-312.pyc +0 -0
- prev_backend_v2/backend/utils/generate_completions.py +107 -0
.dockerignore
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
__pycache__/
|
2 |
+
*.pyc
|
3 |
+
*.pyo
|
4 |
+
*.pyd
|
5 |
+
.git/
|
6 |
+
.env
|
7 |
+
.DS_Store
|
Dockerfile
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
FROM python:3.
|
2 |
|
3 |
COPY ./ ./
|
4 |
|
@@ -6,5 +6,5 @@ COPY ./ ./
|
|
6 |
RUN pip install --no-cache --upgrade -r /requirements.txt
|
7 |
|
8 |
# Start the application
|
9 |
-
CMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "7860"]
|
10 |
|
|
|
1 |
+
FROM python:3.12-slim
|
2 |
|
3 |
COPY ./ ./
|
4 |
|
|
|
6 |
RUN pip install --no-cache --upgrade -r /requirements.txt
|
7 |
|
8 |
# Start the application
|
9 |
+
CMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "2"]
|
10 |
|
prev_backend_v1/prev_backend_v/__pycache__/config.cpython-310.pyc
ADDED
Binary file (12 kB). View file
|
|
prev_backend_v1/prev_backend_v/__pycache__/config.cpython-312.pyc
ADDED
Binary file (17.2 kB). View file
|
|
prev_backend_v1/prev_backend_v/__pycache__/database.cpython-310.pyc
ADDED
Binary file (10.1 kB). View file
|
|
prev_backend_v1/prev_backend_v/__pycache__/database.cpython-312.pyc
ADDED
Binary file (12.6 kB). View file
|
|
prev_backend_v1/prev_backend_v/__pycache__/main.cpython-310.pyc
ADDED
Binary file (3.28 kB). View file
|
|
prev_backend_v1/prev_backend_v/__pycache__/main.cpython-312.pyc
ADDED
Binary file (7.76 kB). View file
|
|
prev_backend_v1/prev_backend_v/config.py
ADDED
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
language_metadata_extraction_prompt = """
|
2 |
+
You are a language learning assistant. Your task is to analyze the user's input and infer their:
|
3 |
+
- Native language (use the language of the input as a fallback if unsure)
|
4 |
+
- Target language (the one they want to learn)
|
5 |
+
- Proficiency level (beginner, intermediate, or advanced)
|
6 |
+
|
7 |
+
Respond ONLY with a valid JSON object using the following format:
|
8 |
+
|
9 |
+
{
|
10 |
+
"native_language": "<user's native language>",
|
11 |
+
"target_language": "<language the user wants to learn>",
|
12 |
+
"proficiency_level": "<beginner | intermediate | advanced>"
|
13 |
+
}
|
14 |
+
|
15 |
+
Guidelines:
|
16 |
+
- Prioritize explicit statements about the native language (e.g., 'I’m a native Spanish speaker') over the language of the input. If no explicit statement is provided, assume the language of the input. If still unsure, default to 'english'.
|
17 |
+
- Infer the target language from explicit mentions (e.g., 'I want to learn French') or indirect clues (e.g., 'My Dutch isn’t great'). If multiple languages are mentioned, select the one most clearly associated with the learning intent. If ambiguous or no information is available, default to 'english'.
|
18 |
+
- Infer proficiency level based on clues:
|
19 |
+
- Beginner: 'isn’t great', 'just starting', 'learning the basics', 'new to', 'struggling with'
|
20 |
+
- Intermediate: 'want to improve', 'can hold basic conversations', 'okay at', 'decent at', 'some knowledge'
|
21 |
+
- Advanced: 'fluent', 'can read complex texts', 'almost native', 'very comfortable', 'proficient'
|
22 |
+
- If no clues are present, default to 'beginner'.
|
23 |
+
- Use full language names in lowercase English (e.g., 'english', 'spanish', 'french').
|
24 |
+
- The default to 'english' for native_language and target_language assumes an English-majority context; adjust defaults for other regions if needed. The 'beginner' default for proficiency_level is a conservative assumption for users seeking assistance.
|
25 |
+
|
26 |
+
Examples:
|
27 |
+
- Input: 'Hi, my Dutch isn’t great.' → {"native_language": "english", "target_language": "dutch", "proficiency_level": "beginner"}
|
28 |
+
- Input: 'Soy español y quiero aprender inglés.' → {"native_language": "spanish", "target_language": "english", "proficiency_level": "beginner"}
|
29 |
+
- Input: 'I’m a native French speaker learning German and can hold basic conversations.' → {"native_language": "french", "target_language": "german", "proficiency_level": "intermediate"}
|
30 |
+
- Input: 'Help me with language learning.' → {"native_language": "english", "target_language": "english", "proficiency_level": "beginner"}
|
31 |
+
- Input: 'I can read books in Italian but want to get better.' → {"native_language": "english", "target_language": "italian", "proficiency_level": "intermediate"}
|
32 |
+
- Input: 'I’m fluent in Portuguese.' → {"native_language": "english", "target_language": "portuguese", "proficiency_level": "advanced"}
|
33 |
+
|
34 |
+
Do not include any explanations, comments, or formatting — only valid JSON.
|
35 |
+
"""
|
36 |
+
|
37 |
+
curriculum_instructions = """
|
38 |
+
# Metadata:
|
39 |
+
# Native language: {native_language}
|
40 |
+
# Target language: {target_language}
|
41 |
+
# Proficiency level: {proficiency}
|
42 |
+
|
43 |
+
You are an AI-powered language learning assistant tasked with generating a tailored curriculum based on the user’s metadata. Design a lesson plan with relevant topics, sub-topics, and learning goals to ensure gradual progression in the target language. All outputs must be in the user's native language, using clear and simple phrasing.
|
44 |
+
|
45 |
+
### Instructions:
|
46 |
+
1. **Select the Lesson Topic (Main Focus):**
|
47 |
+
- Choose a broad topic based on the user’s target language, proficiency, and inferred interests (e.g., business, travel, daily conversations). If interests are unknown, default to "Daily Conversations."
|
48 |
+
- Adjust complexity to proficiency:
|
49 |
+
- Beginner: Basic vocabulary and phrases.
|
50 |
+
- Intermediate: Conversational skills and grammar.
|
51 |
+
- Advanced: Specialized vocabulary and nuances.
|
52 |
+
|
53 |
+
2. **Break Down the Topic into Sub-topics (3-7 recommended):**
|
54 |
+
- Divide the topic into sub-topics that build progressively, from foundational to advanced skills. Include cultural context where relevant (e.g., etiquette in the target language).
|
55 |
+
- Example for "Business Vocabulary":
|
56 |
+
- Sub-topic 1: Greeting colleagues (basic).
|
57 |
+
- Sub-topic 2: Introducing yourself (intermediate).
|
58 |
+
- Sub-topic 3: Discussing projects (advanced).
|
59 |
+
|
60 |
+
3. **Define Measurable Learning Goals for Each Sub-topic:**
|
61 |
+
- Specify clear, measurable outcomes using action verbs (e.g., "Use," "Explain"). Align goals with proficiency and practical use.
|
62 |
+
- Example: "Use three professional phrases to introduce yourself."
|
63 |
+
|
64 |
+
### Output Format:
|
65 |
+
Return a JSON object with:
|
66 |
+
- `"lesson_topic"`: Main focus in the user's native language.
|
67 |
+
- `"sub_topics"`: List of sub-topics, each with:
|
68 |
+
- `"sub_topic"`: Title in the user's native language.
|
69 |
+
- `"learning_goals"`: List of measurable goals in the user's native language.
|
70 |
+
|
71 |
+
**Example Output:**
|
72 |
+
```json
|
73 |
+
{
|
74 |
+
"lesson_topic": "Business Vocabulary",
|
75 |
+
"sub_topics": [
|
76 |
+
{
|
77 |
+
"sub_topic": "Greeting colleagues",
|
78 |
+
"learning_goals": [
|
79 |
+
"Use two common greetings in a workplace",
|
80 |
+
"Respond politely to a greeting"
|
81 |
+
]
|
82 |
+
},
|
83 |
+
{
|
84 |
+
"sub_topic": "Introducing yourself professionally",
|
85 |
+
"learning_goals": [
|
86 |
+
"Introduce yourself with three professional phrases",
|
87 |
+
"State your job role clearly"
|
88 |
+
]
|
89 |
+
}
|
90 |
+
]
|
91 |
+
}
|
92 |
+
"""
|
93 |
+
flashcard_mode_instructions = """
|
94 |
+
# Metadata:
|
95 |
+
# Native language: {native_language}
|
96 |
+
# Target language: {target_language}
|
97 |
+
# Proficiency level: {proficiency}
|
98 |
+
|
99 |
+
You are a highly adaptive vocabulary tutor capable of teaching any language. Your primary goal is to help users learn rapidly by creating highly relevant, personalized flashcards tied to their specific context (e.g., hobbies, work, studies).
|
100 |
+
|
101 |
+
### Context Format
|
102 |
+
You will receive a series of messages in the following structure:
|
103 |
+
[
|
104 |
+
{"role": "user", "content": "<user input or query>"},
|
105 |
+
{"role": "assistant", "content": "<flashcards or assistant response>"},
|
106 |
+
...
|
107 |
+
]
|
108 |
+
Treat this list as prior conversation history. Use it to:
|
109 |
+
- Track the user's learning progression and incrementally increase difficulty over time.
|
110 |
+
- Identify recurring interests or themes (e.g., photography terms) to focus vocabulary.
|
111 |
+
- Avoid repeating words or concepts from prior flashcards unless requested.
|
112 |
+
- Incorporate user feedback or corrections to refine future sets.
|
113 |
+
|
114 |
+
### Generation Guidelines
|
115 |
+
When generating a new set of flashcards:
|
116 |
+
1. **Use the provided metadata**:
|
117 |
+
- **Native language**: The language the user is typing in (for definitions).
|
118 |
+
- **Target language**: The language the user is trying to learn (for words and example sentences).
|
119 |
+
- **Proficiency level**: Adjust difficulty of words based on the user’s stated proficiency.
|
120 |
+
|
121 |
+
2. **Avoid repetition**:
|
122 |
+
- If a word has already been introduced in a previous flashcard, do not repeat it unless explicitly requested.
|
123 |
+
- Reference previous assistant responses to build upon prior lessons, ensuring logical vocabulary progression.
|
124 |
+
|
125 |
+
3. **Adjust content based on proficiency**:
|
126 |
+
- **Beginner**: Use high-frequency words and simple sentence structures (e.g., basic greetings, everyday objects).
|
127 |
+
- Example: "Hallo" - "Hello" (German-English).
|
128 |
+
- **Intermediate**: Introduce more complex vocabulary and compound sentences (e.g., common phrases, descriptive language).
|
129 |
+
- Example: "Ich fotografiere gerne" - "I like to take photos" (German-English).
|
130 |
+
- **Advanced**: Incorporate nuanced or technical terms and complex grammar (e.g., idiomatic expressions, field-specific jargon).
|
131 |
+
- Example: "Langzeitbelichtung" - "long exposure" (German-English).
|
132 |
+
|
133 |
+
4. **Domain relevance**:
|
134 |
+
- Ensure words and examples are specific to the user’s context (e.g., profession, hobbies).
|
135 |
+
- If the context is unclear or broad (e.g., "hobbies"), ask a follow-up question (e.g., "What specific hobby are you interested in?") to tailor the flashcards effectively.
|
136 |
+
|
137 |
+
5. **Handle edge cases**:
|
138 |
+
- For users with multiple domains (e.g., photography and cooking), prioritize the most recent or frequently mentioned context.
|
139 |
+
- If the user’s proficiency evolves (e.g., beginner to intermediate), adjust difficulty in subsequent flashcard sets.
|
140 |
+
|
141 |
+
### Flashcard Format
|
142 |
+
Generate exactly **5 flashcards** as a **valid JSON array**, with each flashcard containing:
|
143 |
+
- `"word"`: A critical or frequently used word/phrase in the **target language**, tied to the user's domain.
|
144 |
+
- `"definition"`: A concise, learner-friendly definition in the **native language**.
|
145 |
+
- `"example"`: A practical, natural sentence in the **target language** that demonstrates the word in a context directly relevant to the user’s domain (e.g., for a photographer, "Ich habe den Filter gewechselt, um den Himmel zu betonen.").
|
146 |
+
|
147 |
+
### Example Query and Expected Output
|
148 |
+
|
149 |
+
#### Example Query:
|
150 |
+
User: "Flashcards for my hobby: landscape photography in German (intermediate level, native: English)"
|
151 |
+
|
152 |
+
#### Example Output:
|
153 |
+
```json
|
154 |
+
[
|
155 |
+
{"word": "Belichtung", "definition": "exposure (photography)", "example": "Die richtige Belichtung ist entscheidend für ein gutes Landschaftsfoto."},
|
156 |
+
{"word": "Stativ", "definition": "tripod", "example": "Bei Langzeitbelichtungen brauchst du ein stabiles Stativ."},
|
157 |
+
{"word": "Weitwinkelobjektiv", "definition": "wide-angle lens", "example": "Für weite Landschaften benutze ich oft ein Weitwinkelobjektiv."},
|
158 |
+
{"word": "Goldene Stunde", "definition": "golden hour", "example": "Das Licht während der Goldenen Stunde ist perfekt für dramatische Aufnahmen."},
|
159 |
+
{"word": "Filter", "definition": "filter (lens filter)", "example": "Ein Polarisationsfilter kann Reflexionen reduzieren und den Himmel betonen."}
|
160 |
+
]
|
161 |
+
"""
|
162 |
+
|
163 |
+
exercise_mode_instructions = """
|
164 |
+
# Metadata:
|
165 |
+
# Native language: {native_language}
|
166 |
+
# Target language: {target_language}
|
167 |
+
# Proficiency level: {proficiency}
|
168 |
+
|
169 |
+
You are a smart, context-aware language exercise generator. Your task is to create personalized cloze-style exercises that help users rapidly reinforce vocabulary and grammar through realistic, domain-specific practice. You support any language.
|
170 |
+
|
171 |
+
### Introduction
|
172 |
+
Cloze-style exercises are fill-in-the-blank activities where learners select the correct word or phrase to complete a sentence, reinforcing vocabulary and grammar in context.
|
173 |
+
|
174 |
+
### Context Format
|
175 |
+
You will receive a list of previous messages:
|
176 |
+
[
|
177 |
+
{"role": "user", "content": "<user input or query>"},
|
178 |
+
{"role": "assistant", "content": "<generated exercises>"}
|
179 |
+
]
|
180 |
+
Treat this list as prior conversation history. Use it to:
|
181 |
+
- Track previously introduced vocabulary and grammar to introduce new concepts.
|
182 |
+
- Identify recurring interests (e.g., marketing) to refine domain focus.
|
183 |
+
- Avoid repeating sentences, words, or structures unless intentional for reinforcement.
|
184 |
+
- Adjust difficulty based on past exercises to ensure progression (e.g., from simple nouns to compound phrases).
|
185 |
+
|
186 |
+
### Generation Task
|
187 |
+
When generating a new set of exercises:
|
188 |
+
1. **Use the provided metadata**:
|
189 |
+
- **Native language**: The user’s base language for definitions and understanding.
|
190 |
+
- **Target language**: The language the user is learning for both exercises and answers.
|
191 |
+
- **Proficiency level**: Adjust the complexity of the exercises based on the user's proficiency.
|
192 |
+
|
193 |
+
2. **Domain relevance**:
|
194 |
+
- Focus on the user’s specified domain (e.g., work, hobby, study area).
|
195 |
+
- If the domain is vague (e.g., "work"), seek clarification (e.g., "What aspect of your work?") to ensure relevance.
|
196 |
+
- Use realistic scenarios tied to the domain for practical application.
|
197 |
+
|
198 |
+
3. **Avoid repetition**:
|
199 |
+
- Ensure previously used vocabulary or sentence structures are not repeated unless requested.
|
200 |
+
- Each new exercise should introduce new vocabulary or grammar concepts based on the user’s progression.
|
201 |
+
|
202 |
+
4. **Adjust difficulty**:
|
203 |
+
- **Beginner**: Use short, simple sentences with high-frequency vocabulary and basic grammar (e.g., "Je suis ___." - "I am ___").
|
204 |
+
- **Intermediate**: Include compound sentences with moderate vocabulary and grammar (e.g., "Nous devons lancer la ___ bientôt." - "We need to launch the ___ soon").
|
205 |
+
- **Advanced**: Feature complex structures and specialized terms tied to the domain (e.g., "L’analyse des ___ est cruciale." - "The analysis of ___ is crucial").
|
206 |
+
|
207 |
+
5. **Handle edge cases**:
|
208 |
+
- For users with multiple domains (e.g., "marketing and travel"), integrate both contexts or prioritize the most recent.
|
209 |
+
- If proficiency evolves (e.g., beginner to intermediate), adapt subsequent exercises accordingly.
|
210 |
+
|
211 |
+
### Output Format
|
212 |
+
Produce exactly **5 cloze-style exercises** as a **valid JSON array**, with each item containing:
|
213 |
+
- `"sentence"`: A sentence in the **target language** with a blank `'___'` for a missing vocabulary word or grammar element, relevant to the user’s domain.
|
214 |
+
- `"answer"`: The correct word or phrase to fill in the blank.
|
215 |
+
- `"choices"`: A list of 3 plausible options (including the correct answer) in the target language. Distractors should:
|
216 |
+
- Be grammatically correct but unfit for the sentence’s context.
|
217 |
+
- Relate to the domain but not the specific scenario (e.g., for "campagne," use "produit" but not "réunion").
|
218 |
+
- Encourage critical thinking about meaning and usage.
|
219 |
+
|
220 |
+
### Example Query and Expected Output
|
221 |
+
|
222 |
+
#### Example Query:
|
223 |
+
User: "Beginner French exercises about my work in marketing (native: English)"
|
224 |
+
|
225 |
+
#### Example Output:
|
226 |
+
```json
|
227 |
+
[
|
228 |
+
{"sentence": "Nous devons lancer la nouvelle ___ le mois prochain.", "answer": "campagne", "choices": ["campagne", "produit", "réunion"]},
|
229 |
+
{"sentence": "Quel est le ___ principal de ce projet ?", "answer": "objectif", "choices": ["client", "objectif", "budget"]},
|
230 |
+
{"sentence": "Il faut analyser le ___ avant de prendre une décision.", "answer": "marché", "choices": ["marché", "bureau", "téléphone"]},
|
231 |
+
{"sentence": "Elle prépare une ___ pour les clients.", "answer": "présentation", "choices": ["facture", "présentation", "publicité"]},
|
232 |
+
{"sentence": "Nous utilisons les ___ sociaux pour la promotion.", "answer": "réseaux", "choices": ["médias", "réseaux", "journaux"]}
|
233 |
+
]
|
234 |
+
"""
|
235 |
+
|
236 |
+
simulation_mode_instructions = """
|
237 |
+
# Metadata:
|
238 |
+
# Native language: {native_language}
|
239 |
+
# Target language: {target_language}
|
240 |
+
# Proficiency level: {proficiency}
|
241 |
+
|
242 |
+
You are a **creative, context-aware storytelling engine**. Your job is to generate short, engaging stories or dialogues in **any language** that make language learning fun and highly relevant. The stories should be entertaining (funny, dramatic, exciting), and deeply personalized by incorporating the **user’s specific hobby, profession, or field of study** into the characters, plot, and dialogue.
|
243 |
+
|
244 |
+
### Context Format
|
245 |
+
You will receive a list of prior messages:
|
246 |
+
[
|
247 |
+
{"role": "user", "content": "<user input>"},
|
248 |
+
{"role": "assistant", "content": "<last generated story>"}
|
249 |
+
]
|
250 |
+
Treat this list as prior conversation history. Use it to:
|
251 |
+
- Avoid repeating ideas, themes, or jokes from previous responses.
|
252 |
+
- Build on past tone, vocabulary, or characters if appropriate.
|
253 |
+
- Adjust story complexity based on past user proficiency or feedback cues.
|
254 |
+
|
255 |
+
### Story Generation Task
|
256 |
+
From the latest user message:
|
257 |
+
1. **Use the provided metadata**:
|
258 |
+
- **Native language**: The user’s base language for understanding.
|
259 |
+
- **Target language**: The language the user is learning.
|
260 |
+
- **Proficiency level**: Adjust the complexity of the story or dialogue based on the user’s proficiency level.
|
261 |
+
|
262 |
+
2. **Domain relevance**:
|
263 |
+
- Focus on the **user's domain of interest** (e.g., work, hobby, field of study).
|
264 |
+
- Use **realistic terminology or scenarios** related to their interests to make the story engaging and practical.
|
265 |
+
|
266 |
+
3. **Adjust story complexity**:
|
267 |
+
- For **beginner** learners, keep sentences simple and direct with basic vocabulary and grammar.
|
268 |
+
- For **intermediate** learners, use natural dialogue, simple narrative structures, and introduce moderately challenging vocabulary.
|
269 |
+
- For **advanced** learners, incorporate idiomatic expressions, complex sentence structures, and domain-specific language.
|
270 |
+
|
271 |
+
4. **Avoid repetition**:
|
272 |
+
- Ensure that new stories or dialogues bring fresh content and characters. Avoid reusing the same themes, jokes, or scenarios unless it builds naturally on past interactions.
|
273 |
+
|
274 |
+
5. **Engage with the user’s tone and interests**:
|
275 |
+
- If the user is passionate about a specific topic (e.g., cooking, space exploration, or law), integrate that into the story. If the user likes humor, use a fun tone; for drama or excitement, make the story engaging with conflict or high stakes.
|
276 |
+
|
277 |
+
### Output Format
|
278 |
+
Return a valid **JSON object** with the following structure:
|
279 |
+
- `"title"`: An engaging title in the **native language**.
|
280 |
+
- `"setting"`: A short setup in the **native language** explaining the story’s background, tailored to the user’s interest.
|
281 |
+
- `"content"`: A list of **6–10 segments**, each containing:
|
282 |
+
- `"speaker"`: Name or role of the speaker in the **native language** (e.g., "Narrator", "Professor Lee", "The Engineer").
|
283 |
+
- `"target_language_text"`: Sentence in the **target language**.
|
284 |
+
- `"phonetics"`: Standardized phonetic transcription (IPA, Pinyin, etc.) if applicable and helpful. Omit if unavailable or not useful.
|
285 |
+
- `"base_language_translation"`: Simple translation of the sentence in the **native language**.
|
286 |
+
|
287 |
+
### Personalization Rules
|
288 |
+
- Base the humor, conflict, and events directly on the user’s interest. For example:
|
289 |
+
- If the user loves space, create an exciting stargazing story.
|
290 |
+
- If they study law, create a courtroom dialogue with legal terms.
|
291 |
+
- If they’re into cooking, make the story about a cooking adventure.
|
292 |
+
- Include real terminology or realistic situations from the domain to make learning useful and immersive.
|
293 |
+
- Adjust the tone and vocabulary complexity based on user proficiency level (beginner = simple, intermediate = natural, advanced = idiomatic).
|
294 |
+
- Keep the pacing tight — avoid overly long narrations or explanations.
|
295 |
+
|
296 |
+
### Output Instructions
|
297 |
+
Return only the final **JSON object**. Do not include:
|
298 |
+
- Explanations
|
299 |
+
- Notes
|
300 |
+
- Comments
|
301 |
+
- Markdown formatting
|
302 |
+
|
303 |
+
### Example User Input
|
304 |
+
"Funny story for intermediate French learner about cooking hobby (base: English)"
|
305 |
+
|
306 |
+
### Example Output (French)
|
307 |
+
```json
|
308 |
+
{
|
309 |
+
"title": "La Panique de la Paella",
|
310 |
+
"setting": "Pierre essaie d'impressionner ses amis en cuisinant une paella espagnole authentique pour la première fois.",
|
311 |
+
"content": [
|
312 |
+
{
|
313 |
+
"speaker": "Narrateur",
|
314 |
+
"target_language_text": "Pierre regarda la recette de paella. Cela semblait facile.",
|
315 |
+
"phonetics": "pjeʁ ʁəɡaʁda la ʁesɛt də paɛʎa. sə.la sɛ̃blɛ ɛ.fa.sil",
|
316 |
+
"base_language_translation": "Pierre looked at the paella recipe. It seemed easy."
|
317 |
+
},
|
318 |
+
{
|
319 |
+
"speaker": "Pierre",
|
320 |
+
"target_language_text": "Il me faut du safran! Où est le safran?",
|
321 |
+
"phonetics": "il mə fo dy sa.fʁɑ̃! u ɛ lə sa.fʁɑ̃",
|
322 |
+
"base_language_translation": "I need saffron! Where is the saffron?"
|
323 |
+
},
|
324 |
+
{
|
325 |
+
"speaker": "Narrateur",
|
326 |
+
"target_language_text": "Pierre fouilla le placard, mais il ne trouva pas de safran.",
|
327 |
+
"phonetics": "pjeʁ fwi.jɑ lə pla.kɑʁ, mɛ il nə tʁu.va pa də sa.fʁɑ̃",
|
328 |
+
"base_language_translation": "Pierre searched the cupboard, but he couldn’t find any saffron."
|
329 |
+
},
|
330 |
+
{
|
331 |
+
"speaker": "Pierre",
|
332 |
+
"target_language_text": "Qu'est-ce que je vais faire maintenant ?",
|
333 |
+
"phonetics": "kɛs.kə ʒə vɛ fɛʁ mɛ̃tə.nɑ̃?",
|
334 |
+
"base_language_translation": "What am I going to do now?"
|
335 |
+
},
|
336 |
+
{
|
337 |
+
"speaker": "Narrateur",
|
338 |
+
"target_language_text": "Finalement, Pierre décida de remplacer le safran par du curcuma.",
|
339 |
+
"phonetics": "fi.nal.mɑ̃ pjeʁ de.si.da də ʁɑ̃.pla.sə lə sa.fʁɑ̃ paʁ dy kyʁ.ky.ma",
|
340 |
+
"base_language_translation": "Finally, Pierre decided to replace the saffron with turmeric."
|
341 |
+
},
|
342 |
+
{
|
343 |
+
"speaker": "Pierre",
|
344 |
+
"target_language_text": "C'est presque pareil, non ?",
|
345 |
+
"phonetics": "sɛ pʁɛs.kə paʁɛj, nɔ̃?",
|
346 |
+
"base_language_translation": "It's almost the same, right?"
|
347 |
+
}
|
348 |
+
]
|
349 |
+
}
|
350 |
+
"""
|
prev_backend_v1/prev_backend_v/database.py
ADDED
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import psycopg2
|
2 |
+
import os
|
3 |
+
from psycopg2 import sql
|
4 |
+
from dotenv import load_dotenv
|
5 |
+
|
6 |
+
load_dotenv()
|
7 |
+
|
8 |
+
# Database Configuration from environment variables
|
9 |
+
DB_NAME = os.getenv("POSTGRES_DB", "linguaai")
|
10 |
+
DB_USER = os.getenv("POSTGRES_USER", "linguaai_user")
|
11 |
+
DB_PASSWORD = os.getenv("POSTGRES_PASSWORD", "LinguaAI1008")
|
12 |
+
DB_HOST = os.getenv("DB_HOST", "localhost")
|
13 |
+
DB_PORT = os.getenv("DB_PORT", "5432")
|
14 |
+
|
15 |
+
# SQL Schema Definition
|
16 |
+
SCHEMA_SQL = """
|
17 |
+
-- Drop existing objects if they exist
|
18 |
+
-- Note: Some drops below might be for tables not defined in this specific script.
|
19 |
+
DROP TABLE IF EXISTS user_activity_progress CASCADE;
|
20 |
+
DROP TABLE IF EXISTS activities CASCADE;
|
21 |
+
DROP TABLE IF EXISTS weekly_modules CASCADE;
|
22 |
+
DROP TABLE IF EXISTS curriculums CASCADE;
|
23 |
+
DROP TABLE IF EXISTS generated_flashcards CASCADE;
|
24 |
+
DROP TABLE IF EXISTS flashcard_sets CASCADE; -- Corrected name
|
25 |
+
DROP TABLE IF EXISTS generated_exercises CASCADE;
|
26 |
+
DROP TABLE IF EXISTS exercise_sets CASCADE; -- Corrected name
|
27 |
+
DROP TABLE IF EXISTS simulations CASCADE; -- Corrected name
|
28 |
+
DROP TABLE IF EXISTS users CASCADE;
|
29 |
+
DROP TYPE IF EXISTS activity_status CASCADE;
|
30 |
+
|
31 |
+
-- Table `users`
|
32 |
+
CREATE TABLE users (
|
33 |
+
user_id SERIAL PRIMARY KEY,
|
34 |
+
username VARCHAR(50) UNIQUE NOT NULL,
|
35 |
+
email VARCHAR(100) UNIQUE NOT NULL,
|
36 |
+
password_hash VARCHAR(255) NOT NULL,
|
37 |
+
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
38 |
+
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
|
39 |
+
);
|
40 |
+
|
41 |
+
-- Trigger function (remains the same)
|
42 |
+
CREATE OR REPLACE FUNCTION update_updated_at_column()
|
43 |
+
RETURNS TRIGGER AS $$
|
44 |
+
BEGIN
|
45 |
+
NEW.updated_at = now();
|
46 |
+
RETURN NEW;
|
47 |
+
END;
|
48 |
+
$$ language 'plpgsql';
|
49 |
+
|
50 |
+
-- Trigger for users (remains the same)
|
51 |
+
CREATE TRIGGER users_update_updated_at
|
52 |
+
BEFORE UPDATE ON users
|
53 |
+
FOR EACH ROW
|
54 |
+
EXECUTE FUNCTION update_updated_at_column();
|
55 |
+
|
56 |
+
|
57 |
+
-- ============================================
|
58 |
+
-- Tables for Generated Content (Flashcards)
|
59 |
+
-- ============================================
|
60 |
+
|
61 |
+
-- Table `flashcard_sets` (Represents one request/query)
|
62 |
+
CREATE TABLE flashcard_sets (
|
63 |
+
id SERIAL PRIMARY KEY,
|
64 |
+
user_id INTEGER NOT NULL REFERENCES users(user_id), -- Added FK reference for completeness
|
65 |
+
query TEXT NOT NULL,
|
66 |
+
flashcards JSONB NOT NULL, -- Stores an array of 5 flashcards
|
67 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
68 |
+
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -- Added updated_at for consistency
|
69 |
+
);
|
70 |
+
|
71 |
+
CREATE INDEX idx_flashcard_set_user ON flashcard_sets(user_id);
|
72 |
+
|
73 |
+
-- Corrected Trigger definition for flashcard_sets
|
74 |
+
CREATE TRIGGER flashcard_sets_update_updated_at -- Renamed trigger
|
75 |
+
BEFORE UPDATE ON flashcard_sets -- Corrected table name
|
76 |
+
FOR EACH ROW
|
77 |
+
EXECUTE FUNCTION update_updated_at_column(); -- Assumes you want updated_at here too
|
78 |
+
|
79 |
+
-- Table `generated_flashcards` (Individual flashcards within a set)
|
80 |
+
CREATE TABLE generated_flashcards (
|
81 |
+
flashcard_id SERIAL PRIMARY KEY,
|
82 |
+
set_id INT NOT NULL REFERENCES flashcard_sets(id) ON DELETE CASCADE, -- Corrected FK reference (table and column)
|
83 |
+
word TEXT NOT NULL,
|
84 |
+
definition TEXT NOT NULL,
|
85 |
+
example TEXT, -- Example might be optional
|
86 |
+
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
87 |
+
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
|
88 |
+
);
|
89 |
+
|
90 |
+
CREATE INDEX idx_flashcard_set ON generated_flashcards(set_id);
|
91 |
+
|
92 |
+
-- Trigger for generated_flashcards (remains the same)
|
93 |
+
CREATE TRIGGER generated_flashcards_update_updated_at
|
94 |
+
BEFORE UPDATE ON generated_flashcards
|
95 |
+
FOR EACH ROW
|
96 |
+
EXECUTE FUNCTION update_updated_at_column();
|
97 |
+
|
98 |
+
|
99 |
+
-- ============================================
|
100 |
+
-- Tables for Generated Content (Exercises)
|
101 |
+
-- ============================================
|
102 |
+
|
103 |
+
-- Table `exercise_sets` (Represents one request/query) -- Corrected comment
|
104 |
+
CREATE TABLE exercise_sets (
|
105 |
+
id SERIAL PRIMARY KEY,
|
106 |
+
user_id INTEGER NOT NULL REFERENCES users(user_id), -- Added FK reference for completeness
|
107 |
+
query TEXT NOT NULL,
|
108 |
+
exercises JSONB NOT NULL, -- Array of 5 exercises
|
109 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
110 |
+
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -- Added updated_at for consistency
|
111 |
+
);
|
112 |
+
|
113 |
+
CREATE INDEX idx_exercise_set_user ON exercise_sets(user_id); -- Corrected table name (was already correct but double-checked)
|
114 |
+
|
115 |
+
-- Corrected Trigger definition for exercise_sets
|
116 |
+
CREATE TRIGGER exercise_sets_update_updated_at -- Renamed trigger
|
117 |
+
BEFORE UPDATE ON exercise_sets -- Corrected table name
|
118 |
+
FOR EACH ROW
|
119 |
+
EXECUTE FUNCTION update_updated_at_column(); -- Assumes you want updated_at here too
|
120 |
+
|
121 |
+
-- Table `generated_exercises` (Individual exercises within a set)
|
122 |
+
CREATE TABLE generated_exercises (
|
123 |
+
exercise_id SERIAL PRIMARY KEY,
|
124 |
+
set_id INT NOT NULL REFERENCES exercise_sets(id) ON DELETE CASCADE, -- Corrected FK reference (table and column)
|
125 |
+
sentence TEXT NOT NULL,
|
126 |
+
answer TEXT NOT NULL,
|
127 |
+
choices JSONB NOT NULL, -- Storing the array of choices
|
128 |
+
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
129 |
+
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
|
130 |
+
);
|
131 |
+
|
132 |
+
CREATE INDEX idx_exercise_set ON generated_exercises(set_id);
|
133 |
+
|
134 |
+
-- Trigger for generated_exercises (remains the same)
|
135 |
+
CREATE TRIGGER generated_exercises_update_updated_at
|
136 |
+
BEFORE UPDATE ON generated_exercises
|
137 |
+
FOR EACH ROW
|
138 |
+
EXECUTE FUNCTION update_updated_at_column();
|
139 |
+
|
140 |
+
|
141 |
+
-- ============================================
|
142 |
+
-- Table for Generated Content (Simulations)
|
143 |
+
-- ============================================
|
144 |
+
|
145 |
+
-- Table `simulations` (Represents one simulation request/result) -- Corrected comment
|
146 |
+
CREATE TABLE simulations (
|
147 |
+
id SERIAL PRIMARY KEY,
|
148 |
+
user_id INTEGER NOT NULL REFERENCES users(user_id), -- Added FK reference for completeness
|
149 |
+
query TEXT NOT NULL,
|
150 |
+
scenario TEXT NOT NULL,
|
151 |
+
dialog JSONB NOT NULL, -- Array of turns with 'role', 'chinese', 'pinyin', 'english'
|
152 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
153 |
+
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -- Added updated_at for consistency
|
154 |
+
);
|
155 |
+
|
156 |
+
CREATE INDEX idx_simulation_user ON simulations(user_id); -- Corrected table name
|
157 |
+
|
158 |
+
-- Corrected Trigger definition for simulations
|
159 |
+
CREATE TRIGGER simulations_update_updated_at -- Renamed trigger
|
160 |
+
BEFORE UPDATE ON simulations -- Corrected table name
|
161 |
+
FOR EACH ROW
|
162 |
+
EXECUTE FUNCTION update_updated_at_column(); -- Assumes you want updated_at here too
|
163 |
+
"""
|
164 |
+
|
165 |
+
def get_db_connection():
|
166 |
+
"""Get a synchronous database connection."""
|
167 |
+
try:
|
168 |
+
conn = psycopg2.connect(
|
169 |
+
dbname=DB_NAME,
|
170 |
+
user=DB_USER,
|
171 |
+
password=DB_PASSWORD,
|
172 |
+
host=DB_HOST,
|
173 |
+
port=DB_PORT
|
174 |
+
)
|
175 |
+
return conn
|
176 |
+
except psycopg2.Error as e:
|
177 |
+
print(f"Database connection error: {e}")
|
178 |
+
raise
|
179 |
+
|
180 |
+
def reset_sequences():
|
181 |
+
"""Generate SQL to reset all sequences (auto-incrementing IDs) to 1."""
|
182 |
+
sequences_sql = """
|
183 |
+
SELECT 'ALTER SEQUENCE ' || sequence_name || ' RESTART WITH 1;'
|
184 |
+
FROM information_schema.sequences
|
185 |
+
WHERE sequence_schema = 'public';
|
186 |
+
"""
|
187 |
+
return sequences_sql
|
188 |
+
|
189 |
+
def reset_database(confirm=True):
|
190 |
+
"""Reset the database by dropping all tables and recreating them."""
|
191 |
+
if confirm:
|
192 |
+
user_confirm = input("WARNING: This will DELETE ALL DATA. Type 'yes' to proceed: ")
|
193 |
+
if user_confirm.lower() != 'yes':
|
194 |
+
print("Database reset cancelled.")
|
195 |
+
return
|
196 |
+
|
197 |
+
conn = None
|
198 |
+
try:
|
199 |
+
conn = get_db_connection()
|
200 |
+
conn.autocommit = False
|
201 |
+
print("Database connection established.")
|
202 |
+
|
203 |
+
with conn.cursor() as cur:
|
204 |
+
print("Dropping and recreating schema...")
|
205 |
+
# Execute the main schema SQL (includes drops)
|
206 |
+
cur.execute(SCHEMA_SQL)
|
207 |
+
print("Schema recreated successfully.")
|
208 |
+
|
209 |
+
# Generate and execute sequence reset SQL
|
210 |
+
print("Resetting sequences...")
|
211 |
+
reset_sql_query = reset_sequences()
|
212 |
+
cur.execute(reset_sql_query)
|
213 |
+
reset_commands = cur.fetchall()
|
214 |
+
for command in reset_commands:
|
215 |
+
cur.execute(command[0])
|
216 |
+
print("Sequences reset successfully.")
|
217 |
+
|
218 |
+
conn.commit()
|
219 |
+
print("Database reset complete.")
|
220 |
+
|
221 |
+
except psycopg2.Error as e:
|
222 |
+
print(f"Database error during reset: {e}")
|
223 |
+
if conn:
|
224 |
+
conn.rollback()
|
225 |
+
print("Transaction rolled back.")
|
226 |
+
except Exception as e:
|
227 |
+
print(f"An unexpected error occurred during reset: {e}")
|
228 |
+
if conn:
|
229 |
+
conn.rollback()
|
230 |
+
finally:
|
231 |
+
if conn:
|
232 |
+
conn.close()
|
233 |
+
print("Database connection closed.")
|
234 |
+
|
235 |
+
def setup_database(confirm=True):
|
236 |
+
"""Set up the database schema if tables do not exist."""
|
237 |
+
if confirm:
|
238 |
+
user_confirm = input("Do you want to set up the database? Type 'yes' to proceed: ")
|
239 |
+
if user_confirm.lower() != 'yes':
|
240 |
+
print("Database setup cancelled.")
|
241 |
+
return
|
242 |
+
|
243 |
+
conn = None
|
244 |
+
try:
|
245 |
+
conn = get_db_connection()
|
246 |
+
conn.autocommit = False
|
247 |
+
print("Database connection established.")
|
248 |
+
|
249 |
+
with conn.cursor() as cur:
|
250 |
+
print("Checking if tables exist...")
|
251 |
+
cur.execute("""
|
252 |
+
SELECT EXISTS (
|
253 |
+
SELECT FROM information_schema.tables
|
254 |
+
WHERE table_schema = 'public'
|
255 |
+
AND table_name = 'users'
|
256 |
+
);
|
257 |
+
""")
|
258 |
+
tables_exist = cur.fetchone()[0]
|
259 |
+
|
260 |
+
if tables_exist:
|
261 |
+
print("Tables already exist. Use reset_database() to reset the database or run setup with confirm=False.")
|
262 |
+
conn.rollback() # Rollback as no changes should be made
|
263 |
+
return
|
264 |
+
|
265 |
+
print("Creating schema...")
|
266 |
+
cur.execute(SCHEMA_SQL)
|
267 |
+
print("Schema created successfully.")
|
268 |
+
|
269 |
+
conn.commit()
|
270 |
+
print("Database setup complete.")
|
271 |
+
|
272 |
+
except psycopg2.Error as e:
|
273 |
+
print(f"Database error during setup: {e}")
|
274 |
+
if conn:
|
275 |
+
conn.rollback()
|
276 |
+
print("Transaction rolled back.")
|
277 |
+
except Exception as e:
|
278 |
+
print(f"An unexpected error occurred during setup: {e}")
|
279 |
+
if conn:
|
280 |
+
conn.rollback()
|
281 |
+
finally:
|
282 |
+
if conn:
|
283 |
+
conn.close()
|
284 |
+
print("Database connection closed.")
|
285 |
+
|
286 |
+
if __name__ == "__main__":
|
287 |
+
action = input("Enter 'setup' to setup database or 'reset' to reset database: ").lower()
|
288 |
+
if action == 'reset':
|
289 |
+
reset_database()
|
290 |
+
elif action == 'setup':
|
291 |
+
setup_database()
|
292 |
+
else:
|
293 |
+
print("Invalid action. Use 'setup' or 'reset'.")
|
prev_backend_v1/prev_backend_v/main.py
ADDED
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from fastapi.responses import JSONResponse
|
3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
4 |
+
from pydantic import BaseModel
|
5 |
+
from backend.utils import generate_completions
|
6 |
+
from backend import config
|
7 |
+
from backend.database import get_db_connection
|
8 |
+
import psycopg2
|
9 |
+
from psycopg2.extras import RealDictCursor
|
10 |
+
from typing import Union, List, Literal, Optional
|
11 |
+
import logging
|
12 |
+
import json
|
13 |
+
|
14 |
+
logging.basicConfig(level=logging.INFO)
|
15 |
+
|
16 |
+
app = FastAPI()
|
17 |
+
|
18 |
+
# Add CORS middleware
|
19 |
+
app.add_middleware(
|
20 |
+
CORSMiddleware,
|
21 |
+
allow_origins=["*"], # Allows all origins
|
22 |
+
allow_credentials=True,
|
23 |
+
allow_methods=["*"], # Allows all methods
|
24 |
+
allow_headers=["*"], # Allows all headers
|
25 |
+
)
|
26 |
+
|
27 |
+
# Dependency to get database connection
|
28 |
+
async def get_db():
|
29 |
+
conn = await get_db_connection()
|
30 |
+
try:
|
31 |
+
yield conn
|
32 |
+
finally:
|
33 |
+
conn.close()
|
34 |
+
|
35 |
+
class Message(BaseModel):
|
36 |
+
role: Literal["user", "assistant"]
|
37 |
+
content: str
|
38 |
+
|
39 |
+
class GenerationRequest(BaseModel):
|
40 |
+
user_id: int
|
41 |
+
query: Union[str, List[Message]]
|
42 |
+
|
43 |
+
class MetadataRequest(BaseModel):
|
44 |
+
query: str
|
45 |
+
|
46 |
+
# Global metadata variables
|
47 |
+
native_language: Optional[str] = None
|
48 |
+
target_language: Optional[str] = None
|
49 |
+
proficiency: Optional[str] = None
|
50 |
+
|
51 |
+
@app.get("/")
|
52 |
+
async def root():
|
53 |
+
return {"message": "Welcome to the AI Learning Assistant API!"}
|
54 |
+
|
55 |
+
@app.post("/extract/metadata")
|
56 |
+
async def extract_metadata(data: MetadataRequest):
|
57 |
+
logging.info(f"Query: {data.query}")
|
58 |
+
try:
|
59 |
+
response_str = await generate_completions.get_completions(
|
60 |
+
data.query,
|
61 |
+
config.language_metadata_extraction_prompt
|
62 |
+
)
|
63 |
+
metadata_dict = json.loads(response_str)
|
64 |
+
# Update globals for other endpoints
|
65 |
+
globals()['native_language'] = metadata_dict.get('native_language', 'unknown')
|
66 |
+
globals()['target_language'] = metadata_dict.get('target_language', 'unknown')
|
67 |
+
globals()['proficiency'] = metadata_dict.get('proficiency_level', 'unknown')
|
68 |
+
return JSONResponse(
|
69 |
+
content={
|
70 |
+
"data": metadata_dict,
|
71 |
+
"type": "language_metadata",
|
72 |
+
"status": "success"
|
73 |
+
},
|
74 |
+
status_code=200
|
75 |
+
)
|
76 |
+
except Exception as e:
|
77 |
+
raise HTTPException(status_code=500, detail=str(e))
|
78 |
+
|
79 |
+
@app.post("/generate/curriculum")
|
80 |
+
async def generate_curriculum(data: GenerationRequest):
|
81 |
+
try:
|
82 |
+
# Use previously extracted metadata
|
83 |
+
instructions = (
|
84 |
+
config.curriculum_instructions
|
85 |
+
.replace("{native_language}", native_language or "unknown")
|
86 |
+
.replace("{target_language}", target_language or "unknown")
|
87 |
+
.replace("{proficiency}", proficiency or "unknown")
|
88 |
+
)
|
89 |
+
response = await generate_completions.get_completions(
|
90 |
+
data.query,
|
91 |
+
instructions
|
92 |
+
)
|
93 |
+
return JSONResponse(
|
94 |
+
content={
|
95 |
+
"data": response,
|
96 |
+
"type": "curriculum",
|
97 |
+
"status": "success"
|
98 |
+
},
|
99 |
+
status_code=200
|
100 |
+
)
|
101 |
+
except Exception as e:
|
102 |
+
raise HTTPException(status_code=500, detail=str(e))
|
103 |
+
|
104 |
+
@app.post("/generate/flashcards")
|
105 |
+
async def generate_flashcards(data: GenerationRequest):
|
106 |
+
try:
|
107 |
+
# Use previously extracted metadata
|
108 |
+
instructions = (
|
109 |
+
config.flashcard_mode_instructions
|
110 |
+
.replace("{native_language}", native_language or "unknown")
|
111 |
+
.replace("{target_language}", target_language or "unknown")
|
112 |
+
.replace("{proficiency}", proficiency or "unknown")
|
113 |
+
)
|
114 |
+
response = await generate_completions.get_completions(
|
115 |
+
data.query,
|
116 |
+
instructions
|
117 |
+
)
|
118 |
+
return JSONResponse(
|
119 |
+
content={
|
120 |
+
"data": response,
|
121 |
+
"type": "flashcards",
|
122 |
+
"status": "success"
|
123 |
+
},
|
124 |
+
status_code=200
|
125 |
+
)
|
126 |
+
except Exception as e:
|
127 |
+
raise HTTPException(status_code=500, detail=str(e))
|
128 |
+
|
129 |
+
@app.post("/generate/exercises")
|
130 |
+
async def generate_exercises(data: GenerationRequest):
|
131 |
+
try:
|
132 |
+
# Use previously extracted metadata
|
133 |
+
instructions = (
|
134 |
+
config.exercise_mode_instructions
|
135 |
+
.replace("{native_language}", native_language or "unknown")
|
136 |
+
.replace("{target_language}", target_language or "unknown")
|
137 |
+
.replace("{proficiency}", proficiency or "unknown")
|
138 |
+
)
|
139 |
+
response = await generate_completions.get_completions(
|
140 |
+
data.query,
|
141 |
+
instructions
|
142 |
+
)
|
143 |
+
return JSONResponse(
|
144 |
+
content={
|
145 |
+
"data": response,
|
146 |
+
"type": "exercises",
|
147 |
+
"status": "success"
|
148 |
+
},
|
149 |
+
status_code=200
|
150 |
+
)
|
151 |
+
except Exception as e:
|
152 |
+
raise HTTPException(status_code=500, detail=str(e))
|
153 |
+
|
154 |
+
@app.post("/generate/simulation")
|
155 |
+
async def generate_simulation(data: GenerationRequest):
|
156 |
+
try:
|
157 |
+
# Use previously extracted metadata
|
158 |
+
instructions = (
|
159 |
+
config.simulation_mode_instructions
|
160 |
+
.replace("{native_language}", native_language or "unknown")
|
161 |
+
.replace("{target_language}", target_language or "unknown")
|
162 |
+
.replace("{proficiency}", proficiency or "unknown")
|
163 |
+
)
|
164 |
+
response = await generate_completions.get_completions(
|
165 |
+
data.query,
|
166 |
+
instructions
|
167 |
+
)
|
168 |
+
return JSONResponse(
|
169 |
+
content={
|
170 |
+
"data": response,
|
171 |
+
"type": "simulation",
|
172 |
+
"status": "success"
|
173 |
+
},
|
174 |
+
status_code=200
|
175 |
+
)
|
176 |
+
except Exception as e:
|
177 |
+
raise HTTPException(status_code=500, detail=str(e))
|
prev_backend_v1/prev_backend_v/utils/__pycache__/generate_completions.cpython-310.pyc
ADDED
Binary file (2.55 kB). View file
|
|
prev_backend_v1/prev_backend_v/utils/__pycache__/generate_completions.cpython-312.pyc
ADDED
Binary file (3.7 kB). View file
|
|
prev_backend_v1/prev_backend_v/utils/generate_completions.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from openai import AsyncOpenAI, OpenAI
|
2 |
+
import asyncio
|
3 |
+
import json
|
4 |
+
from typing import AsyncIterator
|
5 |
+
from typing import Union, List, Dict, Literal
|
6 |
+
from dotenv import load_dotenv
|
7 |
+
import os
|
8 |
+
from pydantic import BaseModel
|
9 |
+
load_dotenv()
|
10 |
+
|
11 |
+
# Initialize the async client
|
12 |
+
client = AsyncOpenAI(
|
13 |
+
base_url=os.getenv("BASE_URL"),
|
14 |
+
api_key=os.getenv("API_KEY"),
|
15 |
+
)
|
16 |
+
|
17 |
+
class Message(BaseModel):
|
18 |
+
role: Literal["user", "assistant"]
|
19 |
+
content: str
|
20 |
+
|
21 |
+
# Helper function to flatten chat messages into a single string prompt
|
22 |
+
def flatten_messages(messages: List[Message]) -> str:
|
23 |
+
return "\n".join([f"{m.role}: {m.content}" for m in messages])
|
24 |
+
|
25 |
+
def process_input(data: Union[str, List[Dict[str, str]]]) -> Union[str, List[Dict[str, str]]]:
|
26 |
+
"""
|
27 |
+
Processes input to either uppercase a string or modify the 'content' field
|
28 |
+
of a list of dictionaries.
|
29 |
+
"""
|
30 |
+
if isinstance(data, str):
|
31 |
+
return data.strip() # Ensures prompt is cleaned up (optional)
|
32 |
+
|
33 |
+
elif isinstance(data, list):
|
34 |
+
# Ensure each item in the list is a dictionary with a 'content' key
|
35 |
+
return [
|
36 |
+
{**item, "content": item["content"].strip()} # Trims whitespace in 'content'
|
37 |
+
for item in data if isinstance(item, dict) and "content" in item
|
38 |
+
]
|
39 |
+
|
40 |
+
else:
|
41 |
+
raise TypeError("Input must be a string or a list of dictionaries with a 'content' field")
|
42 |
+
|
43 |
+
|
44 |
+
# async def get_completions(
|
45 |
+
# prompt: Union[str, List[Dict[str, str]]],
|
46 |
+
# instructions: str
|
47 |
+
# ) -> str:
|
48 |
+
# processed_prompt = process_input(prompt) # Ensures the input format is correct
|
49 |
+
|
50 |
+
# if isinstance(processed_prompt, str):
|
51 |
+
# messages = [
|
52 |
+
# {"role": "system", "content": instructions},
|
53 |
+
# {"role": "user", "content": processed_prompt}
|
54 |
+
# ]
|
55 |
+
# elif isinstance(processed_prompt, list):
|
56 |
+
# messages = [{"role": "system", "content": instructions}] + processed_prompt
|
57 |
+
# else:
|
58 |
+
# raise TypeError("Unexpected processed input type.")
|
59 |
+
|
60 |
+
# response = await client.chat.completions.create(
|
61 |
+
# model=os.getenv("MODEL"),
|
62 |
+
# messages=messages,
|
63 |
+
# response_format={"type": "json_object"}
|
64 |
+
# )
|
65 |
+
|
66 |
+
# output: str = response.choices[0].message.content
|
67 |
+
# return output
|
68 |
+
|
69 |
+
async def get_completions(
|
70 |
+
prompt: Union[str, List[Dict[str, str]]],
|
71 |
+
instructions: str
|
72 |
+
) -> str:
|
73 |
+
if isinstance(prompt, list):
|
74 |
+
formatted_query = flatten_messages(prompt)
|
75 |
+
else:
|
76 |
+
formatted_query = prompt
|
77 |
+
|
78 |
+
processed_prompt = process_input(formatted_query)
|
79 |
+
|
80 |
+
messages = [{"role": "system", "content": instructions}]
|
81 |
+
|
82 |
+
if isinstance(processed_prompt, str):
|
83 |
+
messages.append({"role": "user", "content": processed_prompt})
|
84 |
+
|
85 |
+
elif isinstance(processed_prompt, list):
|
86 |
+
# Only keep the history for context and append the latest user query at the end
|
87 |
+
history = processed_prompt[:-1]
|
88 |
+
last_user_msg = processed_prompt[-1]
|
89 |
+
|
90 |
+
# Optional: Validate that the last message is from the user
|
91 |
+
if last_user_msg.get("role") != "user":
|
92 |
+
raise ValueError("Last message must be from the user.")
|
93 |
+
|
94 |
+
messages += history
|
95 |
+
messages.append(last_user_msg)
|
96 |
+
|
97 |
+
else:
|
98 |
+
raise TypeError("Unexpected processed input type.")
|
99 |
+
|
100 |
+
# print(os.getenv("MODEL"))
|
101 |
+
response = await client.chat.completions.create(
|
102 |
+
model=os.getenv("MODEL"),
|
103 |
+
messages=messages,
|
104 |
+
response_format={"type": "json_object"}
|
105 |
+
)
|
106 |
+
|
107 |
+
return response.choices[0].message.content # adjust based on your client
|
prev_backend_v2/backend/__pycache__/config.cpython-310.pyc
ADDED
Binary file (12 kB). View file
|
|
prev_backend_v2/backend/__pycache__/config.cpython-312.pyc
ADDED
Binary file (17.4 kB). View file
|
|
prev_backend_v2/backend/__pycache__/database.cpython-310.pyc
ADDED
Binary file (10.1 kB). View file
|
|
prev_backend_v2/backend/__pycache__/database.cpython-312.pyc
ADDED
Binary file (12.6 kB). View file
|
|
prev_backend_v2/backend/__pycache__/main.cpython-310.pyc
ADDED
Binary file (3.28 kB). View file
|
|
prev_backend_v2/backend/__pycache__/main.cpython-312.pyc
ADDED
Binary file (8.49 kB). View file
|
|
prev_backend_v2/backend/config.py
ADDED
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
language_metadata_extraction_prompt = """
|
2 |
+
You are a language learning assistant. Your task is to analyze the user's input and infer their:
|
3 |
+
- Native language (use the language of the input as a fallback if unsure)
|
4 |
+
- Target language (the one they want to learn)
|
5 |
+
- Proficiency level (beginner, intermediate, or advanced)
|
6 |
+
- Title (a brief title summarizing the user's language learning context, written in the user's native language)
|
7 |
+
- Description (a catchy, short description of their learning journey, written in the user's native language)
|
8 |
+
|
9 |
+
Respond ONLY with a valid JSON object using the following format:
|
10 |
+
|
11 |
+
{
|
12 |
+
"native_language": "<user's native language>",
|
13 |
+
"target_language": "<language the user wants to learn>",
|
14 |
+
"proficiency": "<beginner | intermediate | advanced>",
|
15 |
+
"title": "<brief title summarizing the learning context, in the native language>",
|
16 |
+
"description": "<catchy, short description of the learning journey, in the native language>"
|
17 |
+
}
|
18 |
+
|
19 |
+
Guidelines:
|
20 |
+
- If the user's native language is not explicitly stated, assume it's the same as the language used in the query.
|
21 |
+
- If the target language is mentioned indirectly (e.g., "my Dutch isn't great"), infer that as the target language.
|
22 |
+
- Make a reasonable guess at proficiency based on clues like "isn't great" → beginner or "I want to improve" → intermediate.
|
23 |
+
- If you cannot infer something at all, write "unknown" for native_language, target_language, or proficiency.
|
24 |
+
- After inferring the native language, ALWAYS generate the title and description in that language, regardless of the query language or any other context.
|
25 |
+
- For title, create a concise phrase (e.g., "Beginner Dutch Adventure" or "Improving Spanish Skills") based on the inferred target language and proficiency, and write it in the user's native language.
|
26 |
+
- For description, craft a catchy, short sentence (10-15 words max) that captures the user's learning journey, and write it in the user's native language.
|
27 |
+
- If target_language or proficiency is "unknown," use generic but engaging phrases for title and description (e.g., "Language Learning Quest," "Embarking on a new linguistic journey!"), but always in the user's native language.
|
28 |
+
- Do not include any explanations, comments, or formatting — only valid JSON.
|
29 |
+
|
30 |
+
Example:
|
31 |
+
User query: "i want to improve my english"
|
32 |
+
Expected output:
|
33 |
+
{
|
34 |
+
"native_language": "english",
|
35 |
+
"target_language": "english",
|
36 |
+
"proficiency": "intermediate",
|
37 |
+
"title": "Improving English Skills",
|
38 |
+
"description": "A journey to perfect English for greater fluency and confidence!"
|
39 |
+
}
|
40 |
+
"""
|
41 |
+
|
42 |
+
curriculum_instructions = """
|
43 |
+
# Metadata:
|
44 |
+
# Native language: {native_language}
|
45 |
+
# Target language: {target_language}
|
46 |
+
# Proficiency level: {proficiency}
|
47 |
+
|
48 |
+
You are an AI-powered language learning assistant tasked with generating an extensive, personalized curriculum. Your goal is to help the user learn {target_language} by designing a 25-lesson curriculum that reflects the user's goals, interests, and proficiency level. All outputs should be written in {native_language}.
|
49 |
+
|
50 |
+
### Curriculum Goals:
|
51 |
+
- Provide 25 lessons.
|
52 |
+
- Ensure logical progression from basic to advanced topics (according to {proficiency}).
|
53 |
+
- Align each lesson with a practical communication goal.
|
54 |
+
- Tailor vocabulary and sub-topics to the user’s intended use (e.g., work, travel, hobbies, daily life).
|
55 |
+
|
56 |
+
### Instructions:
|
57 |
+
|
58 |
+
1. **Define the Lesson Series (Overall Theme):**
|
59 |
+
- Choose a main theme relevant to the user's motivation for learning {target_language} (e.g., "Living in a new country", "Professional communication", "Traveling in {target_language}-speaking regions").
|
60 |
+
- The theme should guide the tone, content, and scope of the entire 25-lesson sequence.
|
61 |
+
|
62 |
+
2. **Divide the Curriculum into 25 Thematic Lessons:**
|
63 |
+
- Each lesson should have a clear focus (e.g., asking for help, describing your job, booking accommodation).
|
64 |
+
- Sequence lessons to build from foundational topics to more complex, specialized language use.
|
65 |
+
- Vary grammar, vocabulary, and communication functions across lessons to avoid repetition and ensure comprehensive coverage.
|
66 |
+
|
67 |
+
3. **Describe Each Lesson Clearly and Concisely:**
|
68 |
+
For each of the 25 lessons, provide:
|
69 |
+
- "sub_topic": A clear and practical lesson title in {native_language}.
|
70 |
+
- "keywords": A list of 1–3 high-level categories in {native_language} that describe the lesson focus (e.g., "directions", "daily routine", "formal conversation").
|
71 |
+
- "description": One sentence in {native_language} that explains what the learner will achieve or be able to do after completing the lesson. Be specific and learner-oriented.
|
72 |
+
|
73 |
+
### Output Format:
|
74 |
+
Return a valid JSON object with:
|
75 |
+
- "lesson_topic": The overall learning theme (in {native_language}).
|
76 |
+
- "sub_topics": A list of 25 items. Each item must include:
|
77 |
+
- "sub_topic": A short title of the lesson (in {native_language}).
|
78 |
+
- "keywords": A list of 1–3 general-purpose categories (in {native_language}).
|
79 |
+
- "description": One clear sentence (in {native_language}) describing the purpose of the lesson.
|
80 |
+
|
81 |
+
Avoid:
|
82 |
+
- Using overly generic or repetitive titles or descriptions.
|
83 |
+
- Keyword lists with only one-word entries (e.g., use "ordering in a restaurant" instead of "food").
|
84 |
+
- Abstract lessons with no real-world relevance.
|
85 |
+
|
86 |
+
Ensure the curriculum builds toward user fluency in relevant contexts.
|
87 |
+
"""
|
88 |
+
|
89 |
+
exercise_mode_instructions = """
|
90 |
+
# Metadata:
|
91 |
+
# Native language: {native_language}
|
92 |
+
# Target language: {target_language}
|
93 |
+
# Proficiency level: {proficiency}
|
94 |
+
|
95 |
+
You are a smart, context-aware language exercise generator. Your task is to create personalized cloze-style exercises that help learners reinforce vocabulary and grammar through realistic, domain-specific practice. You support any language.
|
96 |
+
|
97 |
+
### Input Format
|
98 |
+
You will receive a structured lesson or topic description (e.g., text excerpt, dialogue, thematic scenario). For example, this could be a short paragraph about daily routines, a dialogue between a customer and a shopkeeper, or a scenario involving travel planning. Use it to:
|
99 |
+
- Identify 5 concrete vocabulary items or grammar points suited to the learner’s immediate needs.
|
100 |
+
- Ground each exercise in a specific, vivid scenario.
|
101 |
+
- Reflect real-world tasks or conversations the learner will encounter.
|
102 |
+
|
103 |
+
### Generation Guidelines
|
104 |
+
1. **Metadata usage**
|
105 |
+
- **Native language**: Use {native_language} for all explanations.
|
106 |
+
- **Target language**: Use {target_language} for sentences, answers, and choices.
|
107 |
+
- **Proficiency**:
|
108 |
+
- *Beginner*: Focus on high-frequency vocabulary and simple grammar structures, such as present tense, basic prepositions, and common nouns and verbs.
|
109 |
+
- *Intermediate*: Incorporate a mix of common and thematic vocabulary, and introduce one new tense or grammatical structure per exercise.
|
110 |
+
- *Advanced*: Use domain-specific terminology, idiomatic expressions, and complex syntax to challenge learners.
|
111 |
+
|
112 |
+
2. **Sentence specificity**
|
113 |
+
- Craft each sentence around a concrete action, object, or event (e.g., “At the café counter, she ___ her order,” not “I want to ___”). To make exercises more engaging, consider adding details that paint a vivid picture, such as specific locations, times, or characters. For instance, use "On a sunny Saturday morning, Maria is heading to the local farmers' market to buy fresh produce" instead of "I am going to the store."
|
114 |
+
- Avoid “template” prompts like “I am going to ___” or “I like to ___” without added context.
|
115 |
+
- Each sentence must clearly point to one—and only one—correct word or structure.
|
116 |
+
|
117 |
+
3. **Unique, unambiguous answers**
|
118 |
+
- Design each prompt so distractors could be grammatically plausible but contextually impossible. For example, if the sentence is "She ___ the book on the table," and the correct answer is "put," ensure only "put" fits the context, while distractors like "placed," "set," or "laid" are plausible but incorrect here.
|
119 |
+
- Ensure there is no secondary interpretation that could validate another choice.
|
120 |
+
|
121 |
+
4. **Plausible distractors**
|
122 |
+
- Provide four total options: one correct, three context-related but incorrect.
|
123 |
+
- Distractors must belong to the same word class (noun, verb, adjective, etc.) and semantic field.
|
124 |
+
- Shuffle answer positions randomly.
|
125 |
+
- Ensure distractors are not too similar to the correct answer to avoid confusion.
|
126 |
+
|
127 |
+
5. **Explanations**
|
128 |
+
- Offer a concise 1–2-sentence rationale in {native_language}, explaining why the correct answer fits this very context and briefly noting why each distractor fails. If space allows, consider adding a brief example or analogy to reinforce the learning point.
|
129 |
+
|
130 |
+
### Output Format
|
131 |
+
Return exactly **5** cloze-style exercises as a **JSON array**, each element with:
|
132 |
+
- `"sentence"`: A fully contextualized sentence in {target_language} containing one blank (`___`).
|
133 |
+
- `"answer"`: The single correct fill-in, in {target_language}.
|
134 |
+
- `"choices"`: A list of four total options (in randomized order), all in {target_language}.
|
135 |
+
- `"explanation"`: A concise note in {native_language} clarifying the correct answer and why others don’t fit.
|
136 |
+
|
137 |
+
_Do not wrap the array in any additional objects or metadata—output only the raw JSON array._
|
138 |
+
"""
|
139 |
+
|
140 |
+
flashcard_mode_instructions = """
|
141 |
+
# Metadata:
|
142 |
+
# Native language: {native_language}
|
143 |
+
# Target language: {target_language}
|
144 |
+
# Proficiency level: {proficiency}
|
145 |
+
|
146 |
+
You are a highly adaptive vocabulary tutor capable of teaching any language. Your goal is to help users learn rapidly by generating personalized flashcards from lesson-based content.
|
147 |
+
|
148 |
+
### Input Format
|
149 |
+
You will receive a structured lesson as input (text, dialogue, or vocabulary list). Use this input to:
|
150 |
+
- Identify new or useful vocabulary terms.
|
151 |
+
- Extract contextually relevant and domain-specific language.
|
152 |
+
- Ensure that flashcards reflect the lesson's language, style, and purpose.
|
153 |
+
|
154 |
+
### Generation Guidelines
|
155 |
+
When generating flashcards:
|
156 |
+
1. **Use the provided metadata**:
|
157 |
+
- **Native language**: Use {native_language} for definitions.
|
158 |
+
- **Target language**: Extract and present vocabulary and examples in {target_language}.
|
159 |
+
- **Proficiency level**: Adjust vocabulary complexity based on {proficiency}:
|
160 |
+
- *Beginner*: High-frequency, essential words.
|
161 |
+
- *Intermediate*: Broader, topic-specific terms and common collocations.
|
162 |
+
- *Advanced*: Nuanced, idiomatic, or technical vocabulary.
|
163 |
+
|
164 |
+
2. **Contextual relevance**:
|
165 |
+
- Flashcards should reflect the themes, activities, or domain of the lesson input (e.g., cooking, business, travel).
|
166 |
+
- Ensure that example sentences are directly related to the input content and sound natural in use.
|
167 |
+
|
168 |
+
3. **Avoid redundancy**:
|
169 |
+
- Select terms that are novel, useful, or not overly repetitive within the lesson.
|
170 |
+
- Prioritize terms that learners are likely to encounter again in real-world usage.
|
171 |
+
|
172 |
+
### Flashcard Format
|
173 |
+
Generate exactly **10 flashcards** as a **valid JSON array**, with each flashcard containing:
|
174 |
+
- `"word"`: A key word or phrase in {target_language} drawn from the lesson.
|
175 |
+
- `"definition"`: A learner-friendly explanation in {native_language}.
|
176 |
+
- `"example"`: A clear, natural sentence in {target_language} demonstrating the word **in context with the lesson**.
|
177 |
+
"""
|
178 |
+
|
179 |
+
simulation_mode_instructions = """
|
180 |
+
# Metadata:
|
181 |
+
# Native language: {native_language}
|
182 |
+
# Target language: {target_language}
|
183 |
+
# Proficiency level: {proficiency}
|
184 |
+
|
185 |
+
You are a **creative, context-aware storytelling engine**. Your task is to generate short, engaging stories or dialogues in **any language** to make language learning enjoyable, memorable, and relevant. Stories must reflect the user's interests, profession, or hobbies, and align with their learning level.
|
186 |
+
|
187 |
+
### Input Format
|
188 |
+
You will receive a user-provided **lesson topic, theme, or domain of interest** (e.g., “a courtroom drama for a law student” or “space mission dialogue for a space enthusiast”). Use this input to:
|
189 |
+
- Personalize characters, setting, and vocabulary.
|
190 |
+
- Make the story both educational and entertaining.
|
191 |
+
- Ensure the language reflects real-world use in that context.
|
192 |
+
|
193 |
+
### Story Generation Task
|
194 |
+
1. **Use the provided metadata**:
|
195 |
+
- **Native language**: Present explanations, setup, and translations in {native_language}.
|
196 |
+
- **Target language**: Write dialogue and narration in {target_language}.
|
197 |
+
- **Proficiency level**: Match language complexity to {proficiency}:
|
198 |
+
- *Beginner*: Simple grammar, short sentences, high-frequency vocabulary.
|
199 |
+
- *Intermediate*: Natural sentence flow, basic narrative devices, slightly challenging vocabulary.
|
200 |
+
- *Advanced*: Complex structures, idiomatic expressions, domain-specific language.
|
201 |
+
|
202 |
+
2. **Domain relevance**:
|
203 |
+
- Base the story or dialogue on the user’s interests or specified topic.
|
204 |
+
- Integrate relevant vocabulary and situations (e.g., a chef character using cooking terms, or a pilot discussing navigation).
|
205 |
+
|
206 |
+
3. **Engagement and originality**:
|
207 |
+
- Make the story fun, dramatic, or surprising to increase engagement.
|
208 |
+
- Avoid clichés and repetition—each story should be fresh and imaginative.
|
209 |
+
- Vary tone and structure depending on the theme (e.g., suspenseful for a mystery, humorous for a slice-of-life scene).
|
210 |
+
|
211 |
+
4. **Educational value**:
|
212 |
+
- Use natural-sounding language learners would benefit from hearing or using.
|
213 |
+
- Provide translations and (where helpful) phonetic transcription to support pronunciation and comprehension.
|
214 |
+
|
215 |
+
### Output Format
|
216 |
+
Return a valid **JSON object** with the following structure:
|
217 |
+
- `"title"`: An engaging title in {native_language}.
|
218 |
+
- `"setting"`: A brief setup paragraph in {native_language} explaining the story’s background and relevance to the user’s interest.
|
219 |
+
- `"content"`: A list of **10 segments**, each structured as:
|
220 |
+
- `"speaker"`: A named or role-based character label in {native_language} (e.g., "Narrator", "Captain Li", "The Botanist").
|
221 |
+
- `"target_language_text"`: The sentence or dialogue line in {target_language}.
|
222 |
+
- `"phonetics"`: A phonetic transcription (IPA, Pinyin, etc.), only if helpful or relevant for the target language.
|
223 |
+
- `"base_language_translation"`: A simple, clear translation in {native_language}.
|
224 |
+
|
225 |
+
Ensure that all entries are structured cleanly and consistently. Do not wrap the result in additional containers or metadata.
|
226 |
+
"""
|
prev_backend_v2/backend/database.py
ADDED
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import psycopg2
|
2 |
+
import os
|
3 |
+
from psycopg2 import sql
|
4 |
+
from dotenv import load_dotenv
|
5 |
+
|
6 |
+
load_dotenv()
|
7 |
+
|
8 |
+
# Database Configuration from environment variables
|
9 |
+
DB_NAME = os.getenv("POSTGRES_DB", "linguaai")
|
10 |
+
DB_USER = os.getenv("POSTGRES_USER", "linguaai_user")
|
11 |
+
DB_PASSWORD = os.getenv("POSTGRES_PASSWORD", "LinguaAI1008")
|
12 |
+
DB_HOST = os.getenv("DB_HOST", "localhost")
|
13 |
+
DB_PORT = os.getenv("DB_PORT", "5432")
|
14 |
+
|
15 |
+
# SQL Schema Definition
|
16 |
+
SCHEMA_SQL = """
|
17 |
+
-- Drop existing objects if they exist
|
18 |
+
-- Note: Some drops below might be for tables not defined in this specific script.
|
19 |
+
DROP TABLE IF EXISTS user_activity_progress CASCADE;
|
20 |
+
DROP TABLE IF EXISTS activities CASCADE;
|
21 |
+
DROP TABLE IF EXISTS weekly_modules CASCADE;
|
22 |
+
DROP TABLE IF EXISTS curriculums CASCADE;
|
23 |
+
DROP TABLE IF EXISTS generated_flashcards CASCADE;
|
24 |
+
DROP TABLE IF EXISTS flashcard_sets CASCADE; -- Corrected name
|
25 |
+
DROP TABLE IF EXISTS generated_exercises CASCADE;
|
26 |
+
DROP TABLE IF EXISTS exercise_sets CASCADE; -- Corrected name
|
27 |
+
DROP TABLE IF EXISTS simulations CASCADE; -- Corrected name
|
28 |
+
DROP TABLE IF EXISTS users CASCADE;
|
29 |
+
DROP TYPE IF EXISTS activity_status CASCADE;
|
30 |
+
|
31 |
+
-- Table `users`
|
32 |
+
CREATE TABLE users (
|
33 |
+
user_id SERIAL PRIMARY KEY,
|
34 |
+
username VARCHAR(50) UNIQUE NOT NULL,
|
35 |
+
email VARCHAR(100) UNIQUE NOT NULL,
|
36 |
+
password_hash VARCHAR(255) NOT NULL,
|
37 |
+
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
38 |
+
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
|
39 |
+
);
|
40 |
+
|
41 |
+
-- Trigger function (remains the same)
|
42 |
+
CREATE OR REPLACE FUNCTION update_updated_at_column()
|
43 |
+
RETURNS TRIGGER AS $$
|
44 |
+
BEGIN
|
45 |
+
NEW.updated_at = now();
|
46 |
+
RETURN NEW;
|
47 |
+
END;
|
48 |
+
$$ language 'plpgsql';
|
49 |
+
|
50 |
+
-- Trigger for users (remains the same)
|
51 |
+
CREATE TRIGGER users_update_updated_at
|
52 |
+
BEFORE UPDATE ON users
|
53 |
+
FOR EACH ROW
|
54 |
+
EXECUTE FUNCTION update_updated_at_column();
|
55 |
+
|
56 |
+
|
57 |
+
-- ============================================
|
58 |
+
-- Tables for Generated Content (Flashcards)
|
59 |
+
-- ============================================
|
60 |
+
|
61 |
+
-- Table `flashcard_sets` (Represents one request/query)
|
62 |
+
CREATE TABLE flashcard_sets (
|
63 |
+
id SERIAL PRIMARY KEY,
|
64 |
+
user_id INTEGER NOT NULL REFERENCES users(user_id), -- Added FK reference for completeness
|
65 |
+
query TEXT NOT NULL,
|
66 |
+
flashcards JSONB NOT NULL, -- Stores an array of 5 flashcards
|
67 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
68 |
+
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -- Added updated_at for consistency
|
69 |
+
);
|
70 |
+
|
71 |
+
CREATE INDEX idx_flashcard_set_user ON flashcard_sets(user_id);
|
72 |
+
|
73 |
+
-- Corrected Trigger definition for flashcard_sets
|
74 |
+
CREATE TRIGGER flashcard_sets_update_updated_at -- Renamed trigger
|
75 |
+
BEFORE UPDATE ON flashcard_sets -- Corrected table name
|
76 |
+
FOR EACH ROW
|
77 |
+
EXECUTE FUNCTION update_updated_at_column(); -- Assumes you want updated_at here too
|
78 |
+
|
79 |
+
-- Table `generated_flashcards` (Individual flashcards within a set)
|
80 |
+
CREATE TABLE generated_flashcards (
|
81 |
+
flashcard_id SERIAL PRIMARY KEY,
|
82 |
+
set_id INT NOT NULL REFERENCES flashcard_sets(id) ON DELETE CASCADE, -- Corrected FK reference (table and column)
|
83 |
+
word TEXT NOT NULL,
|
84 |
+
definition TEXT NOT NULL,
|
85 |
+
example TEXT, -- Example might be optional
|
86 |
+
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
87 |
+
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
|
88 |
+
);
|
89 |
+
|
90 |
+
CREATE INDEX idx_flashcard_set ON generated_flashcards(set_id);
|
91 |
+
|
92 |
+
-- Trigger for generated_flashcards (remains the same)
|
93 |
+
CREATE TRIGGER generated_flashcards_update_updated_at
|
94 |
+
BEFORE UPDATE ON generated_flashcards
|
95 |
+
FOR EACH ROW
|
96 |
+
EXECUTE FUNCTION update_updated_at_column();
|
97 |
+
|
98 |
+
|
99 |
+
-- ============================================
|
100 |
+
-- Tables for Generated Content (Exercises)
|
101 |
+
-- ============================================
|
102 |
+
|
103 |
+
-- Table `exercise_sets` (Represents one request/query) -- Corrected comment
|
104 |
+
CREATE TABLE exercise_sets (
|
105 |
+
id SERIAL PRIMARY KEY,
|
106 |
+
user_id INTEGER NOT NULL REFERENCES users(user_id), -- Added FK reference for completeness
|
107 |
+
query TEXT NOT NULL,
|
108 |
+
exercises JSONB NOT NULL, -- Array of 5 exercises
|
109 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
110 |
+
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -- Added updated_at for consistency
|
111 |
+
);
|
112 |
+
|
113 |
+
CREATE INDEX idx_exercise_set_user ON exercise_sets(user_id); -- Corrected table name (was already correct but double-checked)
|
114 |
+
|
115 |
+
-- Corrected Trigger definition for exercise_sets
|
116 |
+
CREATE TRIGGER exercise_sets_update_updated_at -- Renamed trigger
|
117 |
+
BEFORE UPDATE ON exercise_sets -- Corrected table name
|
118 |
+
FOR EACH ROW
|
119 |
+
EXECUTE FUNCTION update_updated_at_column(); -- Assumes you want updated_at here too
|
120 |
+
|
121 |
+
-- Table `generated_exercises` (Individual exercises within a set)
|
122 |
+
CREATE TABLE generated_exercises (
|
123 |
+
exercise_id SERIAL PRIMARY KEY,
|
124 |
+
set_id INT NOT NULL REFERENCES exercise_sets(id) ON DELETE CASCADE, -- Corrected FK reference (table and column)
|
125 |
+
sentence TEXT NOT NULL,
|
126 |
+
answer TEXT NOT NULL,
|
127 |
+
choices JSONB NOT NULL, -- Storing the array of choices
|
128 |
+
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
129 |
+
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
|
130 |
+
);
|
131 |
+
|
132 |
+
CREATE INDEX idx_exercise_set ON generated_exercises(set_id);
|
133 |
+
|
134 |
+
-- Trigger for generated_exercises (remains the same)
|
135 |
+
CREATE TRIGGER generated_exercises_update_updated_at
|
136 |
+
BEFORE UPDATE ON generated_exercises
|
137 |
+
FOR EACH ROW
|
138 |
+
EXECUTE FUNCTION update_updated_at_column();
|
139 |
+
|
140 |
+
|
141 |
+
-- ============================================
|
142 |
+
-- Table for Generated Content (Simulations)
|
143 |
+
-- ============================================
|
144 |
+
|
145 |
+
-- Table `simulations` (Represents one simulation request/result) -- Corrected comment
|
146 |
+
CREATE TABLE simulations (
|
147 |
+
id SERIAL PRIMARY KEY,
|
148 |
+
user_id INTEGER NOT NULL REFERENCES users(user_id), -- Added FK reference for completeness
|
149 |
+
query TEXT NOT NULL,
|
150 |
+
scenario TEXT NOT NULL,
|
151 |
+
dialog JSONB NOT NULL, -- Array of turns with 'role', 'chinese', 'pinyin', 'english'
|
152 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
153 |
+
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -- Added updated_at for consistency
|
154 |
+
);
|
155 |
+
|
156 |
+
CREATE INDEX idx_simulation_user ON simulations(user_id); -- Corrected table name
|
157 |
+
|
158 |
+
-- Corrected Trigger definition for simulations
|
159 |
+
CREATE TRIGGER simulations_update_updated_at -- Renamed trigger
|
160 |
+
BEFORE UPDATE ON simulations -- Corrected table name
|
161 |
+
FOR EACH ROW
|
162 |
+
EXECUTE FUNCTION update_updated_at_column(); -- Assumes you want updated_at here too
|
163 |
+
"""
|
164 |
+
|
165 |
+
def get_db_connection():
|
166 |
+
"""Get a synchronous database connection."""
|
167 |
+
try:
|
168 |
+
conn = psycopg2.connect(
|
169 |
+
dbname=DB_NAME,
|
170 |
+
user=DB_USER,
|
171 |
+
password=DB_PASSWORD,
|
172 |
+
host=DB_HOST,
|
173 |
+
port=DB_PORT
|
174 |
+
)
|
175 |
+
return conn
|
176 |
+
except psycopg2.Error as e:
|
177 |
+
print(f"Database connection error: {e}")
|
178 |
+
raise
|
179 |
+
|
180 |
+
def reset_sequences():
|
181 |
+
"""Generate SQL to reset all sequences (auto-incrementing IDs) to 1."""
|
182 |
+
sequences_sql = """
|
183 |
+
SELECT 'ALTER SEQUENCE ' || sequence_name || ' RESTART WITH 1;'
|
184 |
+
FROM information_schema.sequences
|
185 |
+
WHERE sequence_schema = 'public';
|
186 |
+
"""
|
187 |
+
return sequences_sql
|
188 |
+
|
189 |
+
def reset_database(confirm=True):
|
190 |
+
"""Reset the database by dropping all tables and recreating them."""
|
191 |
+
if confirm:
|
192 |
+
user_confirm = input("WARNING: This will DELETE ALL DATA. Type 'yes' to proceed: ")
|
193 |
+
if user_confirm.lower() != 'yes':
|
194 |
+
print("Database reset cancelled.")
|
195 |
+
return
|
196 |
+
|
197 |
+
conn = None
|
198 |
+
try:
|
199 |
+
conn = get_db_connection()
|
200 |
+
conn.autocommit = False
|
201 |
+
print("Database connection established.")
|
202 |
+
|
203 |
+
with conn.cursor() as cur:
|
204 |
+
print("Dropping and recreating schema...")
|
205 |
+
# Execute the main schema SQL (includes drops)
|
206 |
+
cur.execute(SCHEMA_SQL)
|
207 |
+
print("Schema recreated successfully.")
|
208 |
+
|
209 |
+
# Generate and execute sequence reset SQL
|
210 |
+
print("Resetting sequences...")
|
211 |
+
reset_sql_query = reset_sequences()
|
212 |
+
cur.execute(reset_sql_query)
|
213 |
+
reset_commands = cur.fetchall()
|
214 |
+
for command in reset_commands:
|
215 |
+
cur.execute(command[0])
|
216 |
+
print("Sequences reset successfully.")
|
217 |
+
|
218 |
+
conn.commit()
|
219 |
+
print("Database reset complete.")
|
220 |
+
|
221 |
+
except psycopg2.Error as e:
|
222 |
+
print(f"Database error during reset: {e}")
|
223 |
+
if conn:
|
224 |
+
conn.rollback()
|
225 |
+
print("Transaction rolled back.")
|
226 |
+
except Exception as e:
|
227 |
+
print(f"An unexpected error occurred during reset: {e}")
|
228 |
+
if conn:
|
229 |
+
conn.rollback()
|
230 |
+
finally:
|
231 |
+
if conn:
|
232 |
+
conn.close()
|
233 |
+
print("Database connection closed.")
|
234 |
+
|
235 |
+
def setup_database(confirm=True):
|
236 |
+
"""Set up the database schema if tables do not exist."""
|
237 |
+
if confirm:
|
238 |
+
user_confirm = input("Do you want to set up the database? Type 'yes' to proceed: ")
|
239 |
+
if user_confirm.lower() != 'yes':
|
240 |
+
print("Database setup cancelled.")
|
241 |
+
return
|
242 |
+
|
243 |
+
conn = None
|
244 |
+
try:
|
245 |
+
conn = get_db_connection()
|
246 |
+
conn.autocommit = False
|
247 |
+
print("Database connection established.")
|
248 |
+
|
249 |
+
with conn.cursor() as cur:
|
250 |
+
print("Checking if tables exist...")
|
251 |
+
cur.execute("""
|
252 |
+
SELECT EXISTS (
|
253 |
+
SELECT FROM information_schema.tables
|
254 |
+
WHERE table_schema = 'public'
|
255 |
+
AND table_name = 'users'
|
256 |
+
);
|
257 |
+
""")
|
258 |
+
tables_exist = cur.fetchone()[0]
|
259 |
+
|
260 |
+
if tables_exist:
|
261 |
+
print("Tables already exist. Use reset_database() to reset the database or run setup with confirm=False.")
|
262 |
+
conn.rollback() # Rollback as no changes should be made
|
263 |
+
return
|
264 |
+
|
265 |
+
print("Creating schema...")
|
266 |
+
cur.execute(SCHEMA_SQL)
|
267 |
+
print("Schema created successfully.")
|
268 |
+
|
269 |
+
conn.commit()
|
270 |
+
print("Database setup complete.")
|
271 |
+
|
272 |
+
except psycopg2.Error as e:
|
273 |
+
print(f"Database error during setup: {e}")
|
274 |
+
if conn:
|
275 |
+
conn.rollback()
|
276 |
+
print("Transaction rolled back.")
|
277 |
+
except Exception as e:
|
278 |
+
print(f"An unexpected error occurred during setup: {e}")
|
279 |
+
if conn:
|
280 |
+
conn.rollback()
|
281 |
+
finally:
|
282 |
+
if conn:
|
283 |
+
conn.close()
|
284 |
+
print("Database connection closed.")
|
285 |
+
|
286 |
+
if __name__ == "__main__":
|
287 |
+
action = input("Enter 'setup' to setup database or 'reset' to reset database: ").lower()
|
288 |
+
if action == 'reset':
|
289 |
+
reset_database()
|
290 |
+
elif action == 'setup':
|
291 |
+
setup_database()
|
292 |
+
else:
|
293 |
+
print("Invalid action. Use 'setup' or 'reset'.")
|
prev_backend_v2/backend/main.py
ADDED
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from fastapi.responses import JSONResponse
|
3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
4 |
+
from pydantic import BaseModel
|
5 |
+
from backend.utils import generate_completions
|
6 |
+
from backend import config
|
7 |
+
from backend.database import get_db_connection
|
8 |
+
import psycopg2
|
9 |
+
from psycopg2.extras import RealDictCursor
|
10 |
+
from typing import Union, List, Literal, Optional
|
11 |
+
import logging
|
12 |
+
import json
|
13 |
+
|
14 |
+
logging.basicConfig(level=logging.INFO)
|
15 |
+
|
16 |
+
app = FastAPI()
|
17 |
+
|
18 |
+
# Add CORS middleware
|
19 |
+
app.add_middleware(
|
20 |
+
CORSMiddleware,
|
21 |
+
allow_origins=["*"], # Allows all origins
|
22 |
+
allow_credentials=True,
|
23 |
+
allow_methods=["*"], # Allows all methods
|
24 |
+
allow_headers=["*"], # Allows all headers
|
25 |
+
)
|
26 |
+
|
27 |
+
# Dependency to get database connection
|
28 |
+
async def get_db():
|
29 |
+
conn = await get_db_connection()
|
30 |
+
try:
|
31 |
+
yield conn
|
32 |
+
finally:
|
33 |
+
conn.close()
|
34 |
+
|
35 |
+
class Message(BaseModel):
|
36 |
+
role: Literal["user", "assistant"]
|
37 |
+
content: str
|
38 |
+
|
39 |
+
class GenerationRequest(BaseModel):
|
40 |
+
user_id: int
|
41 |
+
query: Union[str, List[Message]]
|
42 |
+
native_language: Optional[str] = None
|
43 |
+
target_language: Optional[str] = None
|
44 |
+
proficiency: Optional[str] = None
|
45 |
+
|
46 |
+
class MetadataRequest(BaseModel):
|
47 |
+
query: str
|
48 |
+
|
49 |
+
# Global metadata variables
|
50 |
+
native_language: Optional[str] = None
|
51 |
+
target_language: Optional[str] = None
|
52 |
+
proficiency: Optional[str] = None
|
53 |
+
|
54 |
+
@app.get("/")
|
55 |
+
async def root():
|
56 |
+
return {"message": "Welcome to the AI Learning Assistant API!"}
|
57 |
+
|
58 |
+
@app.post("/extract/metadata")
|
59 |
+
async def extract_metadata(data: MetadataRequest):
|
60 |
+
logging.info(f"Query: {data.query}")
|
61 |
+
try:
|
62 |
+
response_str = await generate_completions.get_completions(
|
63 |
+
data.query,
|
64 |
+
config.language_metadata_extraction_prompt
|
65 |
+
)
|
66 |
+
metadata_dict = json.loads(response_str)
|
67 |
+
# Update globals for other endpoints
|
68 |
+
globals()['native_language'] = metadata_dict.get('native_language', 'unknown')
|
69 |
+
globals()['target_language'] = metadata_dict.get('target_language', 'unknown')
|
70 |
+
globals()['proficiency'] = metadata_dict.get('proficiency', 'unknown')
|
71 |
+
return JSONResponse(
|
72 |
+
content={
|
73 |
+
"data": metadata_dict,
|
74 |
+
"type": "language_metadata",
|
75 |
+
"status": "success"
|
76 |
+
},
|
77 |
+
status_code=200
|
78 |
+
)
|
79 |
+
except Exception as e:
|
80 |
+
raise HTTPException(status_code=500, detail=str(e))
|
81 |
+
|
82 |
+
@app.post("/generate/curriculum")
|
83 |
+
async def generate_curriculum(data: GenerationRequest):
|
84 |
+
try:
|
85 |
+
# Use metadata from request or fallback to globals
|
86 |
+
nl = data.native_language or native_language or "unknown"
|
87 |
+
tl = data.target_language or target_language or "unknown"
|
88 |
+
prof = data.proficiency or proficiency or "unknown"
|
89 |
+
instructions = (
|
90 |
+
config.curriculum_instructions
|
91 |
+
.replace("{native_language}", nl)
|
92 |
+
.replace("{target_language}", tl)
|
93 |
+
.replace("{proficiency}", prof)
|
94 |
+
)
|
95 |
+
response = await generate_completions.get_completions(
|
96 |
+
data.query,
|
97 |
+
instructions
|
98 |
+
)
|
99 |
+
return JSONResponse(
|
100 |
+
content={
|
101 |
+
"data": response,
|
102 |
+
"type": "curriculum",
|
103 |
+
"status": "success"
|
104 |
+
},
|
105 |
+
status_code=200
|
106 |
+
)
|
107 |
+
except Exception as e:
|
108 |
+
raise HTTPException(status_code=500, detail=str(e))
|
109 |
+
|
110 |
+
@app.post("/generate/flashcards")
|
111 |
+
async def generate_flashcards(data: GenerationRequest):
|
112 |
+
try:
|
113 |
+
nl = data.native_language or native_language or "unknown"
|
114 |
+
tl = data.target_language or target_language or "unknown"
|
115 |
+
prof = data.proficiency or proficiency or "unknown"
|
116 |
+
instructions = (
|
117 |
+
config.flashcard_mode_instructions
|
118 |
+
.replace("{native_language}", nl)
|
119 |
+
.replace("{target_language}", tl)
|
120 |
+
.replace("{proficiency}", prof)
|
121 |
+
)
|
122 |
+
response = await generate_completions.get_completions(
|
123 |
+
data.query,
|
124 |
+
instructions
|
125 |
+
)
|
126 |
+
return JSONResponse(
|
127 |
+
content={
|
128 |
+
"data": response,
|
129 |
+
"type": "flashcards",
|
130 |
+
"status": "success"
|
131 |
+
},
|
132 |
+
status_code=200
|
133 |
+
)
|
134 |
+
except Exception as e:
|
135 |
+
raise HTTPException(status_code=500, detail=str(e))
|
136 |
+
|
137 |
+
@app.post("/generate/exercises")
|
138 |
+
async def generate_exercises(data: GenerationRequest):
|
139 |
+
try:
|
140 |
+
nl = data.native_language or native_language or "unknown"
|
141 |
+
tl = data.target_language or target_language or "unknown"
|
142 |
+
prof = data.proficiency or proficiency or "unknown"
|
143 |
+
instructions = (
|
144 |
+
config.exercise_mode_instructions
|
145 |
+
.replace("{native_language}", nl)
|
146 |
+
.replace("{target_language}", tl)
|
147 |
+
.replace("{proficiency}", prof)
|
148 |
+
)
|
149 |
+
response = await generate_completions.get_completions(
|
150 |
+
data.query,
|
151 |
+
instructions
|
152 |
+
)
|
153 |
+
return JSONResponse(
|
154 |
+
content={
|
155 |
+
"data": response,
|
156 |
+
"type": "exercises",
|
157 |
+
"status": "success"
|
158 |
+
},
|
159 |
+
status_code=200
|
160 |
+
)
|
161 |
+
except Exception as e:
|
162 |
+
raise HTTPException(status_code=500, detail=str(e))
|
163 |
+
|
164 |
+
@app.post("/generate/simulation")
|
165 |
+
async def generate_simulation(data: GenerationRequest):
|
166 |
+
try:
|
167 |
+
nl = data.native_language or native_language or "unknown"
|
168 |
+
tl = data.target_language or target_language or "unknown"
|
169 |
+
prof = data.proficiency or proficiency or "unknown"
|
170 |
+
instructions = (
|
171 |
+
config.simulation_mode_instructions
|
172 |
+
.replace("{native_language}", nl)
|
173 |
+
.replace("{target_language}", tl)
|
174 |
+
.replace("{proficiency}", prof)
|
175 |
+
)
|
176 |
+
response = await generate_completions.get_completions(
|
177 |
+
data.query,
|
178 |
+
instructions
|
179 |
+
)
|
180 |
+
return JSONResponse(
|
181 |
+
content={
|
182 |
+
"data": response,
|
183 |
+
"type": "simulation",
|
184 |
+
"status": "success"
|
185 |
+
},
|
186 |
+
status_code=200
|
187 |
+
)
|
188 |
+
except Exception as e:
|
189 |
+
raise HTTPException(status_code=500, detail=str(e))
|
prev_backend_v2/backend/utils/__pycache__/generate_completions.cpython-310.pyc
ADDED
Binary file (2.55 kB). View file
|
|
prev_backend_v2/backend/utils/__pycache__/generate_completions.cpython-312.pyc
ADDED
Binary file (3.73 kB). View file
|
|
prev_backend_v2/backend/utils/generate_completions.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from openai import AsyncOpenAI, OpenAI
|
2 |
+
import asyncio
|
3 |
+
import json
|
4 |
+
from typing import AsyncIterator
|
5 |
+
from typing import Union, List, Dict, Literal
|
6 |
+
from dotenv import load_dotenv
|
7 |
+
import os
|
8 |
+
from pydantic import BaseModel
|
9 |
+
load_dotenv()
|
10 |
+
|
11 |
+
# Initialize the async client
|
12 |
+
client = AsyncOpenAI(
|
13 |
+
base_url=os.getenv("BASE_URL"),
|
14 |
+
api_key=os.getenv("API_KEY"),
|
15 |
+
)
|
16 |
+
|
17 |
+
class Message(BaseModel):
|
18 |
+
role: Literal["user", "assistant"]
|
19 |
+
content: str
|
20 |
+
|
21 |
+
# Helper function to flatten chat messages into a single string prompt
|
22 |
+
def flatten_messages(messages: List[Message]) -> str:
|
23 |
+
return "\n".join([f"{m.role}: {m.content}" for m in messages])
|
24 |
+
|
25 |
+
def process_input(data: Union[str, List[Dict[str, str]]]) -> Union[str, List[Dict[str, str]]]:
|
26 |
+
"""
|
27 |
+
Processes input to either uppercase a string or modify the 'content' field
|
28 |
+
of a list of dictionaries.
|
29 |
+
"""
|
30 |
+
if isinstance(data, str):
|
31 |
+
return data.strip() # Ensures prompt is cleaned up (optional)
|
32 |
+
|
33 |
+
elif isinstance(data, list):
|
34 |
+
# Ensure each item in the list is a dictionary with a 'content' key
|
35 |
+
return [
|
36 |
+
{**item, "content": item["content"].strip()} # Trims whitespace in 'content'
|
37 |
+
for item in data if isinstance(item, dict) and "content" in item
|
38 |
+
]
|
39 |
+
|
40 |
+
else:
|
41 |
+
raise TypeError("Input must be a string or a list of dictionaries with a 'content' field")
|
42 |
+
|
43 |
+
|
44 |
+
# async def get_completions(
|
45 |
+
# prompt: Union[str, List[Dict[str, str]]],
|
46 |
+
# instructions: str
|
47 |
+
# ) -> str:
|
48 |
+
# processed_prompt = process_input(prompt) # Ensures the input format is correct
|
49 |
+
|
50 |
+
# if isinstance(processed_prompt, str):
|
51 |
+
# messages = [
|
52 |
+
# {"role": "system", "content": instructions},
|
53 |
+
# {"role": "user", "content": processed_prompt}
|
54 |
+
# ]
|
55 |
+
# elif isinstance(processed_prompt, list):
|
56 |
+
# messages = [{"role": "system", "content": instructions}] + processed_prompt
|
57 |
+
# else:
|
58 |
+
# raise TypeError("Unexpected processed input type.")
|
59 |
+
|
60 |
+
# response = await client.chat.completions.create(
|
61 |
+
# model=os.getenv("MODEL"),
|
62 |
+
# messages=messages,
|
63 |
+
# response_format={"type": "json_object"}
|
64 |
+
# )
|
65 |
+
|
66 |
+
# output: str = response.choices[0].message.content
|
67 |
+
# return output
|
68 |
+
|
69 |
+
async def get_completions(
|
70 |
+
prompt: Union[str, List[Dict[str, str]]],
|
71 |
+
instructions: str
|
72 |
+
) -> str:
|
73 |
+
if isinstance(prompt, list):
|
74 |
+
formatted_query = flatten_messages(prompt)
|
75 |
+
else:
|
76 |
+
formatted_query = prompt
|
77 |
+
|
78 |
+
processed_prompt = process_input(formatted_query)
|
79 |
+
|
80 |
+
messages = [{"role": "system", "content": instructions}]
|
81 |
+
|
82 |
+
if isinstance(processed_prompt, str):
|
83 |
+
messages.append({"role": "user", "content": processed_prompt})
|
84 |
+
|
85 |
+
elif isinstance(processed_prompt, list):
|
86 |
+
# Only keep the history for context and append the latest user query at the end
|
87 |
+
history = processed_prompt[:-1]
|
88 |
+
last_user_msg = processed_prompt[-1]
|
89 |
+
|
90 |
+
# Optional: Validate that the last message is from the user
|
91 |
+
if last_user_msg.get("role") != "user":
|
92 |
+
raise ValueError("Last message must be from the user.")
|
93 |
+
|
94 |
+
messages += history
|
95 |
+
messages.append(last_user_msg)
|
96 |
+
|
97 |
+
else:
|
98 |
+
raise TypeError("Unexpected processed input type.")
|
99 |
+
|
100 |
+
# print(os.getenv("MODEL"))
|
101 |
+
response = await client.chat.completions.create(
|
102 |
+
model=os.getenv("MODEL"),
|
103 |
+
messages=messages,
|
104 |
+
response_format={"type": "json_object"}
|
105 |
+
)
|
106 |
+
|
107 |
+
return response.choices[0].message.content # adjust based on your client
|