|
| 1 | +import random |
| 2 | +import re |
| 3 | +from typing import Any, Optional |
| 4 | + |
| 5 | +from graphgen.bases import BaseGenerator |
| 6 | +from graphgen.templates import AGGREGATED_GENERATION_PROMPT |
| 7 | +from graphgen.utils import detect_main_language, logger |
| 8 | + |
| 9 | +random.seed(42) |
| 10 | + |
| 11 | + |
| 12 | +class MaskedFillInBlankGenerator(BaseGenerator): |
| 13 | + """ |
| 14 | + Masked Fill-in-blank Generator follows a TWO-STEP process: |
| 15 | + 1. rephrase: Rephrase the input nodes and edges into a coherent text that maintains the original meaning. |
| 16 | + 2. mask: Randomly select a node from the input nodes, and then mask the name of the node in the rephrased text. |
| 17 | + """ |
| 18 | + |
| 19 | + @staticmethod |
| 20 | + def build_prompt( |
| 21 | + batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]] |
| 22 | + ) -> str: |
| 23 | + """ |
| 24 | + Build prompts for REPHRASE. |
| 25 | + :param batch |
| 26 | + :return: |
| 27 | + """ |
| 28 | + nodes, edges = batch |
| 29 | + entities_str = "\n".join( |
| 30 | + [ |
| 31 | + f"{index + 1}. {node[0]}: {node[1]['description']}" |
| 32 | + for index, node in enumerate(nodes) |
| 33 | + ] |
| 34 | + ) |
| 35 | + relations_str = "\n".join( |
| 36 | + [ |
| 37 | + f"{index + 1}. {edge[0]} -- {edge[1]}: {edge[2]['description']}" |
| 38 | + for index, edge in enumerate(edges) |
| 39 | + ] |
| 40 | + ) |
| 41 | + language = detect_main_language(entities_str + relations_str) |
| 42 | + |
| 43 | + # TODO: configure add_context |
| 44 | + # if add_context: |
| 45 | + # original_ids = [ |
| 46 | + # node["source_id"].split("<SEP>")[0] for node in _process_nodes |
| 47 | + # ] + [edge[2]["source_id"].split("<SEP>")[0] for edge in _process_edges] |
| 48 | + # original_ids = list(set(original_ids)) |
| 49 | + # original_text = await text_chunks_storage.get_by_ids(original_ids) |
| 50 | + # original_text = "\n".join( |
| 51 | + # [ |
| 52 | + # f"{index + 1}. {text['content']}" |
| 53 | + # for index, text in enumerate(original_text) |
| 54 | + # ] |
| 55 | + # ) |
| 56 | + prompt = AGGREGATED_GENERATION_PROMPT[language]["ANSWER_REPHRASING"].format( |
| 57 | + entities=entities_str, relationships=relations_str |
| 58 | + ) |
| 59 | + return prompt |
| 60 | + |
| 61 | + @staticmethod |
| 62 | + def parse_rephrased_text(response: str) -> Optional[str]: |
| 63 | + """ |
| 64 | + Parse the rephrased text from the response. |
| 65 | + :param response: |
| 66 | + :return: rephrased text |
| 67 | + """ |
| 68 | + rephrased_match = re.search( |
| 69 | + r"<rephrased_text>(.*?)</rephrased_text>", response, re.DOTALL |
| 70 | + ) |
| 71 | + if rephrased_match: |
| 72 | + rephrased_text = rephrased_match.group(1).strip() |
| 73 | + else: |
| 74 | + logger.warning("Failed to parse rephrased text from response: %s", response) |
| 75 | + return None |
| 76 | + return rephrased_text.strip('"').strip("'") |
| 77 | + |
| 78 | + @staticmethod |
| 79 | + def parse_response(response: str) -> dict: |
| 80 | + pass |
| 81 | + |
| 82 | + async def generate( |
| 83 | + self, |
| 84 | + batch: tuple[ |
| 85 | + list[tuple[str, dict]], list[tuple[Any, Any, dict] | tuple[Any, Any, Any]] |
| 86 | + ], |
| 87 | + ) -> list[dict]: |
| 88 | + """ |
| 89 | + Generate QAs based on a given batch. |
| 90 | + :param batch |
| 91 | + :return: QA pairs |
| 92 | + """ |
| 93 | + rephrasing_prompt = self.build_prompt(batch) |
| 94 | + response = await self.llm_client.generate_answer(rephrasing_prompt) |
| 95 | + context = self.parse_rephrased_text(response) |
| 96 | + if not context: |
| 97 | + return [] |
| 98 | + |
| 99 | + nodes, edges = batch |
| 100 | + |
| 101 | + assert len(nodes) == 3, ( |
| 102 | + "MaskedFillInBlankGenerator currently only supports quintuples that has 3 nodes, " |
| 103 | + f"but got {len(nodes)} nodes." |
| 104 | + ) |
| 105 | + assert len(edges) == 2, ( |
| 106 | + "MaskedFillInBlankGenerator currently only supports quintuples that has 2 edges, " |
| 107 | + f"but got {len(edges)} edges." |
| 108 | + ) |
| 109 | + |
| 110 | + node1, node2, node3 = nodes |
| 111 | + mask_node = random.choice([node1, node2, node3]) |
| 112 | + mask_node_name = mask_node[1]["entity_name"].strip("'\" \n\r\t") |
| 113 | + mask_pattern = re.compile(re.escape(mask_node_name), re.IGNORECASE) |
| 114 | + |
| 115 | + match = re.search(mask_pattern, context) |
| 116 | + if match: |
| 117 | + gth = match.group(0) |
| 118 | + masked_context = mask_pattern.sub("___", context) |
| 119 | + else: |
| 120 | + logger.debug( |
| 121 | + "Regex Match Failed!\n" |
| 122 | + "Expected name of node: %s\n" |
| 123 | + "Actual context: %s\n", |
| 124 | + mask_node_name, |
| 125 | + context, |
| 126 | + ) |
| 127 | + return [] |
| 128 | + |
| 129 | + logger.debug("masked_context: %s", masked_context) |
| 130 | + qa_pairs = { |
| 131 | + "question": masked_context, |
| 132 | + "answer": gth, |
| 133 | + } |
| 134 | + return [qa_pairs] |
0 commit comments