-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpressionJSONParser.swift
More file actions
205 lines (184 loc) · 7.54 KB
/
ExpressionJSONParser.swift
File metadata and controls
205 lines (184 loc) · 7.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import Foundation
/// Extracts and parses `ExpressionResult` from raw LLM text output (e.g. JSON embedded in markdown).
public enum ExpressionJSONParser {
public static func promptForExpression(phrase: String, context: String) -> String {
"""
You are an English learning assistant.
Return ONLY valid JSON with this exact schema:
{
"phrase": "string",
"meaning": "string",
"meaning_ko": "string",
"example": "string",
"level": "string"
}
Rules:
- Keep meaning concise and learner-friendly (English).
- meaning_ko: short, natural Korean gloss matching `meaning` (empty string only if impossible).
- Example must naturally use the phrase.
- Level must be exactly one of: B1, B2, C1, C2 (CEFR only; no IELTS or other text).
- Do not include markdown or extra keys.
phrase: \(phrase)
context: \(context)
"""
}
public static func parse(_ text: String) throws -> ExpressionResult {
guard let jsonPayload = extractJSONPayload(from: text),
let jsonData = jsonPayload.data(using: .utf8) else {
throw ExpressionJSONParseError.invalidJSONPayload
}
let root: Any
do {
root = try JSONSerialization.jsonObject(with: jsonData)
} catch {
throw ExpressionJSONParseError.invalidJSONPayload
}
if let dict = root as? [String: Any] {
return try expressionFromDict(dict, fallbackPhrase: "")
}
if let arr = root as? [Any], let first = arr.first as? [String: Any] {
return try expressionFromDict(first, fallbackPhrase: "")
}
throw ExpressionJSONParseError.invalidJSONPayload
}
/// Prefer `{...}` payloads; for `"[...]"` returns `nil` (use `extractJSONPayload` internally for parsing).
public static func extractJSONObject(from text: String) -> String? {
guard let p = extractJSONPayload(from: text), p.trimmingCharacters(in: .whitespacesAndNewlines).first == "{" else {
return nil
}
return p
}
/// Extracts a top-level JSON object `{...}` or array `[...]` from model text (markdown fences, prose, etc.).
public static func extractJSONPayload(from text: String) -> String? {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
if let inner = extractMarkdownFenceInner(trimmed) {
let s = inner.trimmingCharacters(in: .whitespacesAndNewlines)
if s.first == "{" { return extractBalancedJSONObject(from: s) }
if s.first == "[" { return extractBalancedJSONArray(from: s) }
}
if let obj = extractBalancedJSONObject(from: trimmed) { return obj }
if let arr = extractBalancedJSONArray(from: trimmed) { return arr }
return nil
}
private static func extractMarkdownFenceInner(_ text: String) -> String? {
let pattern = #"```(?:json)?\s*\n?([\s\S]*?)```"#
guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else {
return nil
}
let range = NSRange(text.startIndex..<text.endIndex, in: text)
guard let match = regex.firstMatch(in: text, options: [], range: range),
match.numberOfRanges > 1,
let capture = Range(match.range(at: 1), in: text) else {
return nil
}
return String(text[capture])
}
private static func extractBalancedJSONObject(from text: String) -> String? {
scanBalanced(from: text, open: "{", close: "}")
}
private static func extractBalancedJSONArray(from text: String) -> String? {
scanBalanced(from: text, open: "[", close: "]")
}
private static func scanBalanced(from text: String, open: Character, close: Character) -> String? {
var startIndex: String.Index?
var depth = 0
var isEscaped = false
var inString = false
for index in text.indices {
let char = text[index]
if inString {
if isEscaped {
isEscaped = false
continue
}
if char == "\\" {
isEscaped = true
} else if char == "\"" {
inString = false
}
continue
}
if char == "\"" {
inString = true
continue
}
if char == open {
if depth == 0 { startIndex = index }
depth += 1
} else if char == close {
guard depth > 0 else { continue }
depth -= 1
if depth == 0, let start = startIndex {
return String(text[start...index])
}
}
}
return nil
}
// MARK: - Lenient row parsing
private static func stringValue(_ object: [String: Any], keys: [String]) -> String? {
for key in keys {
if let s = object[key] as? String {
let t = s.trimmingCharacters(in: .whitespacesAndNewlines)
if !t.isEmpty { return t }
}
if let n = object[key] as? NSNumber {
return n.stringValue
}
}
return nil
}
/// Builds one `ExpressionResult` from a loosely-shaped JSON object (synonym keys, minor omissions).
private static func expressionFromDict(_ object: [String: Any], fallbackPhrase: String) throws -> ExpressionResult {
let phraseRaw = stringValue(
object,
keys: ["phrase", "expression", "term", "target_phrase", "targetPhrase", "id"]
) ?? fallbackPhrase
let phrase = phraseRaw.trimmingCharacters(in: .whitespacesAndNewlines)
guard let meaning = stringValue(
object,
keys: ["meaning", "definition", "translation", "gloss", "explain", "explanation", "summary"]
), !meaning.isEmpty else {
throw ExpressionJSONParseError.invalidExpressionResult(
NSError(
domain: "ExpressionJSONParser",
code: 1,
userInfo: [NSLocalizedDescriptionKey: "Missing non-empty meaning (or synonym key)."]
)
)
}
let example = stringValue(
object,
keys: ["example", "sample", "usage", "sentence", "context_example"]
) ?? meaning
let meaningKo = stringValue(
object,
keys: ["meaning_ko", "meaningKo", "gloss_ko", "translation_ko", "korean"]
) ?? ""
let rawLevel = stringValue(
object,
keys: ["level", "difficulty", "cefr", "proficiency"]
) ?? "B2"
let level = CEFRLevelFormatting.shortLabel(from: rawLevel)
let finalPhrase = phrase.isEmpty ? fallbackPhrase : phrase
return ExpressionResult(
phrase: finalPhrase,
meaning: meaning,
example: example,
level: level,
meaningKo: meaningKo.trimmingCharacters(in: .whitespacesAndNewlines)
)
}
}
public enum ExpressionJSONParseError: Error, LocalizedError {
case invalidJSONPayload
case invalidExpressionResult(Error)
public var errorDescription: String? {
switch self {
case .invalidJSONPayload:
return "Output did not contain valid JSON."
case let .invalidExpressionResult(error):
return "JSON could not be parsed into ExpressionResult: \(error.localizedDescription)"
}
}
}