|
| 1 | +import re |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +from graphgen.bases import BaseGenerator |
| 5 | +from graphgen.templates import FILL_IN_BLANK_GENERATION_PROMPT |
| 6 | +from graphgen.utils import compute_content_hash, detect_main_language, logger |
| 7 | + |
| 8 | + |
| 9 | +class FillInBlankGenerator(BaseGenerator): |
| 10 | + def __init__(self, llm_client, num_of_questions) -> None: |
| 11 | + super().__init__(llm_client) |
| 12 | + self.num_of_questions = num_of_questions |
| 13 | + |
| 14 | + @staticmethod |
| 15 | + def parse_response(response: str) -> Any: |
| 16 | + """ |
| 17 | + Parse fill-in-the-blank QA pairs from the LLM response. |
| 18 | + Each QA pair contains question text with placeholders and the correct answer(s). |
| 19 | +
|
| 20 | + :param response: The LLM response containing XML-formatted QA pairs |
| 21 | + :return: Dictionary mapping question hash to question data, where each |
| 22 | + value is a dict with "question", "answer", and "answers" keys |
| 23 | + """ |
| 24 | + qa_pairs = {} |
| 25 | + |
| 26 | + # Extract all QA pair blocks |
| 27 | + qa_blocks = re.findall(r"<qa_pair>(.*?)</qa_pair>", response, re.DOTALL) |
| 28 | + |
| 29 | + if not qa_blocks: |
| 30 | + logger.warning("No QA pairs found in response: %s", response) |
| 31 | + return {} |
| 32 | + |
| 33 | + for block in qa_blocks: |
| 34 | + # Extract and clean question text |
| 35 | + q_match = re.search(r"<question>(.*?)</question>", block, re.DOTALL) |
| 36 | + if not q_match: |
| 37 | + logger.warning("Failed to parse question from block: %s", block) |
| 38 | + continue |
| 39 | + question = q_match.group(1).strip().strip('"').strip("'") |
| 40 | + |
| 41 | + # Extract and clean answer text |
| 42 | + ans_match = re.search(r"<answer>(.*?)</answer>", block, re.DOTALL) |
| 43 | + if not ans_match: |
| 44 | + logger.warning("Failed to parse answer from block: %s", block) |
| 45 | + continue |
| 46 | + |
| 47 | + answer_text = ans_match.group(1).strip().strip('"').strip("'") |
| 48 | + |
| 49 | + # Parse multiple answers (e.g., "A8X, 八百万" or "A8X") |
| 50 | + # Split by comma and strip whitespace from each answer |
| 51 | + answers = [ans.strip() for ans in answer_text.split(",") if ans.strip()] |
| 52 | + |
| 53 | + # Ensure at least one valid answer |
| 54 | + if len(answers) == 0: |
| 55 | + logger.warning("No valid answers found in: %s", answer_text) |
| 56 | + continue |
| 57 | + |
| 58 | + # Build result entry with question hash as key |
| 59 | + question_hash = compute_content_hash(question) |
| 60 | + qa_pairs[question_hash] = { |
| 61 | + "question": question, |
| 62 | + "answer": answer_text, # Original answer text with commas |
| 63 | + "answers": answers, # List of individual answers: ["A8X"] or ["A8X", "八百万"] |
| 64 | + } |
| 65 | + |
| 66 | + logger.debug( |
| 67 | + "Successfully parsed fill-in-the-blank question: %s", question[:50] |
| 68 | + ) |
| 69 | + |
| 70 | + if not qa_pairs: |
| 71 | + logger.error("Failed to parse any valid QA pairs from response") |
| 72 | + |
| 73 | + return qa_pairs |
| 74 | + |
| 75 | + # pylint: disable=W0221 |
| 76 | + def build_prompt( |
| 77 | + self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]] |
| 78 | + ) -> str: |
| 79 | + nodes, edges = batch |
| 80 | + entities_str = "\n".join( |
| 81 | + [ |
| 82 | + f"{index + 1}. {node[0]}: {node[1]['description']}" |
| 83 | + for index, node in enumerate(nodes) |
| 84 | + ] |
| 85 | + ) |
| 86 | + |
| 87 | + relationships_str = "\n".join( |
| 88 | + [ |
| 89 | + f"{index + 1}. {edge[0]} -- {edge[1]}: {edge[2]['description']}" |
| 90 | + for index, edge in enumerate(edges) |
| 91 | + ] |
| 92 | + ) |
| 93 | + context = entities_str + "\n" + relationships_str |
| 94 | + language = detect_main_language(entities_str + relationships_str) |
| 95 | + prompt = FILL_IN_BLANK_GENERATION_PROMPT[language].format( |
| 96 | + context=context, |
| 97 | + num_of_questions=self.num_of_questions, |
| 98 | + ) |
| 99 | + return prompt |
0 commit comments