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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pickle
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import pipeline
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Set device
|
| 8 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 9 |
+
print(f"Using device: {device}")
|
| 10 |
+
|
| 11 |
+
# Load the pickled model and tokenizer
|
| 12 |
+
def load_model():
|
| 13 |
+
try:
|
| 14 |
+
# Load from pickle files
|
| 15 |
+
with open('summarization_model.pkl', 'rb') as f:
|
| 16 |
+
model = pickle.load(f)
|
| 17 |
+
|
| 18 |
+
with open('tokenizer.pkl', 'rb') as f:
|
| 19 |
+
tokenizer = pickle.load(f)
|
| 20 |
+
|
| 21 |
+
print("β Model and tokenizer loaded from pickle files")
|
| 22 |
+
|
| 23 |
+
# Create summarization pipeline
|
| 24 |
+
summarizer = pipeline(
|
| 25 |
+
"summarization",
|
| 26 |
+
model=model,
|
| 27 |
+
tokenizer=tokenizer,
|
| 28 |
+
device=0 if torch.cuda.is_available() else -1
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
return summarizer
|
| 32 |
+
|
| 33 |
+
except FileNotFoundError:
|
| 34 |
+
print("Pickle files not found, trying to load from directory...")
|
| 35 |
+
try:
|
| 36 |
+
# Fallback: try loading from directory
|
| 37 |
+
summarizer = pipeline(
|
| 38 |
+
"summarization",
|
| 39 |
+
model="./summarization_model",
|
| 40 |
+
device=0 if torch.cuda.is_available() else -1
|
| 41 |
+
)
|
| 42 |
+
print("β Model loaded from directory")
|
| 43 |
+
return summarizer
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"Error loading model: {e}")
|
| 46 |
+
return None
|
| 47 |
+
|
| 48 |
+
# Load model at startup
|
| 49 |
+
summarizer = load_model()
|
| 50 |
+
|
| 51 |
+
def summarize_text(
|
| 52 |
+
text,
|
| 53 |
+
max_length=128,
|
| 54 |
+
min_length=30,
|
| 55 |
+
temperature=1.0,
|
| 56 |
+
top_p=1.0,
|
| 57 |
+
top_k=50,
|
| 58 |
+
do_sample=True,
|
| 59 |
+
num_beams=4,
|
| 60 |
+
repetition_penalty=1.0,
|
| 61 |
+
length_penalty=1.0
|
| 62 |
+
):
|
| 63 |
+
"""
|
| 64 |
+
Summarize the input text with customizable parameters
|
| 65 |
+
"""
|
| 66 |
+
if summarizer is None:
|
| 67 |
+
return "Error: Model not loaded. Please check model files."
|
| 68 |
+
|
| 69 |
+
if not text.strip():
|
| 70 |
+
return "Please enter some text to summarize."
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
# Generate summary with parameters
|
| 74 |
+
summary = summarizer(
|
| 75 |
+
text,
|
| 76 |
+
max_length=int(max_length),
|
| 77 |
+
min_length=int(min_length),
|
| 78 |
+
temperature=float(temperature),
|
| 79 |
+
top_p=float(top_p),
|
| 80 |
+
top_k=int(top_k),
|
| 81 |
+
do_sample=do_sample,
|
| 82 |
+
num_beams=int(num_beams),
|
| 83 |
+
repetition_penalty=float(repetition_penalty),
|
| 84 |
+
length_penalty=float(length_penalty),
|
| 85 |
+
truncation=True
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
return summary[0]['summary_text']
|
| 89 |
+
|
| 90 |
+
except Exception as e:
|
| 91 |
+
return f"Error generating summary: {str(e)}"
|
| 92 |
+
|
| 93 |
+
def analyze_text(text):
|
| 94 |
+
"""
|
| 95 |
+
Analyze the input text and provide statistics
|
| 96 |
+
"""
|
| 97 |
+
if not text.strip():
|
| 98 |
+
return "No text provided"
|
| 99 |
+
|
| 100 |
+
words = len(text.split())
|
| 101 |
+
sentences = len(text.split('.'))
|
| 102 |
+
chars = len(text)
|
| 103 |
+
|
| 104 |
+
analysis = f"""
|
| 105 |
+
π Text Analysis:
|
| 106 |
+
β’ Words: {words}
|
| 107 |
+
β’ Sentences: {sentences}
|
| 108 |
+
β’ Characters: {chars}
|
| 109 |
+
β’ Average words per sentence: {words/sentences:.1f} (if sentences > 0 else 0)
|
| 110 |
+
β’ Estimated reading time: {words/200:.1f} minutes (200 words/minute)
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
return analysis.strip()
|
| 114 |
+
|
| 115 |
+
# Create Gradio interface
|
| 116 |
+
with gr.Blocks(title="Text Summarization with T5", theme=gr.themes.Soft()) as demo:
|
| 117 |
+
|
| 118 |
+
gr.Markdown("""
|
| 119 |
+
# π€ Advanced Text Summarization
|
| 120 |
+
## Powered by Fine-tuned T5 Model
|
| 121 |
+
|
| 122 |
+
This app uses a custom-trained T5 model for abstractive text summarization.
|
| 123 |
+
Upload your text and get concise, coherent summaries with advanced controls.
|
| 124 |
+
""")
|
| 125 |
+
|
| 126 |
+
with gr.Row():
|
| 127 |
+
with gr.Column(scale=2):
|
| 128 |
+
gr.Markdown("### π Input Text")
|
| 129 |
+
text_input = gr.Textbox(
|
| 130 |
+
label="Enter text to summarize",
|
| 131 |
+
placeholder="Paste your article or text here...",
|
| 132 |
+
lines=10,
|
| 133 |
+
max_lines=20
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
analyze_btn = gr.Button("π Analyze Text", variant="secondary")
|
| 137 |
+
analysis_output = gr.Textbox(
|
| 138 |
+
label="Text Analysis",
|
| 139 |
+
interactive=False,
|
| 140 |
+
lines=5
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
with gr.Column(scale=2):
|
| 144 |
+
gr.Markdown("### βοΈ Advanced Parameters")
|
| 145 |
+
|
| 146 |
+
with gr.Row():
|
| 147 |
+
max_length = gr.Slider(
|
| 148 |
+
minimum=50, maximum=300, value=128, step=10,
|
| 149 |
+
label="Max Summary Length"
|
| 150 |
+
)
|
| 151 |
+
min_length = gr.Slider(
|
| 152 |
+
minimum=10, maximum=100, value=30, step=5,
|
| 153 |
+
label="Min Summary Length"
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
with gr.Row():
|
| 157 |
+
temperature = gr.Slider(
|
| 158 |
+
minimum=0.1, maximum=2.0, value=1.0, step=0.1,
|
| 159 |
+
label="Temperature (Creativity)"
|
| 160 |
+
)
|
| 161 |
+
top_p = gr.Slider(
|
| 162 |
+
minimum=0.1, maximum=1.0, value=1.0, step=0.05,
|
| 163 |
+
label="Top-p (Nucleus Sampling)"
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
with gr.Row():
|
| 167 |
+
top_k = gr.Slider(
|
| 168 |
+
minimum=1, maximum=100, value=50, step=5,
|
| 169 |
+
label="Top-k"
|
| 170 |
+
)
|
| 171 |
+
num_beams = gr.Slider(
|
| 172 |
+
minimum=1, maximum=8, value=4, step=1,
|
| 173 |
+
label="Num Beams (Beam Search)"
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
with gr.Row():
|
| 177 |
+
repetition_penalty = gr.Slider(
|
| 178 |
+
minimum=1.0, maximum=2.0, value=1.0, step=0.1,
|
| 179 |
+
label="Repetition Penalty"
|
| 180 |
+
)
|
| 181 |
+
length_penalty = gr.Slider(
|
| 182 |
+
minimum=0.5, maximum=2.0, value=1.0, step=0.1,
|
| 183 |
+
label="Length Penalty"
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
do_sample = gr.Checkbox(
|
| 187 |
+
value=True,
|
| 188 |
+
label="Use Sampling (vs Greedy Decoding)"
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
summarize_btn = gr.Button("π Generate Summary", variant="primary", size="lg")
|
| 192 |
+
|
| 193 |
+
with gr.Row():
|
| 194 |
+
summary_output = gr.Textbox(
|
| 195 |
+
label="π Generated Summary",
|
| 196 |
+
interactive=False,
|
| 197 |
+
lines=8,
|
| 198 |
+
max_lines=15
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
# Event handlers
|
| 202 |
+
analyze_btn.click(
|
| 203 |
+
fn=analyze_text,
|
| 204 |
+
inputs=text_input,
|
| 205 |
+
outputs=analysis_output
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
summarize_btn.click(
|
| 209 |
+
fn=summarize_text,
|
| 210 |
+
inputs=[
|
| 211 |
+
text_input,
|
| 212 |
+
max_length,
|
| 213 |
+
min_length,
|
| 214 |
+
temperature,
|
| 215 |
+
top_p,
|
| 216 |
+
top_k,
|
| 217 |
+
do_sample,
|
| 218 |
+
num_beams,
|
| 219 |
+
repetition_penalty,
|
| 220 |
+
length_penalty
|
| 221 |
+
],
|
| 222 |
+
outputs=summary_output
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
# Examples
|
| 226 |
+
gr.Examples(
|
| 227 |
+
examples=[
|
| 228 |
+
["Artificial intelligence (AI) has revolutionized numerous industries in recent years. From healthcare to finance, AI systems are now capable of performing tasks that once required human intelligence. Machine learning algorithms can analyze vast amounts of data to identify patterns and make predictions. Natural language processing enables computers to understand and generate human language. Computer vision allows machines to interpret and understand visual information from the world. Despite these advances, concerns about AI ethics, bias, and job displacement remain significant challenges that society must address as the technology continues to evolve."],
|
| 229 |
+
["The COVID-19 pandemic has had a profound impact on global health and economies. Countries worldwide implemented lockdowns and social distancing measures to curb the spread of the virus. Healthcare systems were overwhelmed, and millions of lives were lost. Economic activities came to a standstill, leading to widespread unemployment and financial hardship. Vaccination campaigns were launched globally, providing hope for controlling the pandemic. However, new variants continue to emerge, requiring ongoing vigilance and adaptation of public health strategies."],
|
| 230 |
+
["Climate change represents one of the most significant challenges facing humanity. Rising global temperatures are causing extreme weather events, sea level rise, and ecosystem disruption. The burning of fossil fuels, deforestation, and industrial activities are major contributors to greenhouse gas emissions. International agreements like the Paris Accord aim to limit global warming to well below 2 degrees Celsius. Renewable energy sources such as solar and wind power offer sustainable alternatives. Individual actions, corporate responsibility, and government policies are all crucial in addressing this global crisis."]
|
| 231 |
+
],
|
| 232 |
+
inputs=text_input
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
gr.Markdown("""
|
| 236 |
+
### π― Parameter Guide:
|
| 237 |
+
- **Temperature**: Higher values (1.0+) increase creativity, lower values (0.1-0.5) make output more focused
|
| 238 |
+
- **Top-p**: Nucleus sampling - considers tokens with cumulative probability up to p
|
| 239 |
+
- **Top-k**: Limits sampling to top k most likely tokens
|
| 240 |
+
- **Num Beams**: Beam search width - higher values improve quality but slower
|
| 241 |
+
- **Repetition Penalty**: Reduces repetition (1.0 = no penalty, >1.0 = penalty)
|
| 242 |
+
- **Length Penalty**: Encourages longer (>1.0) or shorter (<1.0) summaries
|
| 243 |
+
|
| 244 |
+
### π Model Info:
|
| 245 |
+
- **Base Model**: T5-small fine-tuned on CNN/DailyMail dataset
|
| 246 |
+
- **Task**: Abstractive text summarization
|
| 247 |
+
- **Training**: Custom fine-tuning with ROUGE optimization
|
| 248 |
+
""")
|
| 249 |
+
|
| 250 |
+
if __name__ == "__main__":
|
| 251 |
+
# Launch the app
|
| 252 |
+
demo.launch(
|
| 253 |
+
server_name="0.0.0.0",
|
| 254 |
+
server_port=int(os.environ.get("PORT", 7860)),
|
| 255 |
+
share=False,
|
| 256 |
+
show_error=True
|
| 257 |
+
)
|