j-js commited on
Commit
a20203f
·
verified ·
1 Parent(s): 2f692e3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -1056
app.py CHANGED
@@ -1,1068 +1,143 @@
1
- # app.py
2
- # GMAT Solver v2
3
- # Hybrid FastAPI app for a Unity trading-game study AI.
4
- # - Keeps the existing /chat schema: {message, chat_history, tone, verbosity, transparency}
5
- # - Uses rule-based / symbolic solving for GMAT-style quantitative prompts
6
- # - Gives hints vs answers depending on user request + slider settings
7
- # - Includes a simple browser test UI at "/"
8
-
9
- from fastapi import FastAPI
10
- from fastapi.responses import HTMLResponse
11
- from pydantic import BaseModel, Field
12
- from typing import List, Optional, Dict, Any, Tuple
13
- import math
14
- import statistics
15
- import re
16
- import html
17
- import ast
18
- import operator as op
19
-
20
- try:
21
- import sympy as sp
22
- SYMPY_AVAILABLE = True
23
- except Exception:
24
- SYMPY_AVAILABLE = False
25
-
26
-
27
- app = FastAPI(title="GMAT Solver v2")
28
-
29
-
30
- # =========================
31
- # Models
32
- # =========================
33
-
34
- class ChatMessage(BaseModel):
35
- role: str
36
- text: str
37
-
38
-
39
- class ChatRequest(BaseModel):
40
- message: str
41
- chat_history: List[ChatMessage] = Field(default_factory=list)
42
- tone: float = 0.5
43
- verbosity: float = 0.5
44
- transparency: float = 0.5
45
-
46
-
47
- class ChatResponse(BaseModel):
48
- reply: str
49
- meta: Optional[Dict[str, Any]] = None
50
-
51
-
52
- # =========================
53
- # Safe arithmetic evaluator
54
- # =========================
55
-
56
- _ALLOWED_OPERATORS = {
57
- ast.Add: op.add,
58
- ast.Sub: op.sub,
59
- ast.Mult: op.mul,
60
- ast.Div: op.truediv,
61
- ast.Pow: op.pow,
62
- ast.USub: op.neg,
63
- ast.Mod: op.mod,
64
- }
65
-
66
- _ALLOWED_FUNCS = {
67
- "sqrt": math.sqrt,
68
- "abs": abs,
69
- "ceil": math.ceil,
70
- "floor": math.floor,
71
- "log10": math.log10,
72
- }
73
-
74
- _ALLOWED_CONSTS = {
75
- "pi": math.pi,
76
- "e": math.e,
77
- }
78
-
79
-
80
- def safe_eval(expr: str) -> Optional[float]:
81
- expr = expr.replace("^", "**")
82
-
83
- def _eval(node):
84
- if isinstance(node, ast.Constant): # py3.8+
85
- if isinstance(node.value, (int, float)):
86
- return node.value
87
- raise ValueError("Invalid constant")
88
- elif isinstance(node, ast.Num): # fallback
89
- return node.n
90
- elif isinstance(node, ast.BinOp):
91
- if type(node.op) not in _ALLOWED_OPERATORS:
92
- raise ValueError("Operator not allowed")
93
- return _ALLOWED_OPERATORS[type(node.op)](_eval(node.left), _eval(node.right))
94
- elif isinstance(node, ast.UnaryOp):
95
- if type(node.op) not in _ALLOWED_OPERATORS:
96
- raise ValueError("Unary operator not allowed")
97
- return _ALLOWED_OPERATORS[type(node.op)](_eval(node.operand))
98
- elif isinstance(node, ast.Call):
99
- if not isinstance(node.func, ast.Name):
100
- raise ValueError("Invalid call")
101
- fname = node.func.id
102
- if fname not in _ALLOWED_FUNCS:
103
- raise ValueError("Function not allowed")
104
- args = [_eval(a) for a in node.args]
105
- return _ALLOWED_FUNCS[fname](*args)
106
- elif isinstance(node, ast.Name):
107
- if node.id in _ALLOWED_CONSTS:
108
- return _ALLOWED_CONSTS[node.id]
109
- raise ValueError("Name not allowed")
110
- raise ValueError("Unsupported expression")
111
-
112
- try:
113
- tree = ast.parse(expr, mode="eval")
114
- value = _eval(tree.body)
115
- return float(value)
116
- except Exception:
117
- return None
118
-
119
-
120
- # =========================
121
- # Text helpers
122
- # =========================
123
-
124
- def clamp(v: float, lo: float, hi: float) -> float:
125
- return max(lo, min(hi, v))
126
-
127
-
128
- def normalize_text(s: str) -> str:
129
- s = s.replace("\r\n", "\n")
130
- s = s.replace("—", "-").replace("–", "-")
131
- s = re.sub(r"[ \t]+", " ", s)
132
- return s.strip()
133
-
134
-
135
- def lower_clean(s: str) -> str:
136
- return normalize_text(s).lower()
137
-
138
-
139
- def last_n_messages(history: List[ChatMessage], n: int = 8) -> str:
140
- parts = []
141
- for m in history[-n:]:
142
- parts.append(f"{m.role.upper()}: {m.text}")
143
- return "\n".join(parts)
144
-
145
-
146
- def extract_options(text: str) -> List[Tuple[str, str]]:
147
- # Supports:
148
- # A) 12
149
- # A. 12
150
- # (A) 12
151
- # A 12
152
- pattern = re.compile(
153
- r'(?mi)^\s*(?:\(?([A-E])\)|([A-E])[.)]?)[ \t]+(.+?)\s*$'
154
- )
155
- found = []
156
- for line in text.splitlines():
157
- m = pattern.match(line.strip())
158
- if m:
159
- letter = m.group(1) or m.group(2)
160
- value = m.group(3).strip()
161
- found.append((letter.upper(), value))
162
- return found
163
-
164
-
165
- def strip_options(text: str) -> str:
166
- lines = text.splitlines()
167
- kept = []
168
- opt_pat = re.compile(r'(?mi)^\s*(?:\(?[A-E]\)|[A-E][.)]?)[ \t]+.+$')
169
- for line in lines:
170
- if not opt_pat.match(line.strip()):
171
- kept.append(line)
172
- return "\n".join(kept).strip()
173
-
174
-
175
- def contains_math_signal(text: str) -> bool:
176
- signals = [
177
- "+", "-", "*", "/", "%", "percent", "ratio", "average", "mean", "median",
178
- "integer", "divisible", "probability", "permutation", "combination",
179
- "solve", "equation", "inequality", "x", "y", "algebra", "geometry",
180
- "triangle", "circle", "rectangle", "table", "chart", "graph", "data"
181
- ]
182
- t = lower_clean(text)
183
- return any(s in t for s in signals)
184
-
185
-
186
- def contains_verbal_signal(text: str) -> bool:
187
- signals = [
188
- "argument", "assumption", "strengthen", "weaken", "inference",
189
- "main idea", "tone", "passage", "sentence correction", "grammar",
190
- "which of the following", "best completes", "critical reasoning",
191
- "reading comprehension"
192
- ]
193
- t = lower_clean(text)
194
- return any(s in t for s in signals)
195
-
196
-
197
- def asks_for_final_answer(text: str) -> bool:
198
- t = lower_clean(text)
199
- patterns = [
200
- "just give me the answer",
201
- "give me the answer",
202
- "what is the answer",
203
- "which option",
204
- "which answer",
205
- "tell me the answer",
206
- "final answer",
207
- "correct answer",
208
- "pick the answer",
209
- "just answer it",
210
- ]
211
- return any(p in t for p in patterns)
212
-
213
-
214
- def asks_for_hint(text: str) -> bool:
215
- t = lower_clean(text)
216
- patterns = [
217
- "hint", "nudge", "don't tell me", "do not tell me", "guide me",
218
- "help me solve", "walk me through", "step by step", "how do i solve"
219
- ]
220
- return any(p in t for p in patterns)
221
-
222
-
223
- def numeric_from_text(s: str) -> Optional[float]:
224
- s = s.strip()
225
- s = s.replace(",", "")
226
- s = s.replace("%", "")
227
- if re.fullmatch(r'-?\d+(\.\d+)?', s):
228
- return float(s)
229
- val = safe_eval(s)
230
- return val
231
-
232
-
233
- # =========================
234
- # Solver core
235
- # =========================
236
-
237
- class SolveResult(BaseModel):
238
- solved: bool = False
239
- answer_letter: Optional[str] = None
240
- answer_value: Optional[str] = None
241
- confidence: float = 0.0
242
- method: str = ""
243
- reasoning: List[str] = Field(default_factory=list)
244
- caution: Optional[str] = None
245
-
246
-
247
- def solve_direct_expression(text: str) -> Optional[SolveResult]:
248
- # Example: "What is 18*(4+2)/3 ?"
249
- expr_match = re.search(r'(?i)(?:what is|compute|calculate|evaluate)\s+([0-9\.\+\-\*\/\^\(\)\s]+)\??', text)
250
- if not expr_match:
251
- return None
252
-
253
- expr = expr_match.group(1).strip()
254
- value = safe_eval(expr)
255
- if value is None:
256
- return None
257
-
258
- return SolveResult(
259
- solved=True,
260
- answer_value=format_number(value),
261
- confidence=0.9,
262
- method="direct arithmetic",
263
- reasoning=[f"Evaluate the expression {expr}.", f"The result is {format_number(value)}."]
264
- )
265
-
266
-
267
- def solve_percent_problem(text: str) -> Optional[SolveResult]:
268
- t = lower_clean(text)
269
-
270
- # Pattern: increased by x% from a to ?
271
- m = re.search(r'(\d+(?:\.\d+)?)\s*(?:increased|increase|rose|rises|grows|grew)\s+by\s+(\d+(?:\.\d+)?)\s*%', t)
272
- if m:
273
- start = float(m.group(1))
274
- pct = float(m.group(2))
275
- result = start * (1 + pct / 100.0)
276
- return SolveResult(
277
- solved=True,
278
- answer_value=format_number(result),
279
- confidence=0.8,
280
- method="percent increase",
281
- reasoning=[
282
- f"Start with {format_number(start)}.",
283
- f"Increase by {pct}%, so multiply by 1 + {pct}/100 = {1 + pct/100:.4f}.",
284
- f"Result = {format_number(result)}."
285
- ]
286
- )
287
-
288
- # Pattern: what percent of A is B
289
- m = re.search(r'what percent of\s+(\d+(?:\.\d+)?)\s+is\s+(\d+(?:\.\d+)?)', t)
290
- if m:
291
- a = float(m.group(1))
292
- b = float(m.group(2))
293
- if a != 0:
294
- result = (b / a) * 100
295
- return SolveResult(
296
- solved=True,
297
- answer_value=format_number(result) + "%",
298
- confidence=0.85,
299
- method="percent comparison",
300
- reasoning=[
301
- f"Percent = part / whole × 100 = {b}/{a} × 100.",
302
- f"Result = {format_number(result)}%."
303
- ]
304
- )
305
-
306
- return None
307
-
308
-
309
- def solve_ratio_total(text: str) -> Optional[SolveResult]:
310
- # Pattern: ratio a:b and total t
311
- t = lower_clean(text)
312
- m = re.search(
313
- r'ratio of [a-z ]*?(\d+)\s*:\s*(\d+).*?total(?: is| of)?\s*(\d+(?:\.\d+)?)',
314
- t
315
- )
316
- if not m:
317
- m = re.search(
318
- r'(\d+)\s*:\s*(\d+).*?total(?: is| of)?\s*(\d+(?:\.\d+)?)',
319
- t
320
- )
321
- if not m:
322
- return None
323
-
324
- a = float(m.group(1))
325
- b = float(m.group(2))
326
- total = float(m.group(3))
327
- unit = total / (a + b)
328
- x = a * unit
329
- y = b * unit
330
-
331
- return SolveResult(
332
- solved=True,
333
- answer_value=f"{format_number(x)} and {format_number(y)}",
334
- confidence=0.75,
335
- method="ratio split",
336
- reasoning=[
337
- f"Total parts = {a} + {b} = {a+b}.",
338
- f"Each part = {format_number(total)}/{a+b} = {unit:.4f}.",
339
- f"The two quantities are {format_number(x)} and {format_number(y)}."
340
- ]
341
- )
342
-
343
-
344
- def solve_average_problem(text: str) -> Optional[SolveResult]:
345
- t = lower_clean(text)
346
-
347
- nums = [float(x) for x in re.findall(r'-?\d+(?:\.\d+)?', t)]
348
-
349
- if "average" in t or "mean" in t:
350
- # Simple: average of 2, 4, 6
351
- if re.search(r'(average|mean) of', t) and len(nums) >= 2:
352
- result = sum(nums) / len(nums)
353
- return SolveResult(
354
- solved=True,
355
- answer_value=format_number(result),
356
- confidence=0.6,
357
- method="mean",
358
- reasoning=[
359
- f"Add the numbers: {format_number(sum(nums))}.",
360
- f"Divide by how many numbers there are: {len(nums)}.",
361
- f"Mean = {format_number(result)}."
362
- ]
363
- )
364
-
365
- if "median" in t and len(nums) >= 2:
366
- result = statistics.median(nums)
367
- return SolveResult(
368
- solved=True,
369
- answer_value=format_number(result),
370
- confidence=0.6,
371
- method="median",
372
- reasoning=[f"Sort the numbers and take the middle value(s). Median = {format_number(result)}."]
373
- )
374
-
375
- if "range" in t and len(nums) >= 2:
376
- result = max(nums) - min(nums)
377
- return SolveResult(
378
- solved=True,
379
- answer_value=format_number(result),
380
- confidence=0.6,
381
- method="range",
382
- reasoning=[f"Range = max - min = {max(nums)} - {min(nums)} = {format_number(result)}."]
383
- )
384
-
385
- return None
386
-
387
-
388
- def solve_probability_problem(text: str) -> Optional[SolveResult]:
389
- t = lower_clean(text)
390
-
391
- # Simple deck example
392
- if "probability" in t and "out of" in t:
393
- m = re.search(r'probability.*?(\d+)\s+out of\s+(\d+)', t)
394
- if m:
395
- a = float(m.group(1))
396
- b = float(m.group(2))
397
- if b != 0:
398
- p = a / b
399
- return SolveResult(
400
- solved=True,
401
- answer_value=format_fraction_or_decimal(p),
402
- confidence=0.6,
403
- method="basic probability",
404
- reasoning=[
405
- f"Probability = favorable / total = {int(a)}/{int(b)}.",
406
- f"That is {format_fraction_or_decimal(p)}."
407
- ]
408
- )
409
-
410
- # "If a bag has 3 red and 2 blue..."
411
- if "probability" in t and ("red" in t or "blue" in t or "green" in t):
412
- counts = [int(x) for x in re.findall(r'\b\d+\b', t)]
413
- if len(counts) >= 2:
414
- total = sum(counts)
415
- fav = counts[0]
416
- p = fav / total if total else None
417
- if p is not None:
418
- return SolveResult(
419
- solved=True,
420
- answer_value=format_fraction_or_decimal(p),
421
- confidence=0.45,
422
- method="basic probability heuristic",
423
- reasoning=[
424
- f"Treat the first quantity as favorable: {fav}.",
425
- f"Total items = {total}.",
426
- f"Probability = {fav}/{total} = {format_fraction_or_decimal(p)}."
427
- ],
428
- caution="This probability result used a heuristic pattern. Check the wording carefully."
429
- )
430
-
431
- return None
432
-
433
-
434
- def solve_algebra_with_sympy(text: str) -> Optional[SolveResult]:
435
- if not SYMPY_AVAILABLE:
436
- return None
437
-
438
- raw = normalize_text(text)
439
- lc = raw.lower()
440
-
441
- # Detect equations with x or y
442
- if not re.search(r'\b[x-y]\b', lc):
443
- return None
444
-
445
- # Common ask: solve for x
446
- target_var = "x"
447
- m_target = re.search(r'solve for\s+([a-z])', lc)
448
- if m_target:
449
- target_var = m_target.group(1)
450
-
451
- # Extract equations like:
452
- # x + y = 10
453
- # 2x - y = 4
454
- eq_lines = []
455
- for line in raw.splitlines():
456
- if "=" in line and re.search(r'[a-zA-Z]', line):
457
- eq_lines.append(line.strip())
458
-
459
- # Also try sentence-level extraction
460
- if not eq_lines:
461
- eq_lines = re.findall(r'([A-Za-z0-9\+\-\*/\^\(\) ]+=[A-Za-z0-9\+\-\*/\^\(\) ]+)', raw)
462
-
463
- if not eq_lines:
464
- return None
465
-
466
- try:
467
- symbol_names = sorted(set(re.findall(r'\b[a-z]\b', lc)))
468
- if not symbol_names:
469
- symbol_names = ["x"]
470
-
471
- symbols = {name: sp.symbols(name) for name in symbol_names}
472
-
473
- equations = []
474
- for eq in eq_lines:
475
- left, right = eq.split("=", 1)
476
- left = sympify_loose(left, symbols)
477
- right = sympify_loose(right, symbols)
478
- equations.append(sp.Eq(left, right))
479
-
480
- vars_to_solve = list(symbols.values())
481
- sol = sp.solve(equations, vars_to_solve, dict=True)
482
-
483
- if not sol:
484
- return None
485
-
486
- sol0 = sol[0]
487
- if target_var in symbols and symbols[target_var] in sol0:
488
- ans = sol0[symbols[target_var]]
489
- return SolveResult(
490
- solved=True,
491
- answer_value=str(ans),
492
- confidence=0.85,
493
- method="symbolic algebra",
494
- reasoning=[
495
- f"Translate the given relationship(s) into equation form.",
496
- f"Solve the system symbolically.",
497
- f"{target_var} = {ans}."
498
- ]
499
- )
500
-
501
- # fallback: show full solution
502
- parts = [f"{str(k)} = {str(v)}" for k, v in sol0.items()]
503
- return SolveResult(
504
- solved=True,
505
- answer_value=", ".join(parts),
506
- confidence=0.75,
507
- method="symbolic algebra",
508
- reasoning=[
509
- "Translate the relationships into equations.",
510
- "Solve the system symbolically.",
511
- "Solution: " + ", ".join(parts)
512
- ]
513
- )
514
-
515
- except Exception:
516
- return None
517
-
518
-
519
- def sympify_loose(expr: str, symbols: Dict[str, Any]):
520
- expr = expr.replace("^", "**")
521
- expr = re.sub(r'(\d)([a-zA-Z])', r'\1*\2', expr) # 2x -> 2*x
522
- expr = re.sub(r'([a-zA-Z])(\d)', r'\1*\2', expr) # x2 -> x*2
523
- expr = re.sub(r'([a-zA-Z])\(', r'\1*(', expr) # x(y+1) -> x*(y+1)
524
- return sp.sympify(expr, locals=symbols)
525
-
526
-
527
- def solve_geometry_heuristic(text: str) -> Optional[SolveResult]:
528
- t = lower_clean(text)
529
-
530
- # Rectangle area
531
- if "rectangle" in t and "area" in t:
532
- nums = [float(x) for x in re.findall(r'\d+(?:\.\d+)?', t)]
533
- if len(nums) >= 2:
534
- area = nums[0] * nums[1]
535
- return SolveResult(
536
- solved=True,
537
- answer_value=format_number(area),
538
- confidence=0.55,
539
- method="rectangle area",
540
- reasoning=[f"Area of rectangle = length × width = {nums[0]} × {nums[1]} = {format_number(area)}."]
541
- )
542
-
543
- # Triangle area
544
- if "triangle" in t and "area" in t:
545
- nums = [float(x) for x in re.findall(r'\d+(?:\.\d+)?', t)]
546
- if len(nums) >= 2:
547
- area = 0.5 * nums[0] * nums[1]
548
- return SolveResult(
549
- solved=True,
550
- answer_value=format_number(area),
551
- confidence=0.5,
552
- method="triangle area",
553
- reasoning=[f"Area of triangle = 1/2 × base × height = 1/2 × {nums[0]} × {nums[1]} = {format_number(area)}."]
554
- )
555
-
556
- # Circle circumference / area
557
- if "circle" in t:
558
- nums = [float(x) for x in re.findall(r'\d+(?:\.\d+)?', t)]
559
- if "radius" in t and nums:
560
- r = nums[0]
561
- if "circumference" in t:
562
- c = 2 * math.pi * r
563
- return SolveResult(
564
- solved=True,
565
- answer_value=f"{format_number(c)}",
566
- confidence=0.6,
567
- method="circle circumference",
568
- reasoning=[f"Circumference = 2πr = 2π({r}) = {format_number(c)}."]
569
- )
570
- if "area" in t:
571
- a = math.pi * r * r
572
- return SolveResult(
573
- solved=True,
574
- answer_value=f"{format_number(a)}",
575
- confidence=0.6,
576
- method="circle area",
577
- reasoning=[f"Area = πr² = π({r}²) = {format_number(a)}."]
578
- )
579
-
580
- return None
581
-
582
-
583
- def solve_option_match(text: str, options: List[Tuple[str, str]]) -> Optional[SolveResult]:
584
- if not options:
585
- return None
586
-
587
- # If prompt is basically a direct computation, compute and match.
588
- direct = solve_direct_expression(text)
589
- if direct and direct.answer_value is not None:
590
- val = numeric_from_text(direct.answer_value)
591
- if val is not None:
592
- letter = find_matching_option(val, options)
593
- if letter:
594
- direct.answer_letter = letter
595
- direct.confidence = max(direct.confidence, 0.95)
596
- direct.reasoning.append(f"That matches option {letter}.")
597
- return direct
598
-
599
- # Try percent / average / ratio / geometry / algebra / probability
600
- candidates = [
601
- solve_percent_problem(text),
602
- solve_ratio_total(text),
603
- solve_average_problem(text),
604
- solve_probability_problem(text),
605
- solve_algebra_with_sympy(text),
606
- solve_geometry_heuristic(text),
607
- ]
608
- candidates = [c for c in candidates if c and c.answer_value]
609
-
610
- for cand in candidates:
611
- val = numeric_from_text(str(cand.answer_value).replace("%", ""))
612
- if val is None:
613
- continue
614
-
615
- # For percentages, compare to options containing %
616
- if "%" in str(cand.answer_value):
617
- letter = find_matching_option(val, options, percent_mode=True)
618
- else:
619
- letter = find_matching_option(val, options)
620
-
621
- if letter:
622
- cand.answer_letter = letter
623
- cand.reasoning.append(f"That matches option {letter}.")
624
- cand.confidence = max(cand.confidence, 0.9)
625
- return cand
626
-
627
- return None
628
-
629
-
630
- def find_matching_option(value: float, options: List[Tuple[str, str]], percent_mode: bool = False) -> Optional[str]:
631
- for letter, raw in options:
632
- raw_clean = raw.strip()
633
- if percent_mode:
634
- raw_num = numeric_from_text(raw_clean.replace("%", ""))
635
- else:
636
- raw_num = numeric_from_text(raw_clean)
637
- if raw_num is None:
638
- continue
639
- if abs(raw_num - value) < 1e-6:
640
- return letter
641
- return None
642
-
643
-
644
- def solve_quant(text: str, options: List[Tuple[str, str]]) -> Optional[SolveResult]:
645
- solvers = [
646
- solve_option_match,
647
- lambda t, o: solve_direct_expression(t),
648
- lambda t, o: solve_percent_problem(t),
649
- lambda t, o: solve_ratio_total(t),
650
- lambda t, o: solve_average_problem(t),
651
- lambda t, o: solve_probability_problem(t),
652
- lambda t, o: solve_algebra_with_sympy(t),
653
- lambda t, o: solve_geometry_heuristic(t),
654
- ]
655
-
656
- for solver in solvers:
657
- try:
658
- result = solver(text, options)
659
- if result and result.solved:
660
- return result
661
- except Exception:
662
- continue
663
- return None
664
-
665
-
666
- def solve_verbal_strategy(text: str, options: List[Tuple[str, str]]) -> SolveResult:
667
- t = lower_clean(text)
668
-
669
- reasoning = []
670
- method = "verbal strategy"
671
-
672
- if "strengthen" in t:
673
- reasoning = [
674
- "Find the conclusion and the main assumption.",
675
- "Choose the option that makes the conclusion more likely by supporting that assumption."
676
- ]
677
- elif "weaken" in t:
678
- reasoning = [
679
- "Find the conclusion and the assumption it depends on.",
680
- "Choose the option that attacks that assumption or offers an alternative explanation."
681
- ]
682
- elif "assumption" in t:
683
- reasoning = [
684
- "Identify the gap between evidence and conclusion.",
685
- "The correct answer is something the argument needs in order to work."
686
- ]
687
- elif "inference" in t:
688
- reasoning = [
689
- "Pick the option that must be true based only on the passage.",
690
- "Avoid answers that are plausible but not guaranteed."
691
- ]
692
- elif "sentence correction" in t or "grammar" in t:
693
- reasoning = [
694
- "Check grammar, meaning, concision, and parallel structure.",
695
- "Eliminate answers that change the intended meaning or introduce agreement errors."
696
- ]
697
- else:
698
- reasoning = [
699
- "Identify what the question type is asking for.",
700
- "Eliminate answers that are too extreme, off-scope, or unsupported."
701
- ]
702
-
703
- return SolveResult(
704
- solved=False,
705
- confidence=0.35,
706
- method=method,
707
- reasoning=reasoning,
708
- caution="Verbal reasoning is currently strategy-first. Quant/Data Insight is much stronger in this version."
709
- )
710
-
711
-
712
- # =========================
713
- # Response shaping
714
- # =========================
715
-
716
- def format_number(x: float) -> str:
717
- if abs(x - round(x)) < 1e-9:
718
- return str(int(round(x)))
719
- return f"{x:.6f}".rstrip("0").rstrip(".")
720
-
721
-
722
- def format_fraction_or_decimal(x: float) -> str:
723
- if x == 0:
724
- return "0"
725
- # Try simple fraction
726
- for d in range(2, 21):
727
- n = x * d
728
- if abs(n - round(n)) < 1e-9:
729
- return f"{int(round(n))}/{d}"
730
- return format_number(x)
731
-
732
-
733
- def build_style(tone: float, verbosity: float, transparency: float) -> Dict[str, Any]:
734
- tone = clamp(tone, 0.0, 1.0)
735
- verbosity = clamp(verbosity, 0.0, 1.0)
736
- transparency = clamp(transparency, 0.0, 1.0)
737
-
738
- if tone < 0.33:
739
- tone_prefix = "Let's keep it focused."
740
- elif tone < 0.66:
741
- tone_prefix = "Let's work through it."
742
- else:
743
- tone_prefix = "You've got this — let's break it down."
744
-
745
- if verbosity < 0.34:
746
- detail = "short"
747
- elif verbosity < 0.67:
748
- detail = "medium"
749
- else:
750
- detail = "long"
751
-
752
- show_steps = transparency >= 0.45
753
-
754
- return {
755
- "tone_prefix": tone_prefix,
756
- "detail": detail,
757
- "show_steps": show_steps,
758
- }
759
-
760
-
761
- def decide_help_mode(req: ChatRequest) -> str:
762
- msg = lower_clean(req.message)
763
-
764
- if asks_for_hint(msg):
765
- return "hint"
766
-
767
- if asks_for_final_answer(msg):
768
- return "answer"
769
-
770
- # Slider-based behavior:
771
- # low transparency = nudge / medium = guided / high = explicit
772
- if req.transparency >= 0.8:
773
- return "answer"
774
- if req.transparency <= 0.25:
775
- return "hint"
776
- return "guided"
777
-
778
-
779
- def compose_quant_reply(
780
- req: ChatRequest,
781
- result: SolveResult,
782
- help_mode: str,
783
- style: Dict[str, Any],
784
- options: List[Tuple[str, str]]
785
- ) -> str:
786
- prefix = style["tone_prefix"]
787
-
788
- short = style["detail"] == "short"
789
- long = style["detail"] == "long"
790
-
791
- lines = [prefix]
792
-
793
- if help_mode == "hint":
794
- lines.append("Hint:")
795
- if result.reasoning:
796
- lines.append(result.reasoning[0])
797
- if len(result.reasoning) > 1 and not short:
798
- lines.append(result.reasoning[1])
799
- if options:
800
- lines.append("Try comparing your result with the answer choices before locking in your choice.")
801
- return "\n".join(lines)
802
-
803
- if help_mode == "guided":
804
- lines.append(f"I think the method is **{result.method}**.")
805
- if style["show_steps"]:
806
- steps = result.reasoning[:2] if short else result.reasoning[:]
807
- lines.extend([f"- {s}" for s in steps])
808
-
809
- if result.answer_letter and result.answer_value:
810
- if long:
811
- lines.append(f"So the value is **{result.answer_value}**, which matches **option {result.answer_letter}**.")
812
- else:
813
- lines.append(f"I get **{result.answer_value}** → **{result.answer_letter}**.")
814
- elif result.answer_value:
815
- lines.append(f"I get **{result.answer_value}**.")
816
-
817
- if result.caution:
818
- lines.append(f"Check: {result.caution}")
819
- return "\n".join(lines)
820
-
821
- # answer mode
822
- if result.answer_letter and result.answer_value:
823
- lines.append(f"**Answer: {result.answer_letter}**")
824
- if style["show_steps"] or long:
825
- lines.append(f"Value: **{result.answer_value}**")
826
- steps = result.reasoning[:2] if short else result.reasoning
827
- lines.extend([f"- {s}" for s in steps])
828
- elif result.answer_value:
829
- lines.append(f"**Answer: {result.answer_value}**")
830
- if style["show_steps"] or long:
831
- steps = result.reasoning[:2] if short else result.reasoning
832
- lines.extend([f"- {s}" for s in steps])
833
-
834
- if result.caution:
835
- lines.append(f"Check: {result.caution}")
836
-
837
- return "\n".join(lines)
838
-
839
-
840
- def compose_verbal_reply(
841
- req: ChatRequest,
842
- result: SolveResult,
843
- help_mode: str,
844
- style: Dict[str, Any],
845
- options: List[Tuple[str, str]]
846
- ) -> str:
847
- prefix = style["tone_prefix"]
848
- lines = [prefix]
849
-
850
- if help_mode == "answer":
851
- lines.append("I can help analyse the verbal logic, but this version is strongest on Quant/Data Insight.")
852
- else:
853
- lines.append("Here’s the best way to approach this verbal question:")
854
-
855
- steps = result.reasoning[:2] if style["detail"] == "short" else result.reasoning
856
- lines.extend([f"- {s}" for s in steps])
857
-
858
- if options:
859
- lines.append("Send the full passage plus all answer choices and I can help eliminate them one by one.")
860
-
861
- if result.caution:
862
- lines.append(result.caution)
863
-
864
- return "\n".join(lines)
865
-
866
-
867
- def compose_fallback_reply(req: ChatRequest, style: Dict[str, Any]) -> str:
868
- prefix = style["tone_prefix"]
869
- detail = style["detail"]
870
-
871
- if detail == "short":
872
- return (
873
- f"{prefix}\n"
874
- "Paste the full GMAT question and the answer choices. I’m strongest on Quant/Data Insight and can give either a hint or the final answer."
875
- )
876
- return (
877
- f"{prefix}\n"
878
- "Paste the full GMAT-style question, ideally with answer choices A-E.\n"
879
- "I can handle:\n"
880
- "- arithmetic, percentages, ratios, algebra, basic statistics, probability, geometry\n"
881
- "- option checking for multiple-choice quant questions\n"
882
- "- strategy help for verbal questions\n"
883
- "Also tell me whether you want a hint, a walkthrough, or just the final answer."
884
- )
885
-
886
-
887
- # =========================
888
- # Main chat logic
889
- # =========================
890
-
891
- def build_context_question(req: ChatRequest) -> str:
892
- # Use the current message first, but pull in recent history if the message is just
893
- # "help me solve it" or similar.
894
- msg = normalize_text(req.message)
895
- if len(msg) > 25 and ("?" in msg or contains_math_signal(msg) or contains_verbal_signal(msg)):
896
- return msg
897
-
898
- history_blob = last_n_messages(req.chat_history, n=8)
899
- return normalize_text(history_blob + "\nUSER: " + msg).strip()
900
-
901
-
902
- def answer_chat(req: ChatRequest) -> ChatResponse:
903
- style = build_style(req.tone, req.verbosity, req.transparency)
904
- help_mode = decide_help_mode(req)
905
-
906
- question_text = build_context_question(req)
907
- options = extract_options(question_text)
908
- stem = strip_options(question_text) if options else question_text
909
-
910
- # Quant/Data Insight path
911
- if contains_math_signal(question_text):
912
- quant_result = solve_quant(stem, options)
913
- if quant_result:
914
- reply = compose_quant_reply(req, quant_result, help_mode, style, options)
915
- return ChatResponse(
916
- reply=reply,
917
- meta={
918
- "domain": "quant",
919
- "solved": quant_result.solved,
920
- "method": quant_result.method,
921
- "confidence": quant_result.confidence,
922
- "answer_letter": quant_result.answer_letter,
923
- "answer_value": quant_result.answer_value,
924
- "help_mode": help_mode
925
- }
926
- )
927
-
928
- # Verbal path
929
- if contains_verbal_signal(question_text):
930
- verbal_result = solve_verbal_strategy(question_text, options)
931
- reply = compose_verbal_reply(req, verbal_result, help_mode, style, options)
932
- return ChatResponse(
933
- reply=reply,
934
- meta={
935
- "domain": "verbal",
936
- "solved": False,
937
- "method": verbal_result.method,
938
- "confidence": verbal_result.confidence,
939
- "help_mode": help_mode
940
- }
941
- )
942
-
943
- # Fallback
944
- return ChatResponse(
945
- reply=compose_fallback_reply(req, style),
946
- meta={
947
- "domain": "fallback",
948
- "solved": False,
949
- "help_mode": help_mode
950
  }
951
- )
952
-
953
-
954
- # =========================
955
- # Routes
956
- # =========================
957
-
958
- @app.get("/health")
959
- def health():
960
- return {
961
- "ok": True,
962
- "service": "GMAT Solver v2",
963
- "sympy_available": SYMPY_AVAILABLE
964
  }
965
 
966
-
967
- @app.post("/chat", response_model=ChatResponse)
968
- def chat(req: ChatRequest):
969
- return answer_chat(req)
970
-
971
-
972
- @app.get("/", response_class=HTMLResponse)
973
- def root():
974
- return HTMLResponse("""
975
- <!DOCTYPE html>
976
- <html>
977
- <head>
978
- <meta charset="utf-8" />
979
- <title>GMAT Solver v2</title>
980
- <style>
981
- body { font-family: Arial, sans-serif; margin: 24px; max-width: 900px; }
982
- textarea, input[type="range"] { width: 100%; }
983
- textarea { min-height: 220px; margin-bottom: 12px; }
984
- .row { margin-bottom: 12px; }
985
- .label { font-weight: bold; margin-bottom: 4px; display: block; }
986
- button { padding: 10px 16px; cursor: pointer; }
987
- pre {
988
- white-space: pre-wrap;
989
- background: #f5f5f5;
990
- padding: 12px;
991
- border-radius: 8px;
992
  }
993
- </style>
994
- </head>
995
- <body>
996
- <h1>GMAT Solver v2</h1>
997
- <p>Paste a GMAT-style question below. You can ask for a hint, a walkthrough, or the final answer.</p>
998
-
999
- <div class="row">
1000
- <label class="label">Question / Message</label>
1001
- <textarea id="message">A store increases the price of a jacket from 80 by 25 percent. What is the new price?
1002
- A) 90
1003
- B) 95
1004
- C) 100
1005
- D) 105
1006
- E) 110
1007
 
1008
- Give me the answer.</textarea>
1009
- </div>
1010
-
1011
- <div class="row">
1012
- <label class="label">Tone: <span id="toneVal">0.5</span></label>
1013
- <input id="tone" type="range" min="0" max="1" step="0.01" value="0.5" oninput="toneVal.textContent=this.value" />
1014
- </div>
1015
-
1016
- <div class="row">
1017
- <label class="label">Verbosity: <span id="verbVal">0.5</span></label>
1018
- <input id="verbosity" type="range" min="0" max="1" step="0.01" value="0.5" oninput="verbVal.textContent=this.value" />
1019
- </div>
1020
 
1021
- <div class="row">
1022
- <label class="label">Transparency: <span id="transVal">0.5</span></label>
1023
- <input id="transparency" type="range" min="0" max="1" step="0.01" value="0.5" oninput="transVal.textContent=this.value" />
1024
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1025
 
1026
- <div class="row">
1027
- <button onclick="send()">Send</button>
1028
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1029
 
1030
- <h3>Response</h3>
1031
- <pre id="output"></pre>
1032
 
1033
- <script>
1034
- async function send() {
1035
- const payload = {
1036
- message: document.getElementById('message').value,
1037
- chat_history: [],
1038
- tone: parseFloat(document.getElementById('tone').value),
1039
- verbosity: parseFloat(document.getElementById('verbosity').value),
1040
- transparency: parseFloat(document.getElementById('transparency').value)
1041
- };
 
 
1042
 
1043
- const out = document.getElementById('output');
1044
- out.textContent = "Loading...";
 
 
 
 
 
1045
 
1046
- try {
1047
- const res = await fetch('/chat', {
1048
- method: 'POST',
1049
- headers: {'Content-Type': 'application/json'},
1050
- body: JSON.stringify(payload)
1051
- });
1052
- const data = await res.json();
1053
- out.textContent = JSON.stringify(data, null, 2);
1054
- } catch (err) {
1055
- out.textContent = "Error: " + err;
1056
- }
1057
  }
1058
- </script>
1059
- </body>
1060
- </html>
1061
- """)
1062
-
1063
-
1064
- # =========================
1065
- # Optional local run
1066
- # =========================
1067
- # For local testing:
1068
- # uvicorn app:app --reload --host 0.0.0.0 --port 7860
 
1
+ using System;
2
+ using System.Collections;
3
+ using System.Collections.Generic;
4
+ using System.Text;
5
+ using UnityEngine;
6
+ using UnityEngine.Networking;
7
+
8
+ public class TradingGameAIApiClient : MonoBehaviour
9
+ {
10
+ [Header("API")]
11
+ [SerializeField] private string apiUrl = "https://j-js-tradinggameai.hf.space/chat";
12
+
13
+ [Header("Debug")]
14
+ [SerializeField] private bool logRequests = true;
15
+ [SerializeField] private bool logResponses = true;
16
+
17
+ [Serializable]
18
+ public class ChatMessage
19
+ {
20
+ public string role;
21
+ public string text;
22
+
23
+ public ChatMessage(string role, string text)
24
+ {
25
+ this.role = role;
26
+ this.text = text;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  }
29
 
30
+ [Serializable]
31
+ public class ChatRequest
32
+ {
33
+ public string message;
34
+ public List<ChatMessage> chat_history;
35
+ public float tone;
36
+ public float verbosity;
37
+ public float transparency;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ [Serializable]
41
+ public class ChatResponse
42
+ {
43
+ public string reply;
44
+ }
 
 
 
 
 
 
 
45
 
46
+ public void SendChatRequest(
47
+ string message,
48
+ List<ChatMessage> chatHistory,
49
+ float tone,
50
+ float verbosity,
51
+ float transparency,
52
+ Action<string> onSuccess,
53
+ Action<string> onError)
54
+ {
55
+ StartCoroutine(SendChatRequestRoutine(
56
+ message,
57
+ chatHistory,
58
+ tone,
59
+ verbosity,
60
+ transparency,
61
+ onSuccess,
62
+ onError
63
+ ));
64
+ }
65
 
66
+ private IEnumerator SendChatRequestRoutine(
67
+ string message,
68
+ List<ChatMessage> chatHistory,
69
+ float tone,
70
+ float verbosity,
71
+ float transparency,
72
+ Action<string> onSuccess,
73
+ Action<string> onError)
74
+ {
75
+ Debug.Log("TradingGameAI apiUrl = " + apiUrl);
76
+
77
+ ChatRequest requestData = new ChatRequest
78
+ {
79
+ message = message,
80
+ chat_history = chatHistory ?? new List<ChatMessage>(),
81
+ tone = tone,
82
+ verbosity = verbosity,
83
+ transparency = transparency
84
+ };
85
+
86
+ string json = JsonUtility.ToJson(requestData);
87
+
88
+ if (logRequests)
89
+ Debug.Log("TradingGameAI Request JSON: " + json);
90
+
91
+ using (UnityWebRequest request = new UnityWebRequest(apiUrl, "POST"))
92
+ {
93
+ byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
94
+ request.uploadHandler = new UploadHandlerRaw(bodyRaw);
95
+ request.downloadHandler = new DownloadHandlerBuffer();
96
+ request.SetRequestHeader("Content-Type", "application/json");
97
+ request.SetRequestHeader("Accept", "application/json");
98
+
99
+ yield return request.SendWebRequest();
100
+
101
+ string responseText = request.downloadHandler.text;
102
+
103
+ if (logResponses)
104
+ Debug.Log("TradingGameAI Raw Response: " + responseText);
105
+
106
+ if (request.result != UnityWebRequest.Result.Success)
107
+ {
108
+ string errorMessage = "API request failed: " + request.error;
109
+
110
+ if (!string.IsNullOrEmpty(responseText))
111
+ errorMessage += "\nServer: " + responseText;
112
+
113
+ Debug.LogError(errorMessage);
114
+ onError?.Invoke(errorMessage);
115
+ yield break;
116
+ }
117
 
118
+ ChatResponse responseData = null;
 
119
 
120
+ try
121
+ {
122
+ responseData = JsonUtility.FromJson<ChatResponse>(responseText);
123
+ }
124
+ catch (Exception e)
125
+ {
126
+ string parseError = "Failed to parse API response: " + e.Message + "\nResponse: " + responseText;
127
+ Debug.LogError(parseError);
128
+ onError?.Invoke(parseError);
129
+ yield break;
130
+ }
131
 
132
+ if (responseData == null || string.IsNullOrEmpty(responseData.reply))
133
+ {
134
+ string invalidResponse = "API returned empty or invalid reply.\nResponse: " + responseText;
135
+ Debug.LogError(invalidResponse);
136
+ onError?.Invoke(invalidResponse);
137
+ yield break;
138
+ }
139
 
140
+ onSuccess?.Invoke(responseData.reply);
141
+ }
 
 
 
 
 
 
 
 
 
142
  }
143
+ }