TheOCEAN commited on
Commit
6fb07b3
Β·
verified Β·
1 Parent(s): 9be7aa1

Updated app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -67
app.py CHANGED
@@ -1,63 +1,53 @@
1
- from flask import Flask, request, jsonify
2
  from transformers import PegasusForConditionalGeneration, PegasusTokenizer
3
  import torch
4
  import os
5
 
6
- # Initialize Flask App
7
- app = Flask(__name__)
 
 
 
 
8
 
9
- # --- Global variables for the model and tokenizer ---
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 into the global variables."""
18
- global model, tokenizer, model_loaded
19
-
20
- # This points to the NEW repository with the corrected model files.
21
- model_repo_id = "TheOCEAN/My_Text_Summarizer_Portable"
22
-
23
- print("--- LAZY LOADING MODEL ---")
24
- try:
25
- print(f"⬇️ Loading model and tokenizer from '{model_repo_id}'...")
26
- tokenizer = PegasusTokenizer.from_pretrained(model_repo_id)
27
- model = PegasusForConditionalGeneration.from_pretrained(model_repo_id)
28
-
29
- # Move model to CPU to ensure it works on free tier hardware
30
- model.to(torch.device("cpu"))
31
-
32
- model_loaded = True
33
- print("βœ… Model and tokenizer loaded successfully.")
34
- print("--- Model Loading Complete ---")
35
- except Exception as e:
36
- model_loaded = False
37
- print(f"❌❌❌ FATAL ERROR DURING MODEL LOADING: {e} ❌❌❌")
38
- # This will be visible in the Space logs if something goes wrong.
 
 
39
 
40
- # --- API Route for Summarization ---
41
- @app.route('/summarize', methods=['POST'])
42
- def summarize_endpoint():
43
- global model, tokenizer, model_loaded
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
- json_data = request.get_json()
56
- text = json_data.get('text', '')
57
- if not text:
58
- return jsonify({'error': 'No text provided.'}), 400
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"An error occurred during summarization: {e}")
75
- return jsonify({'error': 'Failed to process the request.'}), 500
 
76
 
77
- # --- Root Route to Confirm Server is Running ---
78
- @app.route('/')
79
- def home():
80
- # This route will respond instantly, satisfying the health check.
81
- return "Summarizer API is running. Model will be loaded on the first /summarize request."
 
 
 
 
 
82
 
83
- # --- Main Execution ---
84
- if __name__ == '__main__':
85
- # We no longer load the model on startup.
86
- # The port needs to be 7860 for Hugging Face Spaces.
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