awacke1 commited on
Commit
5fa7137
·
verified ·
1 Parent(s): 9519596

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -35
app.py CHANGED
@@ -1,8 +1,15 @@
1
  import gradio as gr
2
- import os
3
  from transformers import pipeline
 
4
 
5
- title = "📗Health and Mindful Story Gen❤️"
 
 
 
 
 
 
6
 
7
  # Define the examples to show in the interface
8
  examples = [
@@ -14,16 +21,16 @@ examples = [
14
  ["Alleviating stress"],
15
  ["Helping breathing, satisfaction"],
16
  ["Relieve Stress, Build Support"],
17
- ["Relaxation Response"],
18
- ["Deep Breaths"],
19
  ["Delete Not Helpful Thoughts"],
20
- ["Strengthen Helpful"],
21
- ["Reprogram Pain Stress Reactions"],
22
- ["Sleep Better and Find Joy"],
23
- ["Yoga Sleep"],
24
  ["Being a Happier and Healthier Person"],
25
- ["Relieve Pain"],
26
- ["Learn to Use Mindfulness to Affect Well Being"],
27
  ["Build and Boost Mental Strength"],
28
  ["Spending Time Outdoors"],
29
  ["Daily Routine Tasks"],
@@ -33,41 +40,92 @@ examples = [
33
  ["Feel better physically by"],
34
  ["Practicing mindfulness each day"],
35
  ["Be happier by"],
36
- ["Meditation can improve health"],
37
- ["Spending time outdoors"],
38
  ["Stress is relieved by quieting your mind, getting exercise and time with nature"],
39
  ["Break the cycle of stress and anxiety"],
40
  ["Feel calm in stressful situations"],
41
- ["Deal with work pressure"],
42
- ["Learn to reduce feelings of overwhelmed"]
43
  ]
44
 
45
- # Initialize the models using Hugging Face pipelines
46
- generator1 = pipeline("text-generation", model="gpt2-large")
47
- generator2 = pipeline("text-generation", model="EleutherAI/gpt-neo-2.7B")
48
- generator3 = pipeline("text-generation", model="EleutherAI/gpt-j-6B")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- with gr.Blocks() as demo:
51
- gr.Markdown(f"# {title}")
52
- input_textbox = gr.Textbox(lines=5, label="Enter a sentence to get another sentence.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  with gr.Row():
55
- gen1_output = gr.Textbox(label="GPT-2 Large Output")
56
- gen2_output = gr.Textbox(label="GPT-Neo Output")
57
- gen3_output = gr.Textbox(label="GPT-J Output")
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
- def generate_outputs(input_text):
60
- out1 = generator1(input_text, max_length=50)[0]['generated_text']
61
- out2 = generator2(input_text, max_length=50)[0]['generated_text']
62
- out3 = generator3(input_text, max_length=50)[0]['generated_text']
63
- return out1, out2, out3
64
 
65
- gr.Button("Generate").click(
66
  fn=generate_outputs,
67
- inputs=input_textbox,
68
- outputs=[gen1_output, gen2_output, gen3_output]
 
69
  )
70
 
71
- gr.Examples(examples=examples, inputs=input_textbox, examples_per_page=100)
72
-
73
- demo.launch(share=False)
 
1
  import gradio as gr
2
+ import torch
3
  from transformers import pipeline
4
+ import os
5
 
6
+ # --- App Configuration ---
7
+ title = "📗 Health and Mindful Story Gen ❤️"
8
+ description = """
9
+ Enter a topic or a starting sentence related to health, mindfulness, or well-being.
10
+ The app will generate continuations from three different language models.
11
+ **Note:** These models are very large. Initial loading and first-time generation may take a few minutes.
12
+ """
13
 
14
  # Define the examples to show in the interface
15
  examples = [
 
21
  ["Alleviating stress"],
22
  ["Helping breathing, satisfaction"],
23
  ["Relieve Stress, Build Support"],
24
+ ["The Relaxation Response"],
25
+ ["Taking Deep Breaths"],
26
  ["Delete Not Helpful Thoughts"],
27
+ ["Strengthen Helpful Thoughts"],
28
+ ["Reprogram Pain and Stress Reactions"],
29
+ ["How to Sleep Better and Find Joy"],
30
+ ["Yoga for deep sleep"],
31
  ["Being a Happier and Healthier Person"],
32
+ ["Relieve chronic pain by"],
33
+ ["Use Mindfulness to Affect Well Being"],
34
  ["Build and Boost Mental Strength"],
35
  ["Spending Time Outdoors"],
36
  ["Daily Routine Tasks"],
 
40
  ["Feel better physically by"],
41
  ["Practicing mindfulness each day"],
42
  ["Be happier by"],
43
+ ["Meditation can improve health by"],
44
+ ["Spending time outdoors helps to"],
45
  ["Stress is relieved by quieting your mind, getting exercise and time with nature"],
46
  ["Break the cycle of stress and anxiety"],
47
  ["Feel calm in stressful situations"],
48
+ ["Deal with work pressure by"],
49
+ ["Learn to reduce feelings of being overwhelmed"]
50
  ]
51
 
52
+ # --- Model Initialization ---
53
+ # WARNING: Loading these models requires significant hardware (ideally a GPU with >24GB VRAM).
54
+ # 'device_map="auto"' and 'torch_dtype' require the 'accelerate' library.
55
+ # Install dependencies: pip install gradio transformers torch accelerate
56
+ try:
57
+ print("Initializing models... This may take several minutes.")
58
+
59
+ # Using device_map="auto" to automatically use available GPUs.
60
+ # Using torch_dtype="auto" to load models in half-precision (float16/bfloat16) to save memory.
61
+
62
+ generator1 = pipeline("text-generation", model="gpt2-large", device_map="auto")
63
+ print("GPT-2 Large loaded.")
64
+
65
+ generator2 = pipeline("text-generation", model="EleutherAI/gpt-neo-2.7B", torch_dtype="auto", device_map="auto")
66
+ print("GPT-Neo 2.7B loaded.")
67
+
68
+ generator3 = pipeline("text-generation", model="EleutherAI/gpt-j-6B", torch_dtype="auto", device_map="auto")
69
+ print("GPT-J 6B loaded.")
70
+
71
+ print("All models loaded successfully! ✅")
72
+
73
+ except Exception as e:
74
+ print(f"Error loading models: {e}")
75
+ print("Please ensure you have 'torch' and 'accelerate' installed and have sufficient VRAM.")
76
+ # Create dummy functions if models fail to load, so the app can still launch.
77
+ def failed_generator(prompt, **kwargs):
78
+ return [{'generated_text': "Model failed to load. Check console for errors."}]
79
+ generator1 = generator2 = generator3 = failed_generator
80
 
81
+
82
+ # --- App Logic ---
83
+ def generate_outputs(input_text: str) -> tuple[str, str, str]:
84
+ """Generates text from the three loaded models."""
85
+ # Using 'max_new_tokens' is preferred over 'max_length' to specify the length of the generated text only.
86
+ params = {"max_new_tokens": 60, "num_return_sequences": 1}
87
+
88
+ out1 = generator1(input_text, **params)[0]['generated_text']
89
+ out2 = generator2(input_text, **params)[0]['generated_text']
90
+ out3 = generator3(input_text, **params)[0]['generated_text']
91
+
92
+ return out1, out2, out3
93
+
94
+ # --- Gradio Interface ---
95
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
96
+ gr.Markdown(f"<h1 style='text-align: center;'>{title}</h1>")
97
+ gr.Markdown(description)
98
 
99
  with gr.Row():
100
+ with gr.Column(scale=1):
101
+ input_area = gr.TextArea(
102
+ lines=3,
103
+ label="Your starting prompt 👇",
104
+ placeholder="e.g., 'To relieve stress, I will try...'"
105
+ )
106
+ generate_button = gr.Button("Generate ✨", variant="primary")
107
+
108
+ with gr.Column(scale=2):
109
+ with gr.Tabs():
110
+ with gr.TabItem("GPT-2 Large"):
111
+ gen1_output = gr.TextArea(label="GPT-2 Large Output", interactive=False, lines=7)
112
+ with gr.TabItem("GPT-Neo 2.7B"):
113
+ gen2_output = gr.TextArea(label="GPT-Neo 2.7B Output", interactive=False, lines=7)
114
+ with gr.TabItem("GPT-J 6B"):
115
+ gen3_output = gr.TextArea(label="GPT-J 6B Output", interactive=False, lines=7)
116
 
117
+ gr.Examples(
118
+ examples=examples,
119
+ inputs=input_area,
120
+ label="Example Prompts (Click to use)"
121
+ )
122
 
123
+ generate_button.click(
124
  fn=generate_outputs,
125
+ inputs=input_area,
126
+ outputs=[gen1_output, gen2_output, gen3_output],
127
+ api_name="generate"
128
  )
129
 
130
+ if __name__ == "__main__":
131
+ demo.launch()