Spaces:
Runtime error
Runtime error
Update src/SecondModule/module2.py
Browse files- src/SecondModule/module2.py +0 -163
src/SecondModule/module2.py
CHANGED
|
@@ -34,169 +34,6 @@ class GeneratedQuestion:
|
|
| 34 |
correct_answer: str
|
| 35 |
explanation: str
|
| 36 |
|
| 37 |
-
# class SimilarQuestionGenerator:
|
| 38 |
-
# def __init__(self, misconception_csv_path: str = 'misconception_mapping.csv'):
|
| 39 |
-
# """
|
| 40 |
-
# Initialize the generator by loading the misconception mapping and the language model.
|
| 41 |
-
# """
|
| 42 |
-
# self._load_data(misconception_csv_path)
|
| 43 |
-
|
| 44 |
-
# def _load_data(self, misconception_csv_path: str):
|
| 45 |
-
# logger.info("Loading misconception mapping...")
|
| 46 |
-
# self.misconception_df = pd.read_csv(misconception_csv_path)
|
| 47 |
-
|
| 48 |
-
# def get_misconception_text(self, misconception_id: float) -> Optional[str]:
|
| 49 |
-
# # MisconceptionId를 받아 해당 ID에 매칭되는 오개념 설명 텍스트를 반환합니다
|
| 50 |
-
# """Retrieve the misconception text based on the misconception ID."""
|
| 51 |
-
# if pd.isna(misconception_id): # NaN 체크
|
| 52 |
-
# logger.warning("Received NaN for misconception_id.")
|
| 53 |
-
# return "No misconception provided."
|
| 54 |
-
|
| 55 |
-
# try:
|
| 56 |
-
# row = self.misconception_df[self.misconception_df['MisconceptionId'] == int(misconception_id)]
|
| 57 |
-
# if not row.empty:
|
| 58 |
-
# return row.iloc[0]['MisconceptionName']
|
| 59 |
-
# except ValueError as e:
|
| 60 |
-
# logger.error(f"Error processing misconception_id: {e}")
|
| 61 |
-
|
| 62 |
-
# logger.warning(f"No misconception found for ID: {misconception_id}")
|
| 63 |
-
# return "Misconception not found."
|
| 64 |
-
|
| 65 |
-
# def generate_prompt(self, construct_name: str, subject_name: str, question_text: str, correct_answer_text: str, wrong_answer_text: str, misconception_text: str) -> str:
|
| 66 |
-
# """Create a prompt for the language model."""
|
| 67 |
-
# #문제 생성을 위한 프롬프트 텍스트를 생성
|
| 68 |
-
# logger.info("Generating prompt...")
|
| 69 |
-
# misconception_clause = (f"that targets the following misconception: \"{misconception_text}\"." if misconception_text != "There is no misconception" else "")
|
| 70 |
-
# prompt = f"""
|
| 71 |
-
# <|begin_of_text|>
|
| 72 |
-
# <|start_header_id|>system<|end_header_id|>
|
| 73 |
-
# You are an educational assistant designed to generate multiple-choice questions {misconception_clause}
|
| 74 |
-
# <|eot_id|>
|
| 75 |
-
# <|start_header_id|>user<|end_header_id|>
|
| 76 |
-
# You need to create a similar multiple-choice question based on the following details:
|
| 77 |
-
|
| 78 |
-
# Construct Name: {construct_name}
|
| 79 |
-
# Subject Name: {subject_name}
|
| 80 |
-
# Question Text: {question_text}
|
| 81 |
-
# Correct Answer: {correct_answer_text}
|
| 82 |
-
# Wrong Answer: {wrong_answer_text}
|
| 83 |
-
|
| 84 |
-
# Please follow this output format:
|
| 85 |
-
# ---
|
| 86 |
-
# Question: <Your Question Text>
|
| 87 |
-
# A) <Choice A>
|
| 88 |
-
# B) <Choice B>
|
| 89 |
-
# C) <Choice C>
|
| 90 |
-
# D) <Choice D>
|
| 91 |
-
# Correct Answer: <Correct Choice (e.g., A)>
|
| 92 |
-
# Explanation: <Brief explanation for the correct answer>
|
| 93 |
-
# ---
|
| 94 |
-
# Ensure that the question is conceptually similar but not identical to the original. Ensure clarity and educational value.
|
| 95 |
-
# <|eot_id|>
|
| 96 |
-
# <|start_header_id|>assistant<|end_header_id|>
|
| 97 |
-
# """.strip()
|
| 98 |
-
# logger.debug(f"Generated prompt: {prompt}")
|
| 99 |
-
# return prompt
|
| 100 |
-
|
| 101 |
-
# def call_model_api(self, prompt: str) -> str:
|
| 102 |
-
# """Hugging Face API 호출"""
|
| 103 |
-
# logger.info("Calling Hugging Face API...")
|
| 104 |
-
# headers = {"Authorization": f"Bearer {API_KEY}"}
|
| 105 |
-
|
| 106 |
-
# try:
|
| 107 |
-
# response = requests.post(API_URL, headers=headers, json={"inputs": prompt})
|
| 108 |
-
# response.raise_for_status()
|
| 109 |
-
|
| 110 |
-
# response_data = response.json()
|
| 111 |
-
# logger.debug(f"Raw API response: {response_data}")
|
| 112 |
-
|
| 113 |
-
# # API 응답이 리스트인 경우 처리
|
| 114 |
-
# if isinstance(response_data, list):
|
| 115 |
-
# if response_data and isinstance(response_data[0], dict):
|
| 116 |
-
# generated_text = response_data[0].get('generated_text', '')
|
| 117 |
-
# else:
|
| 118 |
-
# generated_text = response_data[0] if response_data else ''
|
| 119 |
-
# # API 응답이 딕셔너리인 경우 처리
|
| 120 |
-
# elif isinstance(response_data, dict):
|
| 121 |
-
# generated_text = response_data.get('generated_text', '')
|
| 122 |
-
# else:
|
| 123 |
-
# generated_text = str(response_data)
|
| 124 |
-
|
| 125 |
-
# logger.info(f"Generated text: {generated_text}")
|
| 126 |
-
# return generated_text
|
| 127 |
-
|
| 128 |
-
# except requests.exceptions.RequestException as e:
|
| 129 |
-
# logger.error(f"API request failed: {e}")
|
| 130 |
-
# raise
|
| 131 |
-
# except Exception as e:
|
| 132 |
-
# logger.error(f"Unexpected error in call_model_api: {e}")
|
| 133 |
-
# raise
|
| 134 |
-
# def parse_model_output(self, output: str) -> GeneratedQuestion:
|
| 135 |
-
# if not isinstance(output, str):
|
| 136 |
-
# logger.error(f"Invalid output format: {type(output)}. Expected string.")
|
| 137 |
-
# raise ValueError("Model output is not a string.")
|
| 138 |
-
|
| 139 |
-
# logger.info(f"Parsing output: {output}")
|
| 140 |
-
# output_lines = output.strip().splitlines()
|
| 141 |
-
# logger.debug(f"Split output into lines: {output_lines}")
|
| 142 |
-
|
| 143 |
-
# question, choices, correct_answer, explanation = "", {}, "", ""
|
| 144 |
-
|
| 145 |
-
# for line in output_lines:
|
| 146 |
-
# if line.lower().startswith("question:"):
|
| 147 |
-
# question = line.split(":", 1)[1].strip()
|
| 148 |
-
# elif line.startswith("A)"):
|
| 149 |
-
# choices["A"] = line[2:].strip()
|
| 150 |
-
# elif line.startswith("B)"):
|
| 151 |
-
# choices["B"] = line[2:].strip()
|
| 152 |
-
# elif line.startswith("C)"):
|
| 153 |
-
# choices["C"] = line[2:].strip()
|
| 154 |
-
# elif line.startswith("D)"):
|
| 155 |
-
# choices["D"] = line[2:].strip()
|
| 156 |
-
# elif line.lower().startswith("correct answer:"):
|
| 157 |
-
# correct_answer = line.split(":", 1)[1].strip()
|
| 158 |
-
# elif line.lower().startswith("explanation:"):
|
| 159 |
-
# explanation = line.split(":", 1)[1].strip()
|
| 160 |
-
|
| 161 |
-
# if not question or len(choices) < 4 or not correct_answer or not explanation:
|
| 162 |
-
# logger.warning("Incomplete generated question.")
|
| 163 |
-
# return GeneratedQuestion(question, choices, correct_answer, explanation)
|
| 164 |
-
|
| 165 |
-
# def generate_similar_question_with_text(self, construct_name: str, subject_name: str, question_text: str, correct_answer_text: str, wrong_answer_text: str, misconception_id: float) -> Tuple[Optional[GeneratedQuestion], Optional[str]]:
|
| 166 |
-
# logger.info("generate_similar_question_with_text initiated")
|
| 167 |
-
|
| 168 |
-
# # 예외 처리 추가
|
| 169 |
-
# try:
|
| 170 |
-
# misconception_text = self.get_misconception_text(misconception_id)
|
| 171 |
-
# logger.info(f"Misconception text retrieved: {misconception_text}")
|
| 172 |
-
# except Exception as e:
|
| 173 |
-
# logger.error(f"Error retrieving misconception text: {e}")
|
| 174 |
-
# return None, None
|
| 175 |
-
|
| 176 |
-
# if not misconception_text:
|
| 177 |
-
# logger.info("Skipping question generation due to lack of misconception.")
|
| 178 |
-
# return None, None
|
| 179 |
-
|
| 180 |
-
# prompt = self.generate_prompt(construct_name, subject_name, question_text, correct_answer_text, wrong_answer_text, misconception_text)
|
| 181 |
-
# logger.info(f"Generated prompt: {prompt}")
|
| 182 |
-
|
| 183 |
-
# generated_text = None # 기본값으로 초기화
|
| 184 |
-
# try:
|
| 185 |
-
# logger.info("Calling call_model_api...")
|
| 186 |
-
# generated_text = self.call_model_api(prompt)
|
| 187 |
-
# logger.info(f"Generated text from API: {generated_text}")
|
| 188 |
-
|
| 189 |
-
# # 파싱
|
| 190 |
-
# generated_question = self.parse_model_output(generated_text)
|
| 191 |
-
# logger.info(f"Generated question object: {generated_question}")
|
| 192 |
-
# return generated_question, generated_text
|
| 193 |
-
|
| 194 |
-
# except Exception as e:
|
| 195 |
-
# logger.error(f"Failed to generate question: {e}")
|
| 196 |
-
# logger.debug(f"API output for debugging: {generated_text}")
|
| 197 |
-
# return None, generated_text
|
| 198 |
-
|
| 199 |
-
|
| 200 |
class SimilarQuestionGenerator:
|
| 201 |
def __init__(self, misconception_csv_path: str = 'misconception_mapping.csv'):
|
| 202 |
"""
|
|
|
|
| 34 |
correct_answer: str
|
| 35 |
explanation: str
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
class SimilarQuestionGenerator:
|
| 38 |
def __init__(self, misconception_csv_path: str = 'misconception_mapping.csv'):
|
| 39 |
"""
|