ojas121 commited on
Commit
b06005a
·
verified ·
1 Parent(s): e5b3eef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -89
app.py CHANGED
@@ -1,11 +1,13 @@
1
- import os
2
- import json
3
- from transformers import AutoTokenizer, AutoModelForQuestionAnswering, TrainingArguments, Trainer
4
- from datasets import Dataset
5
 
6
- # 1. Training Data Preparation
7
- raw_text = """
8
- BOOK I. Concerning Discipline.
 
 
 
 
9
  The end of Sciences; association with the aged; restraint of
10
  the organs of sense; the creation of ministers; the creation of
11
  councillors and priests; ascertaining by temptations purity or
@@ -15,90 +17,34 @@ state; winning over the factions for or against an enemy's cause in
15
  an enemy's state; the business of council meeting; the mission of
16
  envoys; protection of princes; the conduct of a prince kept under
17
  restraint; treatment of a prince kept under restraint; the duties of a
18
- king; duty towards the harem; personal safety.
19
- """
20
-
21
- # Create synthetic QA dataset
22
- def generate_qa_pairs(context):
23
- questions_answers = [
24
- {"question": "What is the end of Sciences?", "answer": "Concerning Discipline"},
25
- {"question": "Who should one associate with?", "answer": "The aged"},
26
- {"question": "What does the institution of spies involve?", "answer": "Protection of parties for or against one's own cause in one's own state"},
27
- {"question": "What are the duties of a king?", "answer": "Duty towards the harem; personal safety"},
28
- ]
29
- qa_data = [{"context": context, "question": qa["question"], "answers": {"text": [qa["answer"]], "answer_start": [context.find(qa["answer"])]}} for qa in questions_answers]
30
- return qa_data
31
-
32
- qa_data = generate_qa_pairs(raw_text)
33
-
34
- # Save data as JSON
35
- os.makedirs("data", exist_ok=True)
36
- with open("data/train.json", "w") as f:
37
- json.dump(qa_data, f)
38
-
39
- # Load as Hugging Face Dataset
40
- dataset = Dataset.from_dict({"context": [d["context"] for d in qa_data],
41
- "question": [d["question"] for d in qa_data],
42
- "answers": [d["answers"] for d in qa_data]})
43
-
44
- # 2. Load Pretrained Model and Tokenizer
45
- model_name = "distilbert-base-cased"
46
- tokenizer = AutoTokenizer.from_pretrained(model_name)
47
- model = AutoModelForQuestionAnswering.from_pretrained(model_name)
48
-
49
- # 3. Tokenize Dataset
50
- def preprocess_data(examples):
51
- inputs = tokenizer(
52
- examples["question"], examples["context"], truncation=True, padding="max_length", max_length=384
53
- )
54
- offset_mapping = inputs.pop("offset_mapping")
55
- start_positions = []
56
- end_positions = []
57
-
58
- for i, offsets in enumerate(offset_mapping):
59
- answer = examples["answers"][i]
60
- start_char = answer["answer_start"][0]
61
- end_char = start_char + len(answer["text"][0])
62
-
63
- sequence_ids = inputs.sequence_ids(i)
64
- context_start = sequence_ids.index(1)
65
- context_end = len(sequence_ids) - sequence_ids[::-1].index(1) - 1
66
-
67
- if start_char < offsets[context_start][0] or end_char > offsets[context_end][1]:
68
- start_positions.append(0)
69
- end_positions.append(0)
70
- else:
71
- start_positions.append(sequence_ids.index(1, context_start, context_end))
72
- end_positions.append(sequence_ids.index(1, start_positions[-1] + 1, context_end))
73
-
74
- inputs["start_positions"] = start_positions
75
- inputs["end_positions"] = end_positions
76
- return inputs
77
 
78
- tokenized_dataset = dataset.map(preprocess_data, batched=True)
 
79
 
80
- # 4. Training Arguments
81
- training_args = TrainingArguments(
82
- output_dir="./qa_model",
83
- evaluation_strategy="epoch",
84
- learning_rate=2e-5,
85
- per_device_train_batch_size=4,
86
- num_train_epochs=3,
87
- weight_decay=0.01,
88
- save_strategy="epoch",
89
- )
90
 
91
- # 5. Trainer Initialization
92
- trainer = Trainer(
93
- model=model,
94
- args=training_args,
95
- train_dataset=tokenized_dataset,
96
- tokenizer=tokenizer,
97
- )
98
 
99
- # 6. Train the Model
100
- trainer.train()
101
 
102
- # Save the fine-tuned model
103
- model.save_pretrained("./qa_model")
104
- tokenizer.save_pretrained("./qa_model")
 
1
+ import torch
2
+ from transformers import AutoTokenizer, AutoModelForQuestionAnswering
 
 
3
 
4
+ # Load model and tokenizer
5
+ model_name = "distilbert-base-cased-distilled-squad"
6
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
7
+ model = AutoModelForQuestionAnswering.from_pretrained(model_name)
8
+
9
+ # Example text
10
+ context = """BOOK I. Concerning Discipline.
11
  The end of Sciences; association with the aged; restraint of
12
  the organs of sense; the creation of ministers; the creation of
13
  councillors and priests; ascertaining by temptations purity or
 
17
  an enemy's state; the business of council meeting; the mission of
18
  envoys; protection of princes; the conduct of a prince kept under
19
  restraint; treatment of a prince kept under restraint; the duties of a
20
+ king; duty towards the harem; personal safety."""
21
+ question = "What is the end of Sciences?"
22
+
23
+ # Tokenize input
24
+ inputs = tokenizer(
25
+ question,
26
+ context,
27
+ return_tensors="pt",
28
+ truncation=True,
29
+ padding=True,
30
+ max_length=512,
31
+ return_offsets_mapping=True # Ensure this is included
32
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
+ # Perform inference
35
+ outputs = model(**inputs)
36
 
37
+ # Get start and end logits
38
+ start_logits = outputs.start_logits
39
+ end_logits = outputs.end_logits
 
 
 
 
 
 
 
40
 
41
+ # Find the answer
42
+ start_index = torch.argmax(start_logits)
43
+ end_index = torch.argmax(end_logits)
 
 
 
 
44
 
45
+ # Decode answer
46
+ answer = tokenizer.decode(inputs['input_ids'][0][start_index:end_index + 1])
47
 
48
+ # Print the result
49
+ print(f"Question: {question}")
50
+ print(f"Answer: {answer}")