Shaptoli commited on
Commit
4fc3dbd
Β·
1 Parent(s): 8bfde3b

feat: multi-tier adaptive engine, PDF synopsis generator, and interactive math keyboard

Browse files
Files changed (5) hide show
  1. app.py +23 -6
  2. app/pdf_generator.py +320 -0
  3. app/pipeline.py +86 -5
  4. bot.py +214 -4
  5. requirements.txt +1 -0
app.py CHANGED
@@ -26,6 +26,7 @@ from app.db import get_statistics
26
  from app.pipeline import solve_problem, get_agent_configs, get_groq_key
27
  from app.geometry_drawer import try_draw_geometry
28
  from app.vision import extract_problem_from_image
 
29
 
30
  # 1. Telegram botni orqa fonda 24/7 ishga tushirish
31
  def start_bot_background():
@@ -169,6 +170,7 @@ def solve_problem_web(problem_text: str, image_file):
169
  return (
170
  "<div class='sincc-card warning-card'>⚠️ Iltimos, masala shartini matn ko'rinishida yozing yoki uning rasmini yuklang.</div>",
171
  gr.update(value=None, visible=False),
 
172
  ""
173
  )
174
 
@@ -178,13 +180,27 @@ def solve_problem_web(problem_text: str, image_file):
178
 
179
  # Geometrik chizma tekshiruvi
180
  img_path = try_draw_geometry(text)
181
- if img_path and os.path.exists(img_path):
182
- return html_output, gr.update(value=img_path, visible=True), text
183
- else:
184
- return html_output, gr.update(value=None, visible=False), text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  except Exception as e:
186
  err_html = f"<div class='sincc-card error-card'>❌ Yechish jarayonida kutilmagan xatolik: {html.escape(str(e))}</div>"
187
- return err_html, gr.update(value=None, visible=False), text
188
 
189
  # 5. Geometriya Laboratoriyasi Funksiyasi
190
  def generate_geometry_lab(shape_type: str, p1: float, p2: float, p3: float):
@@ -806,6 +822,7 @@ with gr.Blocks(title="Sincc.on β€” Milliy Matematika & Geometriya AI") as demo:
806
  )
807
  with gr.Column(scale=2):
808
  output_diagram = gr.Image(label="πŸ“ Geometrik Chizma", visible=False)
 
809
 
810
  gr.Markdown("#### πŸ’‘ Tezkor Misollar (bosing va sinab ko'ring):")
811
  gr.Examples(
@@ -824,7 +841,7 @@ with gr.Blocks(title="Sincc.on β€” Milliy Matematika & Geometriya AI") as demo:
824
  btn_solve.click(
825
  fn=solve_problem_web,
826
  inputs=[input_problem, input_image],
827
- outputs=[output_html, output_diagram, input_problem],
828
  api_name=False
829
  )
830
 
 
26
  from app.pipeline import solve_problem, get_agent_configs, get_groq_key
27
  from app.geometry_drawer import try_draw_geometry
28
  from app.vision import extract_problem_from_image
29
+ from app.pdf_generator import generate_math_pdf
30
 
31
  # 1. Telegram botni orqa fonda 24/7 ishga tushirish
32
  def start_bot_background():
 
170
  return (
171
  "<div class='sincc-card warning-card'>⚠️ Iltimos, masala shartini matn ko'rinishida yozing yoki uning rasmini yuklang.</div>",
172
  gr.update(value=None, visible=False),
173
+ gr.update(value=None, visible=False),
174
  ""
175
  )
176
 
 
180
 
181
  # Geometrik chizma tekshiruvi
182
  img_path = try_draw_geometry(text)
183
+ has_img = bool(img_path and os.path.exists(img_path))
184
+
185
+ # PDF Konspekt generatsiyasi
186
+ pdf_path = None
187
+ try:
188
+ if res.get("type") == "solve" and (res.get("steps") or res.get("final_answer")):
189
+ pdf_path = generate_math_pdf(text, res, img_path if has_img else None)
190
+ except Exception as e_pdf:
191
+ print(f"[Web PDF error]: {e_pdf}")
192
+
193
+ has_pdf = bool(pdf_path and os.path.exists(pdf_path))
194
+
195
+ return (
196
+ html_output,
197
+ gr.update(value=img_path if has_img else None, visible=has_img),
198
+ gr.update(value=pdf_path if has_pdf else None, visible=has_pdf),
199
+ text
200
+ )
201
  except Exception as e:
202
  err_html = f"<div class='sincc-card error-card'>❌ Yechish jarayonida kutilmagan xatolik: {html.escape(str(e))}</div>"
203
+ return err_html, gr.update(value=None, visible=False), gr.update(value=None, visible=False), text
204
 
205
  # 5. Geometriya Laboratoriyasi Funksiyasi
206
  def generate_geometry_lab(shape_type: str, p1: float, p2: float, p3: float):
 
822
  )
823
  with gr.Column(scale=2):
824
  output_diagram = gr.Image(label="πŸ“ Geometrik Chizma", visible=False)
825
+ output_pdf = gr.File(label="πŸ“₯ Tayyor A4 PDF Konspekt", visible=False)
826
 
827
  gr.Markdown("#### πŸ’‘ Tezkor Misollar (bosing va sinab ko'ring):")
828
  gr.Examples(
 
841
  btn_solve.click(
842
  fn=solve_problem_web,
843
  inputs=[input_problem, input_image],
844
+ outputs=[output_html, output_diagram, output_pdf, input_problem],
845
  api_name=False
846
  )
847
 
app/pdf_generator.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sincc.on: Matematika va Geometriya Masalalari uchun PDF Konspekt Generatori.
3
+ ReportLab orqali A4 formatdagi professional, chiroyli va chop etishga tayyor konspekt yaratadi.
4
+ """
5
+
6
+ import os
7
+ import tempfile
8
+ import datetime
9
+ import html
10
+ from reportlab.lib.pagesizes import A4
11
+ from reportlab.lib import colors
12
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
13
+ from reportlab.platypus import (
14
+ SimpleDocTemplate,
15
+ Paragraph,
16
+ Spacer,
17
+ Table,
18
+ TableStyle,
19
+ Image as PlatypusImage,
20
+ KeepTogether,
21
+ HRFlowable
22
+ )
23
+ from reportlab.pdfbase import pdfmetrics
24
+ from reportlab.pdfbase.ttfonts import TTFont
25
+
26
+ _REGISTERED_FONT = None
27
+
28
+ def _get_font_name() -> str:
29
+ global _REGISTERED_FONT
30
+ if _REGISTERED_FONT:
31
+ return _REGISTERED_FONT
32
+
33
+ candidates = [
34
+ "C:\\Windows\\Fonts\\arial.ttf",
35
+ "C:\\Windows\\Fonts\\calibri.ttf",
36
+ "C:\\Windows\\Fonts\\segoeui.ttf",
37
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
38
+ "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
39
+ "/usr/share/fonts/TTF/DejaVuSans.ttf",
40
+ "/usr/share/fonts/truetype/freefont/FreeSans.ttf"
41
+ ]
42
+ for path in candidates:
43
+ if os.path.exists(path):
44
+ try:
45
+ pdfmetrics.registerFont(TTFont("SinccFont", path))
46
+ # Bold variant if available
47
+ bold_path = path.replace(".ttf", "bd.ttf").replace("-Regular.ttf", "-Bold.ttf")
48
+ if os.path.exists(bold_path):
49
+ pdfmetrics.registerFont(TTFont("SinccFont-Bold", bold_path))
50
+ else:
51
+ pdfmetrics.registerFont(TTFont("SinccFont-Bold", path))
52
+ _REGISTERED_FONT = "SinccFont"
53
+ return "SinccFont"
54
+ except Exception:
55
+ pass
56
+
57
+ _REGISTERED_FONT = "Helvetica"
58
+ return "Helvetica"
59
+
60
+ def _safe_text(text: str, is_custom_font: bool) -> str:
61
+ if not text:
62
+ return ""
63
+ s = str(text).strip()
64
+ if not is_custom_font:
65
+ repls = {
66
+ "√": "sqrt", "²": "^2", "³": "^3", "⁴": "^4", "⁰": "^0",
67
+ "Β±": "+/-", "Β·": "*", "Γ·": "/", "Ο€": "pi", "∞": "oo",
68
+ "≀": "<=", "β‰₯": ">=", "β‰ ": "!=", "βŠ₯": " perp ",
69
+ "β€˜": "'", "’": "'", "β€œ": '"', "”": '"', "β€”": "-", "–": "-"
70
+ }
71
+ for k, v in repls.items():
72
+ s = s.replace(k, v)
73
+ return html.escape(s).replace("\n", "<br/>")
74
+
75
+ def generate_math_pdf(question: str, solution: dict, diagram_path: str | None = None) -> str:
76
+ """
77
+ Berilgan masala va yechim asosida A4 formatdagi yuqori sifatli PDF konspekt fayli yaratadi.
78
+ Qaytaradi: yaratilgan vaqtinchalik .pdf faylining to'liq yo'li.
79
+ """
80
+ temp_dir = tempfile.gettempdir()
81
+ now_tag = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
82
+ pdf_filename = f"Sincc_Konspekt_{now_tag}.pdf"
83
+ pdf_path = os.path.join(temp_dir, pdf_filename)
84
+
85
+ doc = SimpleDocTemplate(
86
+ pdf_path,
87
+ pagesize=A4,
88
+ leftMargin=36,
89
+ rightMargin=36,
90
+ topMargin=32,
91
+ bottomMargin=32
92
+ )
93
+
94
+ font_name = _get_font_name()
95
+ font_bold = "SinccFont-Bold" if font_name == "SinccFont" else "Helvetica-Bold"
96
+ is_custom = (font_name == "SinccFont")
97
+
98
+ styles = getSampleStyleSheet()
99
+
100
+ # Maxsus uslublar
101
+ title_style = ParagraphStyle(
102
+ "SinccTitle",
103
+ fontName=font_bold,
104
+ fontSize=18,
105
+ leading=22,
106
+ textColor=colors.HexColor("#1e1b4b"),
107
+ alignment=0
108
+ )
109
+ subtitle_style = ParagraphStyle(
110
+ "SinccSubtitle",
111
+ fontName=font_name,
112
+ fontSize=10,
113
+ leading=14,
114
+ textColor=colors.HexColor("#475569")
115
+ )
116
+ section_h_style = ParagraphStyle(
117
+ "SinccSectionH",
118
+ fontName=font_bold,
119
+ fontSize=12,
120
+ leading=16,
121
+ textColor=colors.HexColor("#1e293b")
122
+ )
123
+ body_style = ParagraphStyle(
124
+ "SinccBody",
125
+ fontName=font_name,
126
+ fontSize=10.5,
127
+ leading=15,
128
+ textColor=colors.HexColor("#1e293b")
129
+ )
130
+ step_num_style = ParagraphStyle(
131
+ "SinccStepNum",
132
+ fontName=font_bold,
133
+ fontSize=10,
134
+ leading=14,
135
+ textColor=colors.white,
136
+ alignment=1
137
+ )
138
+ ans_value_style = ParagraphStyle(
139
+ "SinccAnsVal",
140
+ fontName=font_bold,
141
+ fontSize=16,
142
+ leading=20,
143
+ textColor=colors.HexColor("#065f46"),
144
+ alignment=1
145
+ )
146
+ ans_stamp_style = ParagraphStyle(
147
+ "SinccAnsStamp",
148
+ fontName=font_name,
149
+ fontSize=8.5,
150
+ leading=11,
151
+ textColor=colors.HexColor("#047857"),
152
+ alignment=1
153
+ )
154
+ tip_style = ParagraphStyle(
155
+ "SinccTip",
156
+ fontName=font_name,
157
+ fontSize=9.5,
158
+ leading=14,
159
+ textColor=colors.HexColor("#92400e")
160
+ )
161
+ footer_style = ParagraphStyle(
162
+ "SinccFooter",
163
+ fontName=font_name,
164
+ fontSize=8.5,
165
+ leading=11,
166
+ textColor=colors.HexColor("#94a3b8"),
167
+ alignment=1
168
+ )
169
+
170
+ story = []
171
+
172
+ # 1. HEADER (Sarlavha qutisi)
173
+ header_data = [
174
+ [
175
+ Paragraph("<b>πŸ“ Sincc.on</b> β€” Milliy Matematika AI", title_style),
176
+ Paragraph(datetime.datetime.now().strftime("%d.%m.%Y | %H:%M"), subtitle_style)
177
+ ],
178
+ [
179
+ Paragraph("Zero Arithmetic Hallucination β€’ SymPy AST Sandbox Konspekti", subtitle_style),
180
+ Paragraph("Telegram: @sincconbot", subtitle_style)
181
+ ]
182
+ ]
183
+ header_table = Table(header_data, colWidths=[380, 140])
184
+ header_table.setStyle(TableStyle([
185
+ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
186
+ ('ALIGN', (1, 0), (1, -1), 'RIGHT'),
187
+ ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
188
+ ('TOPPADDING', (0, 0), (-1, -1), 2),
189
+ ]))
190
+ story.append(header_table)
191
+ story.append(Spacer(1, 10))
192
+ story.append(HRFlowable(width="100%", thickness=1.5, color=colors.HexColor("#4f46e5"), spaceAfter=14))
193
+
194
+ # 2. MASALA SHARTI (Savol qutisi)
195
+ clean_q = _safe_text(question, is_custom)
196
+ q_content = [
197
+ [Paragraph("<b>πŸ“ MASALA SHARTI:</b>", section_h_style)],
198
+ [Paragraph(clean_q, body_style)]
199
+ ]
200
+ q_table = Table(q_content, colWidths=[520])
201
+ q_table.setStyle(TableStyle([
202
+ ('BACKGROUND', (0, 0), (-1, -1), colors.HexColor("#f8fafc")),
203
+ ('BOX', (0, 0), (-1, -1), 1, colors.HexColor("#cbd5e1")),
204
+ ('PADDING', (0, 0), (-1, -1), 10),
205
+ ('TOPPADDING', (0, 0), (-1, 0), 8),
206
+ ('BOTTOMPADDING', (0, 1), (-1, 1), 10),
207
+ ]))
208
+ story.append(q_table)
209
+ story.append(Spacer(1, 14))
210
+
211
+ # 3. YECHISH BOSQICHLARI
212
+ steps = solution.get("steps", [])
213
+ intro = solution.get("intro", "")
214
+ if intro:
215
+ story.append(Paragraph(f"πŸ§‘β€πŸ« <i>{_safe_text(intro, is_custom)}</i>", body_style))
216
+ story.append(Spacer(1, 8))
217
+
218
+ story.append(Paragraph("<b>πŸͺœ Qadam-baqadam Yechilishi:</b>", section_h_style))
219
+ story.append(Spacer(1, 6))
220
+
221
+ if steps:
222
+ step_rows = []
223
+ for idx, step in enumerate(steps, 1):
224
+ st_text = _safe_text(step, is_custom)
225
+ badge_p = Paragraph(f"<b>{idx}</b>", step_num_style)
226
+ text_p = Paragraph(st_text, body_style)
227
+ step_rows.append([badge_p, text_p])
228
+
229
+ steps_table = Table(step_rows, colWidths=[24, 490])
230
+ steps_table.setStyle(TableStyle([
231
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
232
+ ('BACKGROUND', (0, 0), (0, -1), colors.HexColor("#4f46e5")),
233
+ ('TEXTCOLOR', (0, 0), (0, -1), colors.white),
234
+ ('ALIGN', (0, 0), (0, -1), 'CENTER'),
235
+ ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
236
+ ('TOPPADDING', (0, 0), (-1, -1), 6),
237
+ ('LEFTPADDING', (1, 0), (1, -1), 10),
238
+ ('LINEBELOW', (0, 0), (-1, -1), 0.5, colors.HexColor("#f1f5f9")),
239
+ ]))
240
+ story.append(steps_table)
241
+ else:
242
+ reply_txt = solution.get("reply", "Yechim tahlil qilindi.")
243
+ story.append(Paragraph(_safe_text(reply_txt, is_custom), body_style))
244
+
245
+ story.append(Spacer(1, 12))
246
+
247
+ # 4. QO'LLANILGAN FORMULALAR
248
+ formulas = solution.get("formulas_used", [])
249
+ if formulas:
250
+ f_texts = " β€’ ".join(_safe_text(f, is_custom) for f in formulas if f)
251
+ f_data = [
252
+ [Paragraph("<b>πŸ“ Qo'llanilgan Qoidalar va Formulalar:</b>", section_h_style)],
253
+ [Paragraph(f_texts, body_style)]
254
+ ]
255
+ f_table = Table(f_data, colWidths=[520])
256
+ f_table.setStyle(TableStyle([
257
+ ('BACKGROUND', (0, 0), (-1, -1), colors.HexColor("#eef2ff")),
258
+ ('BOX', (0, 0), (-1, -1), 1, colors.HexColor("#c7d2fe")),
259
+ ('PADDING', (0, 0), (-1, -1), 8),
260
+ ]))
261
+ story.append(f_table)
262
+ story.append(Spacer(1, 12))
263
+
264
+ # 5. GEOMETRIK CHIZMA (Agar mavjud bo'lsa)
265
+ if diagram_path and os.path.exists(diagram_path):
266
+ try:
267
+ story.append(Paragraph("<b>πŸ“ Geometrik Chizma:</b>", section_h_style))
268
+ story.append(Spacer(1, 6))
269
+ img = PlatypusImage(diagram_path, width=280, height=200)
270
+ img.hAlign = 'CENTER'
271
+ story.append(img)
272
+ story.append(Spacer(1, 12))
273
+ except Exception as e:
274
+ print(f"[PDF] Chizmani joylashda xato: {e}")
275
+
276
+ # 6. YAKUNIY JAVOB KARTASI
277
+ final_ans = solution.get("final_answer", "")
278
+ if final_ans:
279
+ ans_text = _safe_text(str(final_ans), is_custom)
280
+ verified_note = "βœ“ SymPy Ramziy Dvigateli Tomonidan 100% Tasdiqlangan" if solution.get("verified") else "ℹ️ Matematik Mantiq Asosida Hisoblandi"
281
+ ans_content = [
282
+ [Paragraph("<b>YAKUNIY ANIQ JAVOB:</b>", ParagraphStyle("AnsLabel", fontName=font_bold, fontSize=10, textColor=colors.HexColor("#047857"), alignment=1))],
283
+ [Paragraph(f"<b>{ans_text}</b>", ans_value_style)],
284
+ [Paragraph(verified_note, ans_stamp_style)]
285
+ ]
286
+ ans_table = Table(ans_content, colWidths=[520])
287
+ ans_table.setStyle(TableStyle([
288
+ ('BACKGROUND', (0, 0), (-1, -1), colors.HexColor("#ecfdf5")),
289
+ ('BOX', (0, 0), (-1, -1), 1.5, colors.HexColor("#10b981")),
290
+ ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
291
+ ('PADDING', (0, 0), (-1, -1), 8),
292
+ ('TOPPADDING', (0, 0), (-1, 0), 8),
293
+ ('BOTTOMPADDING', (0, 2), (-1, 2), 8),
294
+ ]))
295
+ story.append(ans_table)
296
+ story.append(Spacer(1, 12))
297
+
298
+ # 7. USTOZ LAYFXAKI / MASLAHATI
299
+ tip = solution.get("explanation_tip", "")
300
+ if tip:
301
+ tip_content = [
302
+ [Paragraph(f"πŸ’‘ <b>Ustoz Maslahati:</b> {_safe_text(tip, is_custom)}", tip_style)]
303
+ ]
304
+ tip_table = Table(tip_content, colWidths=[520])
305
+ tip_table.setStyle(TableStyle([
306
+ ('BACKGROUND', (0, 0), (-1, -1), colors.HexColor("#fffbeb")),
307
+ ('BOX', (0, 0), (-1, -1), 1, colors.HexColor("#fcd34d")),
308
+ ('PADDING', (0, 0), (-1, -1), 8),
309
+ ]))
310
+ story.append(tip_table)
311
+ story.append(Spacer(1, 12))
312
+
313
+ # 8. FOOTER
314
+ story.append(Spacer(1, 10))
315
+ story.append(HRFlowable(width="100%", thickness=0.8, color=colors.HexColor("#e2e8f0"), spaceAfter=8))
316
+ footer_text = "Sincc.on Β© 2026 β€” Milliy O'zbek Matematika & Geometriya AI Ekotizimi | Muallif: Shahbozxon Abbosov (@sh_abbosov)"
317
+ story.append(Paragraph(footer_text, footer_style))
318
+
319
+ doc.build(story)
320
+ return pdf_path
app/pipeline.py CHANGED
@@ -46,6 +46,17 @@ def get_groq_key() -> str:
46
  return v
47
  return "no-key"
48
 
 
 
 
 
 
 
 
 
 
 
 
49
  def get_agent_configs():
50
  """Ikkala agentning konfiguratsiyasini muhit o'zgaruvchilaridan oladi."""
51
  groq_key = get_groq_key()
@@ -81,15 +92,79 @@ def solve_single_agent(agent_cfg: dict, text: str, script: str, history: list[di
81
  return query_llm(agent_cfg["base_url"], agent_cfg["api_key"], agent_cfg["model"], sys_prompt, text, history=history)
82
 
83
  def solve_problem(text: str, chat_history: list[dict] | None = None, bypass_cache: bool = False) -> dict:
84
- """Aqlli Router + Dual-Agent konsensus + SymPy tekshiruvi bilan yechish."""
 
 
 
 
 
85
  script = detect_script(text)
86
 
87
- # 0-BOSQICH: Faqat mustaqil matematik masalalar uchun keshdan tekshiramiz
88
  if not bypass_cache:
89
  cached = get_cached_solution(text)
90
  if cached:
 
91
  return cached
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  agent1_cfg, agent2_cfg = get_agent_configs()
94
 
95
  if not agent1_cfg["base_url"] and not agent2_cfg["base_url"]:
@@ -101,10 +176,10 @@ def solve_problem(text: str, chat_history: list[dict] | None = None, bypass_cach
101
  "consensus": False
102
  }
103
 
104
- # 1-BOSQICH: Asosiy AI Agent (suhbat tarixini bilgan holda) niyatni va birinchi javobni aniqlaydi
105
  sol1 = solve_single_agent(agent1_cfg, text, script, history=chat_history)
106
 
107
- # Agar bu oddiy suhbat, nazariya, follow-up savol yoki ma'lumoti yetarli bo'lmagan holat bo'lsa -> DARHOL tabiiy javob!
108
  if sol1 and sol1.get("type") in ("chat", "theory", "incomplete"):
109
  reply_text = sol1.get("reply") or sol1.get("final_answer") or "\n".join(sol1.get("steps", []))
110
  return {
@@ -112,10 +187,11 @@ def solve_problem(text: str, chat_history: list[dict] | None = None, bypass_cach
112
  "reply": str(reply_text).strip(),
113
  "verified": False,
114
  "consensus": True,
 
115
  "script": script
116
  }
117
 
118
- # Agar bu haqiqiy hisoblash masalasi ("solve") bo'lsa -> 2-Agent ham mustaqil yechadi!
119
  same_agent = (agent2_cfg["base_url"] == agent1_cfg["base_url"] and agent2_cfg["model"] == agent1_cfg["model"])
120
  sol2 = solve_single_agent(agent2_cfg, text, script, history=chat_history) if not same_agent else sol1
121
 
@@ -130,6 +206,7 @@ def solve_problem(text: str, chat_history: list[dict] | None = None, bypass_cach
130
  "reply": str(reply_text).strip(),
131
  "verified": False,
132
  "consensus": True,
 
133
  "script": script
134
  }
135
 
@@ -141,6 +218,7 @@ def solve_problem(text: str, chat_history: list[dict] | None = None, bypass_cach
141
  "verified": False,
142
  "script": script,
143
  "consensus": False,
 
144
  "note": "AI serverlaridan javob olishda vaqtinchalik uzilish bo'ldi."
145
  }
146
 
@@ -168,6 +246,7 @@ def solve_problem(text: str, chat_history: list[dict] | None = None, bypass_cach
168
  "explanation_tip": tip,
169
  "verified": True,
170
  "consensus": True,
 
171
  "debate_occurred": False,
172
  "script": script
173
  }
@@ -203,6 +282,7 @@ def solve_problem(text: str, chat_history: list[dict] | None = None, bypass_cach
203
  "explanation_tip": tip,
204
  "verified": True,
205
  "consensus": True,
 
206
  "debate_occurred": True,
207
  "script": script
208
  }
@@ -236,6 +316,7 @@ def solve_problem(text: str, chat_history: list[dict] | None = None, bypass_cach
236
  "explanation_tip": tip,
237
  "verified": ok1 or ok2,
238
  "consensus": False,
 
239
  "debate_occurred": True,
240
  "script": script
241
  }
 
46
  return v
47
  return "no-key"
48
 
49
+ def get_fast_agent_config():
50
+ """Tezkor Tier 1 agent konfiguratsiyasi (bepul va o'ta tez Llama-3.3-70B yoki GPT-OSS-20B)."""
51
+ groq_key = get_groq_key()
52
+ groq_url = "https://api.groq.com/openai/v1"
53
+ return {
54
+ "name": os.getenv("FAST_AGENT_NAME", "GPT-OSS-20B (Groq Fast Tier)"),
55
+ "base_url": os.getenv("FAST_AGENT_BASE_URL") or os.getenv("LLM_BASE_URL") or groq_url,
56
+ "api_key": clean_key(os.getenv("FAST_AGENT_API_KEY")) or groq_key,
57
+ "model": os.getenv("FAST_AGENT_MODEL", "openai/gpt-oss-20b")
58
+ }
59
+
60
  def get_agent_configs():
61
  """Ikkala agentning konfiguratsiyasini muhit o'zgaruvchilaridan oladi."""
62
  groq_key = get_groq_key()
 
92
  return query_llm(agent_cfg["base_url"], agent_cfg["api_key"], agent_cfg["model"], sys_prompt, text, history=history)
93
 
94
  def solve_problem(text: str, chat_history: list[dict] | None = None, bypass_cache: bool = False) -> dict:
95
+ """
96
+ Kaskadli 'Zinama-zina' AI Dvigateli (Adaptive Multi-Tier Engine):
97
+ - Tier 0: Lokal SymPy Dvigateli (0.005 soniya, 100% aniq algebra/tenglama/Pifagor)
98
+ - Tier 1: Tezkor AI Tier (Groq Fast Tier - GPT-OSS-20B yoki Llama-3.3-70B + SymPy tekshiruvi)
99
+ - Tier 2: Og'ir Dual-Agent Konsensus & Kross-Debat (GPT-OSS-120B + Qwen-3.8-27B + AST Sandbox)
100
+ """
101
  script = detect_script(text)
102
 
103
+ # 0-BOSQICH: Keshdan tekshiramiz
104
  if not bypass_cache:
105
  cached = get_cached_solution(text)
106
  if cached:
107
+ cached["tier"] = "Cache (0.001s)"
108
  return cached
109
 
110
+ # TIER 0: Lokal ramziy SymPy dvigateli (suhbat tarixi bo'lmaganda eng tezkor)
111
+ if not chat_history:
112
+ try:
113
+ from chat import universal_local_solve
114
+ lokal = universal_local_solve(text)
115
+ if lokal and lokal.get("verified"):
116
+ lokal["tier"] = "Tier 0 (Lokal SymPy - 0.005s)"
117
+ if not bypass_cache:
118
+ save_cached_solution(text, lokal)
119
+ return lokal
120
+ except Exception as e_lokal:
121
+ print(f"[Tier 0 Lokal xatosi]: {e_lokal}")
122
+
123
+ # TIER 1: Tezkor AI Modeli (Fast Tier)
124
+ fast_cfg = get_fast_agent_config()
125
+ if fast_cfg.get("base_url") and fast_cfg.get("api_key") != "no-key":
126
+ try:
127
+ sol_fast = solve_single_agent(fast_cfg, text, script, history=chat_history)
128
+ if sol_fast:
129
+ stype = sol_fast.get("type", "solve")
130
+ # Agar oddiy suhbat, nazariya yoki tushuntirish bo'lsa -> zudlik bilan javob
131
+ if stype in ("chat", "theory", "incomplete"):
132
+ reply_text = sol_fast.get("reply") or sol_fast.get("final_answer") or "\n".join(sol_fast.get("steps", []))
133
+ return {
134
+ "type": stype,
135
+ "reply": str(reply_text).strip(),
136
+ "verified": False,
137
+ "consensus": True,
138
+ "tier": "Tier 1 (Fast Agent Chat)",
139
+ "script": script
140
+ }
141
+
142
+ # Agar hisoblash masalasi bo'lsa -> SymPy AST orqali tekshiramiz
143
+ out_fast = run_sympy(sol_fast.get("sympy_code", ""))
144
+ ans_fast = str(sol_fast.get("final_answer", "")).strip()
145
+ if out_fast is not None and same_answer(out_fast, ans_fast):
146
+ print(f"[Tier 1 Fast] Muvaffaqiyatli tasdiqlandi: {out_fast}")
147
+ res = {
148
+ "type": "solve",
149
+ "intro": sol_fast.get("intro", ""),
150
+ "steps": sol_fast.get("steps", []),
151
+ "final_answer": _pick_display_answer(out_fast, ans_fast),
152
+ "formulas_used": sol_fast.get("formulas_used", []),
153
+ "explanation_tip": sol_fast.get("explanation_tip", ""),
154
+ "verified": True,
155
+ "consensus": True,
156
+ "tier": "Tier 1 (Fast Agent + SymPy)",
157
+ "debate_occurred": False,
158
+ "script": script
159
+ }
160
+ save_cached_solution(text, res)
161
+ return res
162
+ else:
163
+ print(f"[Tier 1 Fast] SymPy tekshiruvidan o'tmadi (out={out_fast}, ans={ans_fast}). Tier 2 ga oshirilmoqda...")
164
+ except Exception as e_fast:
165
+ print(f"[Tier 1 Fast xatosi]: {e_fast}")
166
+
167
+ # TIER 2: Og'ir Dual-Agent Konsensus va Kross-Debat (Heavy Multi-Agent Engine)
168
  agent1_cfg, agent2_cfg = get_agent_configs()
169
 
170
  if not agent1_cfg["base_url"] and not agent2_cfg["base_url"]:
 
176
  "consensus": False
177
  }
178
 
179
+ # 1-Agent
180
  sol1 = solve_single_agent(agent1_cfg, text, script, history=chat_history)
181
 
182
+ # Agar bu oddiy suhbat, nazariya yoki tushuntirish bo'lsa
183
  if sol1 and sol1.get("type") in ("chat", "theory", "incomplete"):
184
  reply_text = sol1.get("reply") or sol1.get("final_answer") or "\n".join(sol1.get("steps", []))
185
  return {
 
187
  "reply": str(reply_text).strip(),
188
  "verified": False,
189
  "consensus": True,
190
+ "tier": "Tier 2 (Heavy Agent Chat)",
191
  "script": script
192
  }
193
 
194
+ # 2-Agent ham mustaqil yechadi
195
  same_agent = (agent2_cfg["base_url"] == agent1_cfg["base_url"] and agent2_cfg["model"] == agent1_cfg["model"])
196
  sol2 = solve_single_agent(agent2_cfg, text, script, history=chat_history) if not same_agent else sol1
197
 
 
206
  "reply": str(reply_text).strip(),
207
  "verified": False,
208
  "consensus": True,
209
+ "tier": "Tier 2 (Heavy Agent Chat)",
210
  "script": script
211
  }
212
 
 
218
  "verified": False,
219
  "script": script,
220
  "consensus": False,
221
+ "tier": "Error Fallback",
222
  "note": "AI serverlaridan javob olishda vaqtinchalik uzilish bo'ldi."
223
  }
224
 
 
246
  "explanation_tip": tip,
247
  "verified": True,
248
  "consensus": True,
249
+ "tier": "Tier 2 (Dual-Agent Consensus)",
250
  "debate_occurred": False,
251
  "script": script
252
  }
 
282
  "explanation_tip": tip,
283
  "verified": True,
284
  "consensus": True,
285
+ "tier": "Tier 2 (Debate Resolved)",
286
  "debate_occurred": True,
287
  "script": script
288
  }
 
316
  "explanation_tip": tip,
317
  "verified": ok1 or ok2,
318
  "consensus": False,
319
+ "tier": "Tier 2 (Best AST Result)",
320
  "debate_occurred": True,
321
  "script": script
322
  }
bot.py CHANGED
@@ -37,6 +37,7 @@ from app.db import (
37
  )
38
  from app.security import analyze_message_threat
39
  from app.voice import transcribe_voice
 
40
  from chat import universal_local_solve
41
 
42
  load_env_file()
@@ -54,6 +55,15 @@ if _env_admin:
54
  # Xato xabari kutayotgan foydalanuvchilar (user_id -> tegishli kontekst)
55
  awaiting_bug_report: dict[int, str] = {}
56
  _bug_report_lock = threading.Lock()
 
 
 
 
 
 
 
 
 
57
  _SUBSCRIPT_MAP = str.maketrans("0123456789nijk", "β‚€β‚β‚‚β‚ƒβ‚„β‚…β‚†β‚‡β‚ˆβ‚‰β‚™α΅’β±Όβ‚–")
58
  _SUPERSCRIPT_MAP = str.maketrans("0123456789n", "⁰¹²³⁴⁡⁢⁷⁸⁹ⁿ")
59
 
@@ -241,6 +251,7 @@ def setup_bot_commands():
241
  try:
242
  commands = [
243
  telebot.types.BotCommand("start", "Botni ishga tushirish"),
 
244
  telebot.types.BotCommand("yangi", "Yangi suhbat (xotirani tozalash)"),
245
  telebot.types.BotCommand("help", "Yordam va imkoniyatlar"),
246
  telebot.types.BotCommand("xato", "Xatolik yoki taklif bildirish"),
@@ -465,6 +476,55 @@ def send_welcome(message):
465
  )
466
  safe_send_reply(message, text)
467
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
468
  def build_solution_keyboard() -> InlineKeyboardMarkup:
469
  kb = InlineKeyboardMarkup(row_width=2)
470
  kb.add(
@@ -473,6 +533,10 @@ def build_solution_keyboard() -> InlineKeyboardMarkup:
473
  )
474
  kb.add(
475
  InlineKeyboardButton("πŸ”„ O'xshash misol", callback_data="similar_problem"),
 
 
 
 
476
  InlineKeyboardButton("🚨 Xato / Taklif", callback_data="report_bug"),
477
  )
478
  return kb
@@ -635,15 +699,22 @@ def process_and_reply(message, existing_wait_msg=None, is_photo=False, is_voice=
635
  add_chat_message(user_id, "assistant", history_assistant_text[:1500])
636
 
637
  # 6. Faqat haqiqiy geometriya masalasida chizma chizib jo'natamiz
 
638
  if javob.get("type", "solve") == "solve" and (javob.get("steps") or javob.get("final_answer")):
639
  diag_path = try_draw_geometry(savol)
640
  if diag_path and os.path.exists(diag_path):
641
  with open(diag_path, "rb") as photo_f:
642
  bot.send_photo(message.chat.id, photo_f, caption="πŸ“ *Geometrik chizma:*", parse_mode="Markdown")
643
- try:
644
- os.unlink(diag_path)
645
- except Exception:
646
- pass
 
 
 
 
 
 
647
 
648
  except Exception as e:
649
  stop_typing.set()
@@ -773,8 +844,147 @@ def handle_inline_callbacks(call):
773
  t.start()
774
  return
775
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
776
  bot.answer_callback_query(call.id)
777
 
 
 
 
 
 
 
 
 
 
 
778
  @bot.message_handler(content_types=['photo'])
779
  def handle_photo(message):
780
  user_id = message.from_user.id
 
37
  )
38
  from app.security import analyze_message_threat
39
  from app.voice import transcribe_voice
40
+ from app.pdf_generator import generate_math_pdf
41
  from chat import universal_local_solve
42
 
43
  load_env_file()
 
55
  # Xato xabari kutayotgan foydalanuvchilar (user_id -> tegishli kontekst)
56
  awaiting_bug_report: dict[int, str] = {}
57
  _bug_report_lock = threading.Lock()
58
+
59
+ # Foydalanuvchining oxirgi yechilgan masalasi (PDF konspekt generatsiyasi uchun)
60
+ _last_user_solutions: dict[int, dict] = {}
61
+ _last_user_solutions_lock = threading.Lock()
62
+
63
+ # Matematik belgilar klaviaturasi sessiyalari (user_id -> joriy ifoda)
64
+ _math_pad_sessions: dict[int, str] = {}
65
+ _math_pad_lock = threading.Lock()
66
+
67
  _SUBSCRIPT_MAP = str.maketrans("0123456789nijk", "β‚€β‚β‚‚β‚ƒβ‚„β‚…β‚†β‚‡β‚ˆβ‚‰β‚™α΅’β±Όβ‚–")
68
  _SUPERSCRIPT_MAP = str.maketrans("0123456789n", "⁰¹²³⁴⁡⁢⁷⁸⁹ⁿ")
69
 
 
251
  try:
252
  commands = [
253
  telebot.types.BotCommand("start", "Botni ishga tushirish"),
254
+ telebot.types.BotCommand("klaviatura", "Matematik klaviatura & belgilar paneli"),
255
  telebot.types.BotCommand("yangi", "Yangi suhbat (xotirani tozalash)"),
256
  telebot.types.BotCommand("help", "Yordam va imkoniyatlar"),
257
  telebot.types.BotCommand("xato", "Xatolik yoki taklif bildirish"),
 
476
  )
477
  safe_send_reply(message, text)
478
 
479
+ def build_math_pad_keyboard() -> InlineKeyboardMarkup:
480
+ """Matematik formulalar va belgilarni terish uchun qulay inline klaviatura paneli."""
481
+ kb = InlineKeyboardMarkup(row_width=5)
482
+ kb.row(
483
+ InlineKeyboardButton("x", callback_data="pad_add_x"),
484
+ InlineKeyboardButton("y", callback_data="pad_add_y"),
485
+ InlineKeyboardButton("+", callback_data="pad_add_+"),
486
+ InlineKeyboardButton("-", callback_data="pad_add_-"),
487
+ InlineKeyboardButton("=", callback_data="pad_add_="),
488
+ )
489
+ kb.row(
490
+ InlineKeyboardButton("xΒ²", callback_data="pad_add_Β²"),
491
+ InlineKeyboardButton("xΒ³", callback_data="pad_add_Β³"),
492
+ InlineKeyboardButton("√", callback_data="pad_add_√("),
493
+ InlineKeyboardButton("Β·", callback_data="pad_add_*"),
494
+ InlineKeyboardButton("/", callback_data="pad_add_/"),
495
+ )
496
+ kb.row(
497
+ InlineKeyboardButton("(", callback_data="pad_add_("),
498
+ InlineKeyboardButton(")", callback_data="pad_add_)"),
499
+ InlineKeyboardButton("^", callback_data="pad_add_^"),
500
+ InlineKeyboardButton("Ο€", callback_data="pad_add_Ο€"),
501
+ InlineKeyboardButton("Β±", callback_data="pad_add_Β±"),
502
+ )
503
+ kb.row(
504
+ InlineKeyboardButton("≀", callback_data="pad_add_≀"),
505
+ InlineKeyboardButton("β‰₯", callback_data="pad_add_β‰₯"),
506
+ InlineKeyboardButton("β‰ ", callback_data="pad_add_β‰ "),
507
+ InlineKeyboardButton("sin", callback_data="pad_add_sin("),
508
+ InlineKeyboardButton("cos", callback_data="pad_add_cos("),
509
+ )
510
+ kb.row(
511
+ InlineKeyboardButton("⌫ O'chirish", callback_data="pad_backspace"),
512
+ InlineKeyboardButton("πŸ—‘ Tozalash", callback_data="pad_clear"),
513
+ )
514
+ kb.row(
515
+ InlineKeyboardButton("πŸš€ Masalani Yechish", callback_data="pad_solve"),
516
+ InlineKeyboardButton("❌ Yopish", callback_data="pad_close"),
517
+ )
518
+ return kb
519
+
520
+ def get_math_pad_text(formula: str) -> str:
521
+ display_f = formula if formula else "_(hali belgilar terilmadi)_"
522
+ return (
523
+ "πŸ”’ <b>Matematik Belgilar & Formula Paneli:</b>\n\n"
524
+ f"πŸ“ <b>Joriy ifoda:</b> <code>{html.escape(display_f)}</code>\n\n"
525
+ "<i>Quyidagi tugmalar orqali formulangizni shakllantiring va <b>Β«πŸš€ Masalani YechishΒ»</b> tugmasini bosing:</i>"
526
+ )
527
+
528
  def build_solution_keyboard() -> InlineKeyboardMarkup:
529
  kb = InlineKeyboardMarkup(row_width=2)
530
  kb.add(
 
533
  )
534
  kb.add(
535
  InlineKeyboardButton("πŸ”„ O'xshash misol", callback_data="similar_problem"),
536
+ InlineKeyboardButton("πŸ“₯ PDF Konspekt", callback_data="get_pdf_solution"),
537
+ )
538
+ kb.add(
539
+ InlineKeyboardButton("πŸ”’ Matematik Belgilar", callback_data="open_math_pad"),
540
  InlineKeyboardButton("🚨 Xato / Taklif", callback_data="report_bug"),
541
  )
542
  return kb
 
699
  add_chat_message(user_id, "assistant", history_assistant_text[:1500])
700
 
701
  # 6. Faqat haqiqiy geometriya masalasida chizma chizib jo'natamiz
702
+ saved_diag = None
703
  if javob.get("type", "solve") == "solve" and (javob.get("steps") or javob.get("final_answer")):
704
  diag_path = try_draw_geometry(savol)
705
  if diag_path and os.path.exists(diag_path):
706
  with open(diag_path, "rb") as photo_f:
707
  bot.send_photo(message.chat.id, photo_f, caption="πŸ“ *Geometrik chizma:*", parse_mode="Markdown")
708
+ saved_diag = diag_path
709
+
710
+ # 7. PDF konspekt generatsiyasi uchun so'nggi yechimni xotirada saqlaymiz
711
+ if javob.get("type", "solve") == "solve":
712
+ with _last_user_solutions_lock:
713
+ _last_user_solutions[user_id] = {
714
+ "question": savol,
715
+ "solution": javob,
716
+ "diagram_path": saved_diag
717
+ }
718
 
719
  except Exception as e:
720
  stop_typing.set()
 
844
  t.start()
845
  return
846
 
847
+ if data == "get_pdf_solution":
848
+ with _last_user_solutions_lock:
849
+ last_info = _last_user_solutions.get(user_id)
850
+ if not last_info:
851
+ bot.answer_callback_query(call.id, "Avval biror masala yuboring, shunda konspekt tayyorlayman!", show_alert=True)
852
+ return
853
+ bot.answer_callback_query(call.id, "πŸ“„ A4 PDF konspekt shakllantirilmoqda...")
854
+ def _send_pdf_worker():
855
+ try:
856
+ q = last_info["question"]
857
+ sol = last_info["solution"]
858
+ diag = last_info.get("diagram_path")
859
+ if not diag or not os.path.exists(diag):
860
+ diag = try_draw_geometry(q)
861
+ pdf_path = generate_math_pdf(q, sol, diag)
862
+ if pdf_path and os.path.exists(pdf_path):
863
+ with open(pdf_path, "rb") as pdf_file:
864
+ bot.send_document(
865
+ msg.chat.id,
866
+ pdf_file,
867
+ caption="πŸ“„ <b>Sincc.on: Ushbu masalaning A4 PDF Konspekti</b>\n"
868
+ "<i>Chop etish va darsda/imtihonda foydalanish uchun to'liq yechim va chizma.</i>",
869
+ parse_mode="HTML"
870
+ )
871
+ try:
872
+ os.unlink(pdf_path)
873
+ except Exception:
874
+ pass
875
+ except Exception as e_pdf:
876
+ print(f"[PDF Telegram xatosi]: {e_pdf}")
877
+ bot.send_message(msg.chat.id, f"❌ PDF konspekt yaratishda xatolik: {e_pdf}")
878
+ threading.Thread(target=_send_pdf_worker, daemon=True).start()
879
+ return
880
+
881
+ if data == "open_math_pad":
882
+ bot.answer_callback_query(call.id, "Matematik klaviatura ochilmoqda...")
883
+ with _math_pad_lock:
884
+ _math_pad_sessions[user_id] = ""
885
+ kb = build_math_pad_keyboard()
886
+ txt = get_math_pad_text("")
887
+ bot.send_message(msg.chat.id, txt, parse_mode="HTML", reply_markup=kb)
888
+ return
889
+
890
+ if data.startswith("pad_add_"):
891
+ sym = data[8:]
892
+ with _math_pad_lock:
893
+ curr = _math_pad_sessions.get(user_id, "")
894
+ if len(curr) < 150:
895
+ curr += sym
896
+ _math_pad_sessions[user_id] = curr
897
+ bot.answer_callback_query(call.id)
898
+ kb = build_math_pad_keyboard()
899
+ txt = get_math_pad_text(curr)
900
+ try:
901
+ bot.edit_message_text(txt, chat_id=msg.chat.id, message_id=msg.message_id, parse_mode="HTML", reply_markup=kb)
902
+ except Exception:
903
+ pass
904
+ return
905
+
906
+ if data == "pad_backspace":
907
+ with _math_pad_lock:
908
+ curr = _math_pad_sessions.get(user_id, "")
909
+ if curr:
910
+ for prefix in ("sin(", "cos(", "tan(", "log(", "ln(", "√("):
911
+ if curr.endswith(prefix):
912
+ curr = curr[:-len(prefix)]
913
+ break
914
+ else:
915
+ curr = curr[:-1]
916
+ _math_pad_sessions[user_id] = curr
917
+ bot.answer_callback_query(call.id)
918
+ kb = build_math_pad_keyboard()
919
+ txt = get_math_pad_text(curr)
920
+ try:
921
+ bot.edit_message_text(txt, chat_id=msg.chat.id, message_id=msg.message_id, parse_mode="HTML", reply_markup=kb)
922
+ except Exception:
923
+ pass
924
+ return
925
+
926
+ if data == "pad_clear":
927
+ with _math_pad_lock:
928
+ _math_pad_sessions[user_id] = ""
929
+ bot.answer_callback_query(call.id, "Formula tozalandi")
930
+ kb = build_math_pad_keyboard()
931
+ txt = get_math_pad_text("")
932
+ try:
933
+ bot.edit_message_text(txt, chat_id=msg.chat.id, message_id=msg.message_id, parse_mode="HTML", reply_markup=kb)
934
+ except Exception:
935
+ pass
936
+ return
937
+
938
+ if data == "pad_close":
939
+ bot.answer_callback_query(call.id, "Klaviatura yopildi")
940
+ try:
941
+ bot.delete_message(msg.chat.id, msg.message_id)
942
+ except Exception:
943
+ try:
944
+ bot.edit_message_text("πŸ”’ <i>Matematik klaviatura yopildi.</i>", chat_id=msg.chat.id, message_id=msg.message_id, parse_mode="HTML")
945
+ except Exception:
946
+ pass
947
+ return
948
+
949
+ if data == "pad_solve":
950
+ with _math_pad_lock:
951
+ formula = _math_pad_sessions.get(user_id, "").strip()
952
+ if not formula:
953
+ bot.answer_callback_query(call.id, "Formula bo'sh! Avval tugmalarni bosib ifoda tering.", show_alert=True)
954
+ return
955
+ bot.answer_callback_query(call.id, "Masala yechishga yuborilmoqda! πŸš€")
956
+ try:
957
+ bot.edit_message_text(
958
+ f"πŸš€ <b>Hisoblanmoqda:</b> <code>{html.escape(formula)}</code>",
959
+ chat_id=msg.chat.id,
960
+ message_id=msg.message_id,
961
+ parse_mode="HTML"
962
+ )
963
+ except Exception:
964
+ pass
965
+ t = threading.Thread(
966
+ target=process_and_reply,
967
+ kwargs={
968
+ "message": msg,
969
+ "override_prompt": formula,
970
+ "actor_user": call.from_user,
971
+ }
972
+ )
973
+ t.start()
974
+ return
975
+
976
  bot.answer_callback_query(call.id)
977
 
978
+ @bot.message_handler(commands=['klaviatura', 'belgilar', 'formula', 'pad'])
979
+ def math_pad_command(message):
980
+ user_id = message.from_user.id
981
+ record_user_activity(user_id, message.from_user.username, message.from_user.first_name)
982
+ with _math_pad_lock:
983
+ _math_pad_sessions[user_id] = ""
984
+ kb = build_math_pad_keyboard()
985
+ txt = get_math_pad_text("")
986
+ safe_send_reply(message, txt, reply_markup=kb, parse_mode="HTML")
987
+
988
  @bot.message_handler(content_types=['photo'])
989
  def handle_photo(message):
990
  user_id = message.from_user.id
requirements.txt CHANGED
@@ -8,3 +8,4 @@ fastapi>=0.100.0
8
  uvicorn>=0.23.0
9
  pydantic>=2.0.0
10
  python-dotenv>=1.0.0
 
 
8
  uvicorn>=0.23.0
9
  pydantic>=2.0.0
10
  python-dotenv>=1.0.0
11
+ reportlab>=4.0.0