Spaces:
Sleeping
Sleeping
Updated app.py
Browse files
app.py
CHANGED
|
@@ -1,63 +1,53 @@
|
|
| 1 |
-
|
| 2 |
from transformers import PegasusForConditionalGeneration, PegasusTokenizer
|
| 3 |
import torch
|
| 4 |
import os
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
# ---
|
| 10 |
-
# We will load these lazily (on the first request) to avoid startup timeouts.
|
| 11 |
-
model = None
|
| 12 |
-
tokenizer = None
|
| 13 |
-
model_loaded = False
|
| 14 |
-
|
| 15 |
-
# --- Function to Load the Model ---
|
| 16 |
def load_model():
|
| 17 |
-
"""Loads the model and tokenizer
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
# ---
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
# If the model isn't loaded yet, load it now.
|
| 46 |
-
# This happens only on the very first request.
|
| 47 |
-
if not model_loaded:
|
| 48 |
-
load_model()
|
| 49 |
|
| 50 |
-
# If loading failed, return an error.
|
| 51 |
-
if not model or not tokenizer:
|
| 52 |
-
return jsonify({'error': 'Model is not available. Check server logs for loading errors.'}), 503
|
| 53 |
-
|
| 54 |
try:
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
# Use the loaded model and tokenizer to summarize
|
| 61 |
inputs = tokenizer(text, max_length=1024, truncation=True, return_tensors="pt")
|
| 62 |
|
| 63 |
summary_ids = model.generate(
|
|
@@ -67,23 +57,25 @@ def summarize_endpoint():
|
|
| 67 |
early_stopping=True
|
| 68 |
)
|
| 69 |
summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
|
| 70 |
-
|
| 71 |
-
return jsonify({'summary': summary})
|
| 72 |
-
|
| 73 |
except Exception as e:
|
| 74 |
-
print(f"
|
| 75 |
-
|
|
|
|
| 76 |
|
| 77 |
-
# ---
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
#
|
| 86 |
-
|
| 87 |
-
port = int(os.environ.get("PORT", 7860))
|
| 88 |
-
app.run(host='0.0.0.0', port=port)
|
| 89 |
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
from transformers import PegasusForConditionalGeneration, PegasusTokenizer
|
| 3 |
import torch
|
| 4 |
import os
|
| 5 |
|
| 6 |
+
# --- Global variables to cache the model ---
|
| 7 |
+
# We use a dictionary to hold the model and tokenizer to manage state.
|
| 8 |
+
model_cache = {
|
| 9 |
+
"model": None,
|
| 10 |
+
"tokenizer": None
|
| 11 |
+
}
|
| 12 |
|
| 13 |
+
# --- Function to Load the Model (only runs once) ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def load_model():
|
| 15 |
+
"""Loads the model and tokenizer if they are not already loaded."""
|
| 16 |
+
# This check prevents reloading on every request
|
| 17 |
+
if model_cache["model"] is None or model_cache["tokenizer"] is None:
|
| 18 |
+
print("--- LAZY LOADING MODEL (First Request) ---")
|
| 19 |
+
try:
|
| 20 |
+
# This points to the NEW repository with the corrected model files.
|
| 21 |
+
model_repo_id = "TheOCEAN/My_Text_Summarizer_Portable"
|
| 22 |
+
print(f"β¬οΈ Loading model and tokenizer from '{model_repo_id}'...")
|
| 23 |
+
|
| 24 |
+
tokenizer = PegasusTokenizer.from_pretrained(model_repo_id)
|
| 25 |
+
model = PegasusForConditionalGeneration.from_pretrained(model_repo_id)
|
| 26 |
+
model.to(torch.device("cpu")) # Ensure it runs on CPU
|
| 27 |
+
|
| 28 |
+
# Store the loaded model and tokenizer in our cache
|
| 29 |
+
model_cache["model"] = model
|
| 30 |
+
model_cache["tokenizer"] = tokenizer
|
| 31 |
+
|
| 32 |
+
print("β
Model and tokenizer loaded successfully.")
|
| 33 |
+
except Exception as e:
|
| 34 |
+
print(f"βββ FATAL ERROR DURING MODEL LOADING: {e} βββ")
|
| 35 |
+
# Raise a Gradio-specific error that will be shown in the UI
|
| 36 |
+
raise gr.Error("Model failed to load. Please check the Space logs for details.")
|
| 37 |
+
|
| 38 |
+
return model_cache["model"], model_cache["tokenizer"]
|
| 39 |
|
| 40 |
+
# --- The core summarization function that Gradio will expose as an API ---
|
| 41 |
+
def summarize_text(text):
|
| 42 |
+
"""Takes text input and returns a summary."""
|
| 43 |
+
if not text or not text.strip():
|
| 44 |
+
return "Please provide some text to summarize."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
try:
|
| 47 |
+
# Load the model (or get it from the cache if already loaded)
|
| 48 |
+
model, tokenizer = load_model()
|
| 49 |
+
|
| 50 |
+
# Tokenize and generate the summary
|
|
|
|
|
|
|
| 51 |
inputs = tokenizer(text, max_length=1024, truncation=True, return_tensors="pt")
|
| 52 |
|
| 53 |
summary_ids = model.generate(
|
|
|
|
| 57 |
early_stopping=True
|
| 58 |
)
|
| 59 |
summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
|
| 60 |
+
return summary
|
|
|
|
|
|
|
| 61 |
except Exception as e:
|
| 62 |
+
print(f"Error during summarization: {e}")
|
| 63 |
+
# Gradio can handle returning error messages to the API caller
|
| 64 |
+
return f"An error occurred during processing: {e}"
|
| 65 |
|
| 66 |
+
# --- Create and launch the Gradio Interface ---
|
| 67 |
+
# This creates a simple UI on the Space page for testing,
|
| 68 |
+
# and automatically creates a background API endpoint that your local app will call.
|
| 69 |
+
demo = gr.Interface(
|
| 70 |
+
fn=summarize_text,
|
| 71 |
+
inputs=gr.Textbox(lines=15, placeholder="Enter a long text or article to summarize here..."),
|
| 72 |
+
outputs="text",
|
| 73 |
+
title="AI Text Summarizer",
|
| 74 |
+
description="This is a demo of a fine-tuned Pegasus model. The model is loaded on the first request, which may take a few minutes. Subsequent requests will be fast."
|
| 75 |
+
)
|
| 76 |
|
| 77 |
+
if __name__ == "__main__":
|
| 78 |
+
# The launch() command tells Gradio to start the web server.
|
| 79 |
+
# It will automatically use the correct port for Hugging Face Spaces.
|
| 80 |
+
demo.launch()
|
|
|
|
|
|
|
| 81 |
|