|
| 1 | +from lark import Lark, Transformer, v_args, Tree, Token |
| 2 | +from lark.tree import Meta |
| 3 | +from pydantic import BaseModel |
| 4 | +from typing import Any, Optional |
| 5 | +import math |
| 6 | +from app.lm.models.chat_completion import TokenLogprob |
| 7 | + |
| 8 | +class HasProb(BaseModel): |
| 9 | + value: Any |
| 10 | + start: int |
| 11 | + end: int |
| 12 | + logprob: float |
| 13 | + prob: float |
| 14 | + |
| 15 | +def map_characters_to_token_indices(extracted_data_token: list[TokenLogprob]) -> list[int]: |
| 16 | + """ |
| 17 | + Maps each character in the JSON string output to its corresponding token index. |
| 18 | + |
| 19 | + Args: |
| 20 | + extracted_data_token : A list of `TokenLogprob` objects, where each object represents a token and its data (such as the logprobs) |
| 21 | +
|
| 22 | + Returns: |
| 23 | + A list of integers where each position corresponds to a character in the concatenated JSON string, |
| 24 | + and the integer at each position is the index of the token responsible for generating that specific character in the JSON string. |
| 25 | + |
| 26 | + Example: |
| 27 | + -------- |
| 28 | + Given `extracted_data_token = [TokenLogprob(token='{'), TokenLogprob(token='"key1"'), TokenLogprob(token=': '), TokenLogprob(token='"value1"'), TokenLogprob(token='}')]` |
| 29 | + the JSON output is : '{"key1": "value1"}' and the function will return the list [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4] |
| 30 | + |
| 31 | + """ |
| 32 | + |
| 33 | + json_output = "".join(token_data.token for token_data in extracted_data_token) |
| 34 | + |
| 35 | + token_indices = [None] * len(json_output) |
| 36 | + current_char_pos = 0 |
| 37 | + |
| 38 | + for token_idx, token_data in enumerate(extracted_data_token): |
| 39 | + token_text = token_data.token |
| 40 | + for char_pos in range(len(token_text)): |
| 41 | + token_indices[current_char_pos] = token_idx |
| 42 | + current_char_pos += 1 |
| 43 | + |
| 44 | + return token_indices |
| 45 | + |
| 46 | +# Define a grammar for JSON |
| 47 | +json_grammar = r""" |
| 48 | + start: value |
| 49 | +
|
| 50 | + ?value: object #'?' is a Lark convention indicating that the rule can return the value directly instead of creating a separate parse tree node. |
| 51 | + | array |
| 52 | + | string |
| 53 | + | SIGNED_NUMBER -> number #'-> number' specifies an alias for the rule |
| 54 | + | "true" |
| 55 | + | "false" |
| 56 | + | "null" |
| 57 | +
|
| 58 | + array : "[" [value ("," value)*] "]" |
| 59 | + object : "{" [pair ("," pair)*] "}" |
| 60 | + pair : key ":" value |
| 61 | + key : ESCAPED_STRING |
| 62 | +
|
| 63 | + string : ESCAPED_STRING |
| 64 | +
|
| 65 | + %import common.ESCAPED_STRING |
| 66 | + %import common.SIGNED_NUMBER |
| 67 | + %import common.WS |
| 68 | + %ignore WS |
| 69 | +""" |
| 70 | + |
| 71 | +@v_args(meta=True) |
| 72 | +class Extractor(Transformer): |
| 73 | + def __init__(self, tokens: list[TokenLogprob], token_indices: list[int]): |
| 74 | + super().__init__() |
| 75 | + self.tokens = tokens |
| 76 | + self.token_indices = token_indices |
| 77 | + |
| 78 | + def _compute_logprob_sum(self, start: int, end: int) -> float: |
| 79 | + token_start = self.token_indices[start] |
| 80 | + token_end = self.token_indices[end] |
| 81 | + sum_logporb= sum(self.tokens[i].logprob for i in range(token_start, token_end)) |
| 82 | + return sum_logporb |
| 83 | + |
| 84 | + def number(self, meta: Meta, children: list[Token]) -> HasProb: |
| 85 | + logprob_sum = self._compute_logprob_sum(meta.start_pos, meta.end_pos) |
| 86 | + prob=math.exp(logprob_sum)* 100 |
| 87 | + return HasProb(value=float(children[0]), start=meta.start_pos, end=meta.end_pos, logprob=logprob_sum, prob=prob) |
| 88 | + |
| 89 | + def string(self, meta: Meta, children: list[Token]) -> HasProb: |
| 90 | + logprob_sum = self._compute_logprob_sum(meta.start_pos, meta.end_pos) |
| 91 | + prob=math.exp(logprob_sum)* 100 |
| 92 | + return HasProb(value=children[0][1:-1], start=meta.start_pos, end=meta.end_pos, logprob=logprob_sum, prob=prob) |
| 93 | + |
| 94 | + def true(self, meta: Meta, children: list[Token]) -> HasProb: |
| 95 | + logprob_sum = self._compute_logprob_sum(meta.start_pos, meta.end_pos) |
| 96 | + prob=math.exp(logprob_sum)* 100 |
| 97 | + return HasProb(value=True, start=meta.start_pos, end=meta.end_pos, logprob=logprob_sum, prob=prob) |
| 98 | + |
| 99 | + def false(self, meta: Meta, children: list[Token]) -> HasProb: |
| 100 | + logprob_sum = self._compute_logprob_sum(meta.start_pos, meta.end_pos) |
| 101 | + prob=math.exp(logprob_sum)* 100 |
| 102 | + return HasProb(value=False, start=meta.start_pos, end=meta.end_pos, logprob=logprob_sum, prob=prob) |
| 103 | + |
| 104 | + def null(self, meta: Meta, children: list[Token]): |
| 105 | + return None |
| 106 | + |
| 107 | + def array(self, meta: Meta, children:list[dict[str, Any] | Any]) -> list[dict[str,Any] | Any]: |
| 108 | + return [child.value if isinstance(child, HasProb) else child for child in children] |
| 109 | + |
| 110 | + def object(self, meta: Meta, children:list[tuple[str,Any]]) -> dict[str,Any]: |
| 111 | + result = {} |
| 112 | + for key, value in children: |
| 113 | + if isinstance(value, HasProb): |
| 114 | + result[key]=value.value |
| 115 | + result[f"{key}_logprob"]=value.logprob |
| 116 | + result[f"{key}_probability"]=value.prob |
| 117 | + else: |
| 118 | + result[key]=value |
| 119 | + return result |
| 120 | + |
| 121 | + def pair(self, meta: Meta, children:list[str, Any]) -> tuple[str, Any]: |
| 122 | + value = children[1] |
| 123 | + key = children[0] |
| 124 | + if isinstance(value, Tree) and not value.children: #['b', Tree(Token('RULE', 'value'), [])] |
| 125 | + value = None |
| 126 | + return key, value |
| 127 | + |
| 128 | + def key(self, meta: Meta, children: list[Token]) -> str: |
| 129 | + return children[0][1:-1] |
| 130 | + |
| 131 | + def start(self, meta: Meta, children:list[dict[str,Any]]) -> dict[str, Any]: |
| 132 | + return children[0] |
| 133 | + |
| 134 | +json_parser = Lark(json_grammar, parser="lalr", propagate_positions=True, maybe_placeholders=False) |
| 135 | + |
| 136 | +def extract_json_data(json_string: str, tokens: list[TokenLogprob], token_indices: list[int]) -> dict[str,Any]: |
| 137 | + tree = json_parser.parse(json_string) |
| 138 | + extractor = Extractor(tokens, token_indices) |
| 139 | + return extractor.transform(tree) |
| 140 | + |
0 commit comments