Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesFiles changed (6)
- .DS_Store
- .gitignore+1
- gradio_app.py+303-36
- prompts.py+20-12
- translation.pyAdded+592
- utils.pyAdded+84
3 unmodified lines4563 unmodified linestest.md__pycache__/.env3 unmodified lines45673 unmodified linestest.md__pycache__/.envgoogle.json
12345678910111213141516171819202124 unmodified lines46474849505152535455565758596061624 unmodified lines67686970717228 unmodified lines10110210310410510610710810911011111211315 unmodified lines129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189import gradio as grfrom app import question_graph, MemorySaverimport uuidimport os# -----------------------------# In-Memory Storage for Feedback Flow# -----------------------------session_data = {}# -----------------------------# Graph Invocation Function# -----------------------------def run_graph(topic, subtopic, difficulty):session_id = str(uuid.uuid4()) # Unique session per questionmemory = MemorySaver()inputs = {"topic": topic,"subtopic": subtopic,24 unmodified lines}generated_question = partial_result.get("question", "No question generated.")return (session_id,generated_question,"Enter feedback if needed, or click 'Solve Question'.",)# -----------------------------# Handle Feedback and Rerun Graph# -----------------------------def handle_feedback(session_id, feedback_text):data = session_data.get(session_id)if not data:return session_id, "Session expired or invalid.", ""4 unmodified linesif feedback_text:# Update state with feedback at node 'feedback'question_graph.update_state(thread, {"human_feedback": feedback_text}, as_node="feedback")28 unmodified linessolution_md = final_result.get("solution", "No solution generated.")answer = final_result.get("answer", "No answer.")return session_id, solution_md, answer# -----------------------------# Solve Question – Full Graph Run# -----------------------------def solve_question(session_id):data = session_data.get(session_id)thread = {"configurable": {"thread_id": session_id}}if not data:15 unmodified linesprint("Final Result", final_result)solution_md = final_result.get("solution", "No solution generated.")answer = final_result.get("answer", "No answer.")return solution_md, answer# -----------------------------# Gradio UI Layout# -----------------------------with gr.Blocks(title="LangGraph Math Solver") as demo:gr.Markdown("## 🧠 Dahee AI\nInput your topic and generate math questions, provide feedback, and get step-by-step solutions.")with gr.Row():topic_input = gr.Textbox(label="Topic", placeholder="e.g., Combinatorics")subtopic_input = gr.Textbox(label="Subtopic", placeholder="e.g., Enumerative combinatorics")difficulty_input = gr.Dropdown(label="Difficulty", choices=["easy", "medium", "hard"], value="medium")generate_btn = gr.Button("Generate Question")question_output = gr.Markdown(label="Generated Question", render=True)feedback_note = gr.Textbox(label="Feedback (Optional)", placeholder="Enter feedback to refine question...")with gr.Row():feedback_btn = gr.Button("Submit Feedback")solve_btn = gr.Button("Solve Question")solution_output = gr.Markdown(label="Solution (Markdown)", render=True)final_answer = gr.Markdown(label="Final Answer", render=True)# Hidden session IDsession_state = gr.State()# Eventsgenerate_btn.click(run_graph,inputs=[topic_input, subtopic_input, difficulty_input],outputs=[session_state, question_output, feedback_note],)feedback_btn.click(handle_feedback,inputs=[session_state, feedback_note],outputs=[session_state, question_output, feedback_note],)solve_btn.click(solve_question, inputs=[session_state], outputs=[solution_output, final_answer])# -----------------------------# Launch App# -----------------------------if __name__ == "__main__":demo.launch(share=True)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474824 unmodified lines73747576777879808182838485868788899091924 unmodified lines97989910010110210310410510628 unmodified lines13513613713813914014114214314414514614714814915015115215315415515615715 unmodified lines173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456import gradio as grimport utilsfrom app import question_graph, MemorySaverfrom translation import LANGUAGESimport uuidimport osfrom dotenv import load_dotenvimport tempfileload_dotenv()service_account_json = os.environ.get("GOOGLE_SERVICE_ACCOUNT_JSON")PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT")if service_account_json:# Write the JSON content to a temporary filetemp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".json")temp_file.write(service_account_json.encode("utf-8"))temp_file.close()# Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the temp file pathos.environ["GOOGLE_APPLICATION_CREDENTIALS"] = temp_file.name# -----------------------------# In-Memory Storage for Feedback Flow# -----------------------------session_data = {}session_data["en_topics"] = utils.get_topic_names("en")session_data["az_topics"] = utils.get_topic_names("az")session_data["ru_topics"] = utils.get_topic_names("ru")# -----------------------------# Graph Invocation Function# -----------------------------def run_graph(topic, subtopic, difficulty, lang):session_id = str(uuid.uuid4()) # Unique session per questionmemory = MemorySaver()if lang == "az" or lang == "ru":topic, subtopic, difficulty = utils.get_eng_names(topic, subtopic, difficulty, lang)print("Topic:", topic, "Subtopic:", subtopic, "Difficulty:", difficulty)inputs = {"topic": topic,"subtopic": subtopic,24 unmodified lines}generated_question = partial_result.get("question", "No question generated.")# Translate Question if English is not selectedif lang != "en":generated_question = utils.translate_text(generated_question, PROJECT_ID, target_lang=lang, source_lang="en")return session_id, generated_question, LANGUAGES[lang]["feedback_placeholder"]# -----------------------------# Handle Feedback and Rerun Graph# -----------------------------def handle_feedback(session_id, feedback_text, lang):data = session_data.get(session_id)if not data:return session_id, "Session expired or invalid.", ""4 unmodified linesif feedback_text:# Update state with feedback at node 'feedback'feedback_text = utils.translate_text(feedback_text, PROJECT_ID, target_lang="en")question_graph.update_state(thread, {"human_feedback": feedback_text}, as_node="feedback")28 unmodified linessolution_md = final_result.get("solution", "No solution generated.")answer = final_result.get("answer", "No answer.")# Translate solution and answer if lang is not Englishif lang != "en":solution_md = utils.translate_text(solution_md, PROJECT_ID, target_lang=lang, source_lang="en")answer = utils.translate_text(answer, PROJECT_ID, target_lang=lang, source_lang="en")return session_id, solution_md, answer# -----------------------------# Solve Question – Full Graph Run# -----------------------------def solve_question(session_id, lang):data = session_data.get(session_id)thread = {"configurable": {"thread_id": session_id}}if not data:15 unmodified linesprint("Final Result", final_result)solution_md = final_result.get("solution", "No solution generated.")answer = final_result.get("answer", "No answer.")# Translate solution and answer if lang is not Englishif lang != "en":solution_md = utils.translate_text(solution_md, PROJECT_ID, target_lang=lang, source_lang="en")answer = utils.translate_text(answer, PROJECT_ID, target_lang=lang, source_lang="en")return solution_md# Language toggle updates UIdef update_ui(lang):return (LANGUAGES[lang]["title"], # Markdown titlegr.update(visible=(lang == "az")), # Show Azerbaijani UIgr.update(visible=(lang == "en")), # Show English UIgr.update(visible=(lang == "ru")), # Show Russian UI)def update_subtopics(selected_topic, lang):subtopics_list = utils.get_subtopics(selected_topic, lang)return gr.update(choices=subtopics_list, value=subtopics_list[0] if subtopics_list else "")# -----------------------------# Gradio UI Layout# -----------------------------with gr.Blocks(title="LangGraph Math Solver") as demo:lang_toggle = gr.Dropdown(label="🌍 Select Language", choices=["en", "az", "ru"], value="en")title = gr.Markdown(LANGUAGES["en"]["title"])# English UI Componentswith gr.Column(visible=True) as english_ui:with gr.Row():topic_input_en = gr.Dropdown(label=LANGUAGES["en"]["topic_label"],choices=session_data["en_topics"],value=None,)subtopic_input_en = gr.Dropdown(label=LANGUAGES["en"]["subtopic_label"], choices=[], value=None)difficulty_input_en = gr.Dropdown(label=LANGUAGES["en"]["difficulty_label"],choices=["easy", "medium", "hard"],value="medium",)generate_btn_en = gr.Button(LANGUAGES["en"]["generate_btn"])question_output_en = gr.Markdown(label=LANGUAGES["en"]["question_output"],render=True,latex_delimiters=[{"left": "$$", "right": "$$", "display": True},{"left": "$", "right": "$", "display": False},],)feedback_note_en = gr.Textbox(label=LANGUAGES["en"]["feedback_label"],placeholder=LANGUAGES["en"]["feedback_placeholder"],)with gr.Row():feedback_btn_en = gr.Button(LANGUAGES["en"]["feedback_btn"])solve_btn_en = gr.Button(LANGUAGES["en"]["solve_btn"])solution_output_en = gr.Markdown(label=LANGUAGES["en"]["solution_output"],render=True,latex_delimiters=[{"left": "$$", "right": "$$", "display": True},{"left": "$", "right": "$", "display": False},{"left": "[", "right": "]", "display": False},],)# final_answer_en = gr.Markdown(# label=LANGUAGES["en"]["final_answer"], render=True# )# Azerbaijani UI Components (Initially Hidden)with gr.Column(visible=False) as azeri_ui:with gr.Row():topic_input_az = gr.Dropdown(label=LANGUAGES["az"]["topic_label"],choices=session_data["az_topics"],value=None,)subtopic_input_az = gr.Dropdown(label=LANGUAGES["az"]["subtopic_label"], choices=[], value=None)difficulty_input_az = gr.Dropdown(label=LANGUAGES["az"]["difficulty_label"],choices=["asan", "orta", "çətin"],value="orta",)generate_btn_az = gr.Button(LANGUAGES["az"]["generate_btn"])question_output_az = gr.Markdown(label=LANGUAGES["az"]["question_output"],render=True,latex_delimiters=[{"left": "$$", "right": "$$", "display": True},{"left": "$", "right": "$", "display": False},],)feedback_note_az = gr.Textbox(label=LANGUAGES["az"]["feedback_label"],placeholder=LANGUAGES["az"]["feedback_placeholder"],)with gr.Row():feedback_btn_az = gr.Button(LANGUAGES["az"]["feedback_btn"])solve_btn_az = gr.Button(LANGUAGES["az"]["solve_btn"])solution_output_az = gr.Markdown(label=LANGUAGES["az"]["solution_output"],render=True,latex_delimiters=[{"left": "$$", "right": "$$", "display": True},{"left": "$", "right": "$", "display": False},{"left": "[", "right": "]", "display": False},],)# final_answer_az = gr.Markdown(# label=LANGUAGES["az"]["final_answer"], render=True# )# Russian UI Components (Initially Hidden)with gr.Column(visible=False) as russian_ui:with gr.Row():topic_input_ru = gr.Dropdown(label=LANGUAGES["ru"]["topic_label"],choices=session_data["ru_topics"],value=None,)subtopic_input_ru = gr.Dropdown(label=LANGUAGES["ru"]["subtopic_label"], choices=[], value=None)difficulty_input_ru = gr.Dropdown(label=LANGUAGES["ru"]["difficulty_label"],choices=["легкий", "средний", "сложный"],value="средний",)generate_btn_ru = gr.Button(LANGUAGES["ru"]["generate_btn"])question_output_ru = gr.Markdown(label=LANGUAGES["ru"]["question_output"],render=True,latex_delimiters=[{"left": "$$", "right": "$$", "display": True},{"left": "$", "right": "$", "display": False},],)feedback_note_ru = gr.Textbox(label=LANGUAGES["ru"]["feedback_label"],placeholder=LANGUAGES["ru"]["feedback_placeholder"],)with gr.Row():feedback_btn_ru = gr.Button(LANGUAGES["ru"]["feedback_btn"])solve_btn_ru = gr.Button(LANGUAGES["ru"]["solve_btn"])solution_output_ru = gr.Markdown(label=LANGUAGES["ru"]["solution_output"],render=True,latex_delimiters=[{"left": "$$", "right": "$$", "display": True},{"left": "$", "right": "$", "display": False},{"left": "[", "right": "]", "display": False},],)# final_answer_ru = gr.Markdown(# label=LANGUAGES["ru"]["final_answer"], render=True# )# Language Togglelang_toggle.change(update_ui,inputs=[lang_toggle],outputs=[title,azeri_ui,english_ui,russian_ui,], # Using .update() to toggle visibility)# Topic Selection Eventstopic_input_en.change(update_subtopics,inputs=[topic_input_en, lang_toggle],outputs=[subtopic_input_en],)topic_input_az.change(update_subtopics,inputs=[topic_input_az, lang_toggle],outputs=[subtopic_input_az],)topic_input_ru.change(update_subtopics,inputs=[topic_input_ru, lang_toggle],outputs=[subtopic_input_ru],)# Hidden session IDsession_state = gr.State()# Events for English UIgenerate_btn_en.click(run_graph,inputs=[topic_input_en, subtopic_input_en, difficulty_input_en, lang_toggle],outputs=[session_state, question_output_en, feedback_note_en],)feedback_btn_en.click(handle_feedback,inputs=[session_state, feedback_note_en, lang_toggle],outputs=[session_state, question_output_en, feedback_note_en],)solve_btn_en.click(solve_question,inputs=[session_state, lang_toggle],outputs=[solution_output_en],)# Events for Azerbaijani UIgenerate_btn_az.click(run_graph,inputs=[topic_input_az, subtopic_input_az, difficulty_input_az, lang_toggle],outputs=[session_state, question_output_az, feedback_note_az],)feedback_btn_az.click(handle_feedback,inputs=[session_state, feedback_note_az, lang_toggle],outputs=[session_state, question_output_az, feedback_note_az],)solve_btn_az.click(solve_question,inputs=[session_state, lang_toggle],outputs=[solution_output_az],)# Events for Russian UIgenerate_btn_ru.click(run_graph,inputs=[topic_input_ru, subtopic_input_ru, difficulty_input_ru, lang_toggle],outputs=[session_state, question_output_ru, feedback_note_ru],)feedback_btn_ru.click(handle_feedback,inputs=[session_state, feedback_note_ru, lang_toggle],outputs=[session_state, question_output_ru, feedback_note_ru],)solve_btn_ru.click(solve_question,inputs=[session_state, lang_toggle],outputs=[solution_output_ru],)# -----------------------------# Launch App# -----------------------------if __name__ == "__main__":demo.launch()
92 unmodified lines9394959697989910010110210310410510610710892 unmodified linesFINALIZE_INSTRUCTION = """You are a math tutor. Given the problem, steps, and calculation results, write a clear and concise Markdown solution.Include:- Step-by-step solution- Final answer (boxed or highlighted)Question: {question}Steps: {steps}Tool Results: {tool_results}Verified: {verified}Respond in markdown format. ALWAYS write mathematical equations in between dollar signs (e.g., $x^2$)."""92 unmodified lines9394959697989910010110210310410510610710810911011111211311411511692 unmodified linesFINALIZE_INSTRUCTION = """You are a math tutor, and your task is to produce a clear and concise Markdown solution for math problems. Follow these instructions carefully:1. Provide a detailed, step-by-step solution.2. Present the final answer clearly, either boxed or highlighted.3. **All mathematical expressions MUST be enclosed in dollar signs only:**- For inline math, use a single pair of dollar signs (e.g., `$x^2$`).- For display math, use double dollar signs on their own lines (e.g.,```$$x^2$$```).- **Do NOT use any other LaTeX environments (e.g., do not use `\\(`, `\\[`, or similar).**4. Strictly follow these formatting rules for every mathematical expression.Use the following placeholders in your solution:- **Question:** {question}- **Steps:** {steps}- **Tool Results:** {tool_results}- **Verified:** {verified}Respond in Markdown format only."""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592LANGUAGES = { "en": { "title": "## 🧠 Dahee AI\nInput your topic and generate math questions, provide feedback, and get step-by-step solutions.", "topic_label": "Topic", "topic_placeholder": "e.g., Combinatorics", "subtopic_label": "Subtopic", "subtopic_placeholder": "e.g., Enumerative combinatorics", "difficulty_label": "Difficulty", "generate_btn": "Generate Question", "feedback_label": "Feedback (Optional)", "feedback_placeholder": "Enter feedback to refine question...", "feedback_btn": "Submit Feedback", "solve_btn": "Solve Question", "question_output": "Generated Question", "solution_output": "Solution (Markdown)", "final_answer": "Final Answer", }, "az": { "title": "## 🧠 Dahee AI\nMövzunu daxil edin və riyazi suallar yaradın, rəy bildirin və addım-addım həllər əldə edin.", "topic_label": "Mövzu", "topic_placeholder": "məs., Kombinatorika", "subtopic_label": "Alt mövzu", "subtopic_placeholder": "məs., Hesablama Kombinatorikası", "difficulty_label": "Çətinlik", "generate_btn": "Sual Yarat", "feedback_label": "Rəy (İstəyə bağlı)", "feedback_placeholder": "Sualı düzəltmək üçün rəy bildirin...", "feedback_btn": "Rəyi Göndər", "solve_btn": "Sualı Həll et", "question_output": "Yaradılan Sual", "solution_output": "Həll (Markdown)", "final_answer": "Son Cavab", }, "ru": { "title": "## 🧠 Dahee AI\nВведите свою тему и сгенерируйте математические вопросы, оставьте отзыв и получите пошаговые решения.", "topic_label": "Тема", "topic_placeholder": "например, Комбинаторика", "subtopic_label": "Подтема", "subtopic_placeholder": "например, Перечислительная комбинаторика", "difficulty_label": "Сложность", "generate_btn": "Создать вопрос", "feedback_label": "Отзыв (Необязательно)", "feedback_placeholder": "Введите отзыв для улучшения вопроса...", "feedback_btn": "Отправить отзыв", "solve_btn": "Решить вопрос", "question_output": "Сгенерированный вопрос", "solution_output": "Решение (Markdown)", "final_answer": "Финальный ответ", },}
DIFFICULTY = [ {"en": "Easy", "az": "Asan", "ru": "Легко"}, {"en": "Medium", "az": "Orta", "ru": "Средне"}, {"en": "Hard", "az": "Çətin", "ru": "Трудно"},]
TOPICS = [ { "en": "nth degree root", "az": "n-ci dərəcədən kök", "ru": "корень n-й степени", "subtopics": [ { "level": 9, "en": "Real numbers", "az": "Həqiqi ədədlər", "ru": "Действительные числа", }, { "level": 9, "en": "Absolute value of real number", "az": "Həqiqi ədədin mütləq qiymətı", "ru": "Абсолютная величина действительного числа", }, { "level": 9, "en": "Numerical sets", "az": "Ədədi çoxluqlar", "ru": "Числовые множества", }, { "level": 9, "en": "Introduction to nth degree root", "az": "n -ci dərəcədən kökə giriş", "ru": "Введение в корень n-й степени", }, { "level": 9, "en": "Properties of nth degree root", "az": "n-ci dərəcədən kökün xassələri", "ru": "Свойства корня n-й степени", }, { "level": 9, "en": "Taking the factor out from under the root sign", "az": "Vuruğun kök işarəsi altindan çıxarılması", "ru": "Вынесение множителя из-под знака корня", }, { "level": 9, "en": "Putting the factor under the root sign", "az": "Vuruğun kök işarəsi altina daxil edilməsi", "ru": "Внесение множителя под знак корня", }, ], }, { "en": "Rational Exponents", "az": "Rasional üstlü qüvvətlər", "ru": "Рациональные показатели", "subtopics": [ { "level": 9, "en": "Rational Exponents", "az": "Rasional üstlü qüvvətlər", "ru": "Рациональные показатели", }, { "level": 9, "en": "Properties of Rational Exponents", "az": "Rasional üstlü qüvvənin xassələri", "ru": "Свойства степени с рациональным показателем", }, ], }, { "en": "Circle", "az": "Çevrə", "ru": "Окружность", "subtopics": [ { "level": 9, "en": "Central angle. Arc of a circle", "az": "Mərkəzi bucaq. Çevrə qövsü", "ru": "Центральный угол. Дуга окружности", }, { "level": 9, "en": "Arc length", "az": "Qövsün uzunluğu", "ru": "Длина дуги", }, { "level": 9, "en": "Properties of a chord", "az": "Vətərin xassələri", "ru": "Свойства хорды", }, { "level": 9, "en": "Angle inscribed in a circle", "az": "Çevrə daxilinə çəkilmiş bucaq", "ru": "Угол, вписанный в окружность", }, { "level": 9, "en": "Tangent to a circle", "az": "Çevrəyə toxunan", "ru": "Касательная к окружности", }, { "level": 9, "en": "Angles formed by tangents and secants", "az": "Çevrəyə çəkilmiş toxunanlar və kəsənlər arasındakı bucaqlar", "ru": "Углы, образованные касательными и секущими", }, { "level": 9, "en": "Proportionality of chords and tangents in a circle", "az": "Çevrədə vətər və kəsənlərin parçalarının mütənasibliyi", "ru": "Пропорциональность отрезков хорд и секущих окружности", }, ], }, { "en": "Functions and Graphs", "az": "Funksiyalar və qrafiklər", "ru": "Функции и графики", "subtopics": [ { "level": 9, "en": "Quadratic function and its graph", "az": "Kvadratik funksiya və onun qrafiki", "ru": "Квадратичная функция и ее график", }, { "level": 9, "en": "Representation of the quadratic function in different forms", "az": "Kvadratik funksiyanın müxtəlif formalarda təqdimi", "ru": "Представление квадратичной функции в разных формах", }, { "level": 9, "en": "Plotting the graph of the function y = ax^2 + bx + c", "az": "y = ax^2 + bx + c funksiyasının qrafikinin qurulması", "ru": "Построение графика функции y = ax^2 + bx + c", }, { "level": 9, "en": "Properties of the function y = ax^2 + bx + c", "az": "y = ax^2 + bx + c funksiyasının xassələri", "ru": "Свойства функции y = ax^2 + bx + c", }, { "level": 9, "en": "Function y = |x| and its graph", "az": "y = |x| funksiyası və onun qrafiki", "ru": "Функция у = |х| и ее график", }, { "level": 9, "en": "Function y = x^3 and its graph", "az": "y = x^3 funksiyası və onun qrafiki", "ru": "Функция у = x^3 и ее график", }, ], }, { "en": "Equation of a circle", "az": "Çevrənin tənliyi", "ru": "Уравнение окружности", "subtopics": [ { "level": 9, "en": "Distance between two points", "az": "İki nöqtə arasındakı məsafə düsturu", "ru": "Расстояние между двумя точками", }, { "level": 9, "en": "Equation of a circle", "az": "Çevrənin tənliyi", "ru": "Уравнение окружности", }, { "level": 9, "en": "Coordinates of points on a circle and trigonometric ratios", "az": "Çevrə üzərindəki nöqtələrin koordinatları və triqonometrik nisbətlər", "ru": "Координаты точек, находящихся на окружности, и тригонометрические соотношения", }, { "level": 9, "en": "Area of a circular sector and segment", "az": "Dairə sektoru və seqmentinin sahəsi", "ru": "Площадь кругового сектора и сегмента", }, ], }, { "en": "Equations and System of equations", "az": "Tənliklər və tənlikler sistemi", "ru": "Уравнения и система уравнений", "subtopics": [ { "level": 9, "en": "Equations of higher degrees", "az": "Yüksək dərəcəli tənliklər", "ru": "Уравнения высших степеней", }, { "level": 9, "en": "Rational equations", "az": "Rasional tənliklər", "ru": "Рациональные уравнения", }, { "level": 9, "en": "Equations with modulus", "az": "Modullu tənliklər", "ru": "Уравнения с модулем", }, { "level": 9, "en": "Irrational equations", "az": "İrrasional tənliklər", "ru": "Иррациональные уравнения", }, { "level": 9, "en": "Introduction to system of equations", "az": "Tənliklər sisteminə giriş", "ru": "Введение в систему уравнений", }, { "level": 9, "en": "Systems of equations in which one equation is of the first and the other of the second degree", "az": "Bir tənliyi birdərəcəli, digəri ikidərəcəli olan tənliklər sistemi", "ru": "Системы уравнений, в которых одно уравнение первой, а другое второй степени", }, { "level": 9, "en": "Solution of the system by algebraic methods", "az": "Tənliklər sisteminin cəbri üsulla həlli", "ru": "Решение системы алгебраическими методами", }, { "level": 9, "en": "Systems of equations in which both equations are of the second degree", "az": "Hər iki tənliyi ikidərəcəli olan tənliklər sistemi", "ru": "Системы уравнений, в которых оба уравнения второй степени", }, { "level": 9, "en": "Problems leading to a system of equations", "az": "Tənliklər sisteminə gətirilən məsələlər", "ru": "Задачи, приводящие к системе уравнений", }, ], }, { "en": "Polygons", "az": "Çoxbucaqlılar", "ru": "Многоугольники", "subtopics": [ { "level": 9, "en": "Introduction to Polygons", "az": "Çoxbucaqlılara giriş", "ru": "Введение в многоугольники", }, { "level": 9, "en": "The sum of the interior and exterior angles of a convex polygon", "az": "Qabarıq çoxbucaqlının daxili və xarici bucaqlarının cəmi", "ru": "Сумма внутренних и внешних углов выпуклого многоугольника", }, { "level": 9, "en": "Inscribed and circumscribed polygons", "az": "Çevrənin daxilinə və xaricinə çəkilmiş çoxbucaqlılar", "ru": "Вписанные и описанные многоугольники", }, { "level": 9, "en": "Inscribed and circumscribed triangles", "az": "Üçbucağın daxilinə və xaricinə çəkilmiş çevrələr", "ru": "Вписанные и описанные треугольники", }, { "level": 9, "en": "Properties of inscribed and circumscribed quadrilaterals", "az": "Çevrənin daxilinə və xaricinə çəkilmiş dördbucaqlının xassələri", "ru": "Свойства вписанных и описанных четырехугольников", }, { "level": 9, "en": "Inscribed and circumscribed regular polygons", "az": "Düzgün çoxbucaqlının daxilinə və xaricinə çəkilmiş çevrələr", "ru": "Вписанные и описанные правильные многоугольники", }, { "level": 9, "en": "Area of a regular polygon", "az": "Düzgün çoxbucaqlının sahəsi", "ru": "Площадь правильного многоугольника", }, ], }, { "en": "Inequalities", "az": "Bərabərsizliklər", "ru": "Неравенства", "subtopics": [ { "level": 9, "en": "System of Linear Inequalities", "az": "Xətti bərabərsizliklər sistemi", "ru": "Система линейных неравенств", }, { "level": 9, "en": "Inequalities with modulus", "az": "Modullu bərabərsizliklər", "ru": "Неравенства с модулем", }, { "level": 9, "en": "Quadratic inequalities", "az": "Kvadrat bərabərsizliklər", "ru": "Квадратные неравенства", }, { "level": 9, "en": "Interval method", "az": "İntervallar üsulu", "ru": "Метод интервалов", }, { "level": 9, "en": "Solution of rational inequalities by interval method", "az": "Rasional bərabərsizliklərin intervallar üsulu ilə həlli", "ru": "Решение рациональных неравенств методом интервалов", }, { "level": 9, "en": "Irretional inequalities", "az": "İrrasional bərabərsizliklər", "ru": "Иррациональные неравенства", }, ], }, { "en": "Vectors", "az": "Vektorlar", "ru": "Векторы", "subtopics": [ { "level": 9, "en": "Intorduction to Vectors", "az": "Vektorlara giriş", "ru": "Введение в векторы", }, { "level": 9, "en": "Vectors on the Cartesian coordinate plane", "az": "Dekart koordinat müstəvisində vektorlar", "ru": "Векторы на декартовой координатной плоскости", }, { "level": 9, "en": "Vector direction and direction angle", "az": "Vektorun istiqaməti və meyil bucağı", "ru": "Направление вектора и угол наклона", }, { "level": 9, "en": "Trigonometric relations and vector components", "az": "Triqonometrik nisbətlər və vektorun komponentləri", "ru": "Тригонометрические соотношения и компоненты вектора", }, { "level": 9, "en": "Addition and subtraction of vectors", "az": "Vektorların toplanması və çıxılması", "ru": "Сложение и вычитание векторов", }, { "level": 9, "en": "Addition of collinear vectors", "az": "Kollinear vektorların toplanması", "ru": "Сложение коллинеарных векторов", }, { "level": 9, "en": "Addition and subtraction of non-collinear vectors", "az": "Kollinear olmayan vektorların toplanması və çıxılması", "ru": "Сложение и вычитание неколлинеарных векторов", }, { "level": 9, "en": "Addition of vectors given by components", "az": "Vektorların komponentlərindən istifadə etməklə toplanması", "ru": "Сложение векторов, заданных компонентами", }, { "level": 9, "en": "Multiplying a vector by a number", "az": "Vektorun ədədə vurulması", "ru": "Умножение вектора на число", }, { "level": 9, "en": "Operations on vectors given by components", "az": "Komponentləri ilə verilmiş vektorlar üzərində əməllər", "ru": "Операции над векторами, заданными компонентами", }, { "level": 9, "en": "Parallel transport", "az": "Paralel köçürmə", "ru": "Параллельный перенос", }, { "level": 9, "en": "Movement and congruent figures", "az": "Hərəkət və konqruyent fiqurlar", "ru": "Движение и конгруэнтные фигуры", }, ], }, { "en": "Numerical sequences", "az": "Ədədi ardıcıllıqlar", "ru": "Числовые последовательности", "subtopics": [ { "level": 9, "en": "Introduction to numerical sequences", "az": "Ədədi ardıcıllıqlara giriş", "ru": "Введение в числовые последовательности", }, { "level": 9, "en": "Arithmetic progression", "az": "Ədədi silsilə", "ru": "Арифметическая прогрессия", }, { "level": 9, "en": "nth term of an arithmetic progression", "az": "Ədədi silsilənin n-ci həddi", "ru": "n-й член арифметической прогрессии", }, { "level": 9, "en": "Properties of arithmetic progression", "az": "Ədədi silsilənin xassələri", "ru": "Свойства арифметической прогрессии", }, { "level": 9, "en": "Sum of n terms of an arithmetic progression", "az": "Ədədi silsilənin n həddinin cəmi", "ru": "Сумма n членов арифметической прогрессии", }, { "level": 9, "en": "Geometric progression", "az": "Həndəsi silsilə", "ru": "Геометрическая прогрессия", }, { "level": 9, "en": "nth term of a geometric progression", "az": "Həndəsi silsilənin n-ci həddi", "ru": "n-й член геометрической прогрессии", }, { "level": 9, "en": "Properties of geometric progression", "az": "Həndəsi silsilənin xassələri", "ru": "Свойства геометрической прогрессии", }, { "level": 9, "en": "Sum of n terms of a geometric progression", "az": "Həndəsi silsilənin n həddinin cəmi", "ru": "Сумма n членов геометрической прогрессии", }, { "level": 9, "en": "Sum of infinitely decreasing geometric progression", "az": "Sonsuz azalan həndəsi silsilənin cəmi", "ru": "Сумма бесконечно убывающей геометрической прогрессии", }, ], }, { "en": "Combinatorics and Permutations", "az": "Kombinatorika və Ehtimal", "ru": "Комбинаторика и Перестановки", "subtopics": [ { "level": 9, "en": "Relative frequency", "az": "Nisbi tezlik", "ru": "Относительная частота", }, { "level": 9, "en": "Arithmetic mean of frequency distribution", "az": "Tezlik paylanmasına görə ədədi orta", "ru": "Среднее арифметическое по распределению частот", }, { "level": 9, "en": "Permuations nPn", "az": "Permutasiya nPn", "ru": "Перестановки nPn", }, { "level": 9, "en": "Permutations with repetitions", "az": "Təkrarlı permutasiyalar", "ru": "Пермутации с повторениями", }, { "level": 9, "en": "Permutations - Placements, nPk", "az": "Permutasiyalar - Yerləşmələr, nPk", "ru": "Пермутации - Размещения, nPk", }, { "level": 9, "en": "Combinations nCk", "az": "Kombinezon, nCk", "ru": "Комбинезон nCk", }, ], },]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384from google.cloud import translate_v3 as translatefrom translation import TOPICS, DIFFICULTY
# -----------------------------# Helper Function: Translate Text# -----------------------------def translate_text(text, project_id, target_lang="az", source_lang=None): """Translate text to the target language using Google Translate API.""" if not text.strip(): return text # Return empty text unchanged try: translate_client = translate.TranslationServiceClient() parent = f"projects/{project_id}/locations/global" response = translate_client.translate_text( contents=[text], target_language_code=target_lang, parent=parent, mime_type="text/plain", source_language_code=source_lang, ) return response.translations[0].translated_text except Exception as e: return f"Translation Error: {str(e)}"
# -----------------------------# Helper Function: Get Topics List# -----------------------------def get_topic_names(lang): return [topic[lang] for topic in TOPICS]
# -----------------------------# Helper Function: Get Subtopics List# -----------------------------def get_subtopics(selected_topic, lang): if not selected_topic: return []
# Reverse map to find subtopics of selected topic subtopics = next( (topic["subtopics"] for topic in TOPICS if topic[lang] == selected_topic), None )
return [subtopic[lang] for subtopic in subtopics]
# -----------------------------# Helper Function: Get English Topic and Subtopic Names# -----------------------------def get_eng_names(selected_topic, selected_subtopic, difficulty, lang): if not selected_topic or not selected_subtopic: return None, None
# Reverse map to find English names of selected topic and subtopic topic_en, subtopics = next( ( (topic["en"], topic["subtopics"]) for topic in TOPICS if topic[lang] == selected_topic ), None, )
subtopic_en = next( ( subtopic["en"] for subtopic in subtopics if subtopic[lang] == selected_subtopic ), None, )
difficulty_en = next( ( difficulty["en"] for difficulty in DIFFICULTY if difficulty[lang] == difficulty ), None, )
return topic_en, subtopic_en, difficulty_en.DS_Store
.gitignore+1
gradio_app.py+303-36
prompts.py+20-12
translation.pyAdded+592
utils.pyAdded+84