TheOCEAN commited on
Commit
7eae1fe
Β·
verified Β·
1 Parent(s): 0ad897c

Updated app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -25
app.py CHANGED
@@ -1,10 +1,10 @@
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
@@ -12,42 +12,50 @@ model_cache = {
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(
@@ -60,22 +68,19 @@ def summarize_text(text):
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
 
 
1
  import gradio as gr
2
  from transformers import PegasusForConditionalGeneration, PegasusTokenizer
3
  import torch
4
+ from huggingface_hub import hf_hub_download
5
  import os
6
 
7
+ # --- Global cache for the model ---
 
8
  model_cache = {
9
  "model": None,
10
  "tokenizer": None
 
12
 
13
  # --- Function to Load the Model (only runs once) ---
14
  def load_model():
15
+ """Loads the quantized model and tokenizer if they are not already loaded."""
16
+ if model_cache["model"] is None:
17
+ print("--- LAZY LOADING QUANTIZED MODEL (First Request) ---")
 
18
  try:
19
+ # This now points to the final, smaller, quantized model repository
20
+ model_repo_id = "TheOCEAN/My_Text_Summarizer_Quantized"
21
  print(f"⬇️ Loading model and tokenizer from '{model_repo_id}'...")
22
 
23
+ # 1. Load the tokenizer
24
  tokenizer = PegasusTokenizer.from_pretrained(model_repo_id)
 
 
25
 
26
+ # 2. Create the base model structure
27
+ model = PegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum")
28
+
29
+ # 3. Apply the same quantization structure to the base model
30
+ model = torch.quantization.quantize_dynamic(
31
+ model, {torch.nn.Linear}, dtype=torch.qint8
32
+ )
33
+
34
+ # 4. Download and load your fine-tuned quantized weights
35
+ weights_path = hf_hub_download(repo_id=model_repo_id, filename="quantized_weights.pth")
36
+ model.load_state_dict(torch.load(weights_path, map_location="cpu"))
37
+
38
+ model.to(torch.device("cpu"))
39
+
40
  model_cache["model"] = model
41
  model_cache["tokenizer"] = tokenizer
42
 
43
+ print("βœ… Quantized model and tokenizer loaded successfully.")
44
  except Exception as e:
45
  print(f"❌❌❌ FATAL ERROR DURING MODEL LOADING: {e} ❌❌❌")
46
+ raise gr.Error("Model failed to load. Please check the Space logs.")
 
47
 
48
  return model_cache["model"], model_cache["tokenizer"]
49
 
50
+ # --- The core summarization function for the API ---
51
  def summarize_text(text):
52
  """Takes text input and returns a summary."""
53
  if not text or not text.strip():
54
  return "Please provide some text to summarize."
55
 
56
  try:
 
57
  model, tokenizer = load_model()
58
 
 
59
  inputs = tokenizer(text, max_length=1024, truncation=True, return_tensors="pt")
60
 
61
  summary_ids = model.generate(
 
68
  return summary
69
  except Exception as e:
70
  print(f"Error during summarization: {e}")
 
71
  return f"An error occurred during processing: {e}"
72
 
73
  # --- Create and launch the Gradio Interface ---
74
+ # The api_name allows us to call this function like a REST API
 
75
  demo = gr.Interface(
76
  fn=summarize_text,
77
+ inputs=gr.Textbox(lines=15, placeholder="Enter text to summarize..."),
78
  outputs="text",
79
+ title="AI Text Summarizer (Quantized)",
80
+ description="This demo uses a smaller, faster, quantized version of the fine-tuned Pegasus model.",
81
+ api_name="summarize"
82
  )
83
 
84
  if __name__ == "__main__":
 
 
85
  demo.launch()
86