22f1001555 commited on
Commit
065beff
·
0 Parent(s):

Deploy conversation summarizer space

Browse files
Files changed (5) hide show
  1. .gitignore +17 -0
  2. README.md +223 -0
  3. app.py +62 -0
  4. model.py +88 -0
  5. requirements.txt +8 -0
.gitignore ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ env/
2
+ **/env/
3
+ __pycache__/
4
+ **/__pycache__/
5
+ *.pyc
6
+ .ipynb_checkpoints/
7
+ results/
8
+ logs/
9
+ .gradio/
10
+
11
+ # model weights / saved local model folders
12
+ *.safetensors
13
+ *.bin
14
+ *.pt
15
+ *.pth
16
+ conversation_summarizer/conversation_summarizer/
17
+ conversation_summarizer/
README.md ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dialogue Summarizer
2
+
3
+ An interactive Gradio app that summarizes chat-style conversations using a fine-tuned `google/flan-t5-small` model from Hugging Face.
4
+
5
+ The model was fine-tuned on the [SAMSum](https://huggingface.co/datasets/knkarthick/samsum) dialogue summarization dataset. Users can paste a conversation, click submit, and receive a short generated summary.
6
+
7
+ ## Demo
8
+
9
+ ```text
10
+ Tom: Did you submit the report?
11
+ Anika: Not yet, I'm fixing the charts.
12
+ Tom: The deadline is 5 pm.
13
+ Anika: I know. I'll send it by 4:30.
14
+ Tom: Great, please copy me on the email.
15
+ ```
16
+
17
+ Expected output:
18
+
19
+ ```text
20
+ Anika is fixing the report charts and will send the report by 4:30, copying Tom.
21
+ ```
22
+
23
+ ## Features
24
+
25
+ - Fine-tuned T5/FLAN-T5 sequence-to-sequence summarization model
26
+ - Simple Gradio web interface
27
+ - Built-in example conversations
28
+ - Beam search generation for better summaries
29
+ - Local model loading from the `conversation_summarizer/` folder
30
+
31
+ ## Project Structure
32
+
33
+ ```text
34
+ conversation_summarizer/
35
+ +-- app.py
36
+ +-- model.py
37
+ +-- requirements.txt
38
+ +-- README.md
39
+ +-- conversation_summarizer/
40
+ +-- config.json
41
+ +-- generation_config.json
42
+ +-- model.safetensors
43
+ +-- spiece.model
44
+ +-- tokenizer_config.json
45
+ +-- special_tokens_map.json
46
+ ```
47
+
48
+ ## Setup
49
+
50
+ Create and activate a virtual environment:
51
+
52
+ ```bash
53
+ python -m venv env
54
+ ```
55
+
56
+ Windows:
57
+
58
+ ```bash
59
+ env\Scripts\activate
60
+ ```
61
+
62
+ macOS/Linux:
63
+
64
+ ```bash
65
+ source env/bin/activate
66
+ ```
67
+
68
+ Install dependencies:
69
+
70
+ ```bash
71
+ pip install -r requirements.txt
72
+ ```
73
+
74
+ ## Run The App
75
+
76
+ ```bash
77
+ python app.py
78
+ ```
79
+
80
+ Gradio will start a local app and print a URL like:
81
+
82
+ ```text
83
+ http://127.0.0.1:7860
84
+ ```
85
+
86
+ Open the URL in your browser and try one of the example conversations.
87
+
88
+ ## Example Inputs
89
+
90
+ ```text
91
+ Nora: Are you picking up the groceries today?
92
+ Eli: Yes, after work.
93
+ Nora: Please get milk, eggs, and bread.
94
+ Eli: Got it. Anything else?
95
+ Nora: Bananas if they look fresh.
96
+ Eli: Okay, I'll be home around 6:30.
97
+ ```
98
+
99
+ ```text
100
+ Priya: Did you call the dentist?
101
+ Karan: Yes, they had an opening tomorrow at 11.
102
+ Priya: Great. Did you book it?
103
+ Karan: Yes, I confirmed it.
104
+ Priya: Thanks. I'll leave work early to go.
105
+ ```
106
+
107
+ ```text
108
+ Sam: The Wi-Fi is down again.
109
+ Lina: I restarted the router, but it didn't help.
110
+ Sam: Should I call the provider?
111
+ Lina: Yes, please. Tell them it stopped working an hour ago.
112
+ Sam: Okay, I'll call them now.
113
+ ```
114
+
115
+ ## Training
116
+
117
+ The training script is in `model.py`.
118
+
119
+ It:
120
+
121
+ 1. Loads the SAMSum dataset.
122
+ 2. Loads `google/flan-t5-small`.
123
+ 3. Tokenizes dialogues as inputs and summaries as labels.
124
+ 4. Fine-tunes the model with `Seq2SeqTrainer`.
125
+ 5. Evaluates with ROUGE.
126
+ 6. Saves the trained model and tokenizer.
127
+
128
+ Run training with:
129
+
130
+ ```bash
131
+ python model.py
132
+ ```
133
+
134
+ Note: training is much faster with a CUDA-enabled GPU.
135
+
136
+ ## Model Notes
137
+
138
+ The app expects a saved Hugging Face model folder at:
139
+
140
+ ```text
141
+ ./conversation_summarizer
142
+ ```
143
+
144
+ This folder should contain files like:
145
+
146
+ ```text
147
+ model.safetensors
148
+ config.json
149
+ spiece.model
150
+ tokenizer_config.json
151
+ generation_config.json
152
+ ```
153
+
154
+ If you retrain the model and save it to another folder, update this line in `app.py`:
155
+
156
+ ```python
157
+ model = T5ForConditionalGeneration.from_pretrained("./conversation_summarizer")
158
+ tokenizer = T5Tokenizer.from_pretrained("./conversation_summarizer")
159
+ ```
160
+
161
+ ## Evaluation
162
+
163
+ The model is evaluated using ROUGE:
164
+
165
+ - `rouge1`: unigram overlap
166
+ - `rouge2`: bigram overlap
167
+ - `rougeL`: longest common subsequence overlap
168
+ - `rougeLsum`: summarization-oriented ROUGE-L
169
+
170
+ ROUGE scores usually range from `0` to `1`, where higher is better.
171
+
172
+ ## Before Pushing To GitHub
173
+
174
+ Do not commit the local virtual environment:
175
+
176
+ ```text
177
+ env/
178
+ ```
179
+
180
+ If the model file is large, consider using Git LFS or uploading the model to the Hugging Face Hub instead of committing `model.safetensors` directly.
181
+
182
+ Recommended `.gitignore`:
183
+
184
+ ```gitignore
185
+ env/
186
+ __pycache__/
187
+ *.pyc
188
+ .ipynb_checkpoints/
189
+ results/
190
+ logs/
191
+ ```
192
+
193
+ ## Git Commands
194
+
195
+ Initialize the repo:
196
+
197
+ ```bash
198
+ git init
199
+ git add app.py model.py requirements.txt README.md conversation_summarizer/
200
+ git commit -m "Add dialogue summarizer app"
201
+ ```
202
+
203
+ Connect to GitHub:
204
+
205
+ ```bash
206
+ git branch -M main
207
+ git remote add origin https://github.com/YOUR_USERNAME/YOUR_REPO_NAME.git
208
+ git push -u origin main
209
+ ```
210
+
211
+ ## Tech Stack
212
+
213
+ - Python
214
+ - Hugging Face Transformers
215
+ - Hugging Face Datasets
216
+ - Evaluate
217
+ - ROUGE
218
+ - Gradio
219
+ - FLAN-T5
220
+
221
+ ## Limitations
222
+
223
+ This is a small fine-tuned model, so it may occasionally miss details or infer something incorrectly. It works best when the dialogue clearly identifies speakers, actions, and decisions.
app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import T5ForConditionalGeneration, T5Tokenizer
2
+ import gradio as gr
3
+
4
+ model = T5ForConditionalGeneration.from_pretrained("abhi-codes/finetuned_flank_t5_for_summarization")
5
+ tokenizer = T5Tokenizer.from_pretrained("abhi-codes/finetuned_flank_t5_for_summarization")
6
+
7
+ examples = [
8
+ ["""Tom: Did you submit the report?
9
+ Anika: Not yet, I'm fixing the charts.
10
+ Tom: The deadline is 5 pm.
11
+ Anika: I know. I'll send it by 4:30.
12
+ Tom: Great, please copy me on the email."""],
13
+ ["""Nora: Are you picking up the groceries today?
14
+ Eli: Yes, after work.
15
+ Nora: Please get milk, eggs, and bread.
16
+ Eli: Got it. Anything else?
17
+ Nora: Bananas if they look fresh.
18
+ Eli: Okay, I'll be home around 6:30"""],
19
+ ["""Priya: Did you call the dentist?
20
+ Karan: Yes, they had an opening tomorrow at 11.
21
+ Priya: Great. Did you book it?
22
+ Karan: Yes, I confirmed it.
23
+ Priya: Thanks. I'll leave work early to go."""]
24
+ ]
25
+
26
+
27
+ def summarize(input):
28
+ input = "summarize: "+ input
29
+ model_inputs = tokenizer(input, return_tensors="pt", max_length=512, truncation=True,padding = 'max_length')
30
+ summary_ids = model.generate(
31
+ input_ids=model_inputs["input_ids"],
32
+ attention_mask=model_inputs["attention_mask"],
33
+ max_new_tokens=128,
34
+ num_beams=4,
35
+ no_repeat_ngram_size=3
36
+ )
37
+ return tokenizer.decode(summary_ids[0], skip_special_tokens=True)
38
+
39
+ demo = gr.Interface(
40
+ fn=summarize,
41
+ inputs=[
42
+ gr.Textbox(
43
+ lines=8,
44
+ label="Dialogue",
45
+ placeholder="Paste a conversation here"
46
+ )],
47
+ outputs=[
48
+ gr.Textbox(
49
+ lines=2,
50
+ label="Summary"
51
+ ),
52
+ ],
53
+ title="Dialogue Summarizer",
54
+ description=(
55
+ "Enter a chat-style conversation and the model will generate a short summary. "
56
+ "For best results, write each message on a new line with the speaker name."
57
+ ),
58
+ examples=examples,
59
+ flagging_mode="never"
60
+
61
+ )
62
+ demo.launch()
model.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """hf_workshop_project.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/16rr3KcHT3lyfI2QjUDm720EZjpP8Jw28
8
+ """
9
+
10
+ from datasets import load_dataset
11
+ from transformers import T5Tokenizer,T5ForConditionalGeneration
12
+ from transformers import Seq2SeqTrainingArguments,Seq2SeqTrainer
13
+ import evaluate
14
+ import numpy as np
15
+
16
+ df = load_dataset("knkarthick/samsum")
17
+
18
+ tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-small")
19
+ model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-small",device_map = "auto")
20
+
21
+ def tokenize(data):
22
+ input = ["summarize: "+ text for text in data['dialogue']]
23
+ model_inputs = tokenizer(input,max_length=128,padding='max_length',truncation=True)
24
+ label = tokenizer(data['summary'],max_length=128,padding='max_length',truncation=True)
25
+ model_inputs['labels'] = label['input_ids']
26
+ return model_inputs
27
+
28
+ tokenized_train_data = df['train'].map(tokenize,batched= True)
29
+ tokenized_validation_data = df['validation'].map(tokenize,batched= True)
30
+
31
+ # tokenized_train_data = df['train'].select(range(2000)).map(tokenize,batched= True)
32
+ # tokenized_validation_data = df['validation'].select(range(600)).map(tokenize,batched= True)
33
+
34
+
35
+ training_args = Seq2SeqTrainingArguments(
36
+ output_dir = './results',
37
+ eval_strategy = 'epoch',
38
+ learning_rate = 3e-5,
39
+ per_device_train_batch_size = 8,
40
+ per_device_eval_batch_size = 8,
41
+ num_train_epochs = 10,
42
+ weight_decay = 0.01,
43
+ report_to = "none",
44
+ logging_dir = './logs',
45
+ fp16 = False,
46
+ predict_with_generate= True,
47
+ generation_max_length= 128,
48
+
49
+ )
50
+
51
+ # !pip install evaluate
52
+ # !pip install rouge_score
53
+
54
+
55
+ metric = evaluate.load('rouge')
56
+
57
+ def compute_metrics(eval_pred) :
58
+ preds,labels = eval_pred
59
+
60
+ if isinstance(preds,tuple):
61
+ preds = preds[0]
62
+
63
+ if preds.ndim == 3:
64
+ preds = np.argmax(preds, axis=-1)
65
+
66
+ preds = np.where(preds < 0, tokenizer.pad_token_id, preds)
67
+ decoded_preds = tokenizer.batch_decode(preds,skip_special_tokens= True)
68
+
69
+ labels = np.where(labels !=-100,labels,tokenizer.pad_token_id)
70
+ decoded_labels = tokenizer.batch_decode(labels,skip_special_tokens= True)
71
+
72
+ return metric.compute(predictions=decoded_preds,
73
+ references = decoded_labels,
74
+ use_stemmer = True)
75
+
76
+ trainer = Seq2SeqTrainer(
77
+ model = model,
78
+ train_dataset= tokenized_train_data,
79
+ eval_dataset= tokenized_validation_data,
80
+ args = training_args,
81
+ compute_metrics= compute_metrics
82
+ )
83
+
84
+ trainer.train()
85
+
86
+ save_dir = './summary_model'
87
+ trainer.save_model(save_dir)
88
+ tokenizer.save_pretrained(save_dir)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ transformers==4.43.0
2
+ accelerate==0.33.0
3
+ datasets==2.20.0
4
+ evaluate==0.4.2
5
+ rouge_score
6
+ sentencepiece
7
+ numpy
8
+ gradio