frankai98 commited on
Commit
05fbc95
·
verified ·
1 Parent(s): 2ee971f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -16
app.py CHANGED
@@ -9,6 +9,7 @@ import io
9
  import time
10
  from streamlit.components.v1 import html
11
  import asyncio
 
12
  if not asyncio.get_event_loop().is_running():
13
  asyncio.set_event_loop(asyncio.new_event_loop())
14
 
@@ -25,11 +26,12 @@ def timer():
25
  return """
26
  <div id="timer" style="font-size:16px;color:#666;margin-bottom:10px;">⏱️ Elapsed: 00:00</div>
27
  <script>
 
28
  function updateTimer() {
29
  var start = Date.now();
30
  var timerElement = document.getElementById('timer');
31
 
32
- var interval = setInterval(function() {
33
  var elapsed = Date.now() - start;
34
  var minutes = Math.floor(elapsed / 60000);
35
  var seconds = Math.floor((elapsed % 60000) / 1000);
@@ -37,17 +39,18 @@ def timer():
37
  (minutes < 10 ? '0' : '') + minutes + ':' +
38
  (seconds < 10 ? '0' : '') + seconds;
39
  }, 1000);
40
-
41
- // Cleanup when component is removed
42
- return function() {
43
- clearInterval(interval);
44
- }
45
  }
46
- var cleanup = updateTimer();
 
 
 
 
 
 
47
 
48
- // Handle Streamlit's component cleanup
49
  window.addEventListener('beforeunload', function() {
50
- cleanup();
51
  });
52
  </script>
53
  """
@@ -61,7 +64,19 @@ st.header("Turn Your Image to a Short Audio Story for Children")
61
  def load_models():
62
  return {
63
  "img_model": pipeline("image-to-text", "cnmoro/tiny-image-captioning"),
64
- "story_model": pipeline("text-generation", "Qwen/Qwen2.5-0.5B-Instruct")
 
 
 
 
 
 
 
 
 
 
 
 
65
  }
66
 
67
  models = load_models()
@@ -136,9 +151,13 @@ if uploaded_file is not None:
136
  )
137
  progress_bar.progress(100)
138
 
139
- # Final status
140
  status_text.success("**✅ Generation complete!**")
141
- html("<script>document.getElementById('timer').style.color = '#00cc00';</script>")
 
 
 
 
142
 
143
  # Show results
144
  st.subheader("Results")
@@ -146,14 +165,16 @@ if uploaded_file is not None:
146
  st.write("**Story:**", st.session_state.processed_data['story'])
147
 
148
  except Exception as e:
149
- html("<script>document.getElementById('timer').remove();</script>")
 
 
 
 
 
150
  status_text.error(f"**❌ Error:** {str(e)}")
151
  progress_bar.empty()
152
  raise e
153
 
154
- finally:
155
- pass # Timer cleanup handled by JavaScript
156
-
157
  # Audio playback
158
  if st.button("Play Audio of the Story Generated"):
159
  if st.session_state.processed_data.get('audio'):
 
9
  import time
10
  from streamlit.components.v1 import html
11
  import asyncio
12
+
13
  if not asyncio.get_event_loop().is_running():
14
  asyncio.set_event_loop(asyncio.new_event_loop())
15
 
 
26
  return """
27
  <div id="timer" style="font-size:16px;color:#666;margin-bottom:10px;">⏱️ Elapsed: 00:00</div>
28
  <script>
29
+ var timerInterval;
30
  function updateTimer() {
31
  var start = Date.now();
32
  var timerElement = document.getElementById('timer');
33
 
34
+ timerInterval = setInterval(function() {
35
  var elapsed = Date.now() - start;
36
  var minutes = Math.floor(elapsed / 60000);
37
  var seconds = Math.floor((elapsed % 60000) / 1000);
 
39
  (minutes < 10 ? '0' : '') + minutes + ':' +
40
  (seconds < 10 ? '0' : '') + seconds;
41
  }, 1000);
 
 
 
 
 
42
  }
43
+ updateTimer();
44
+
45
+ // Listen for custom stop event
46
+ document.addEventListener('stopTimer', function() {
47
+ clearInterval(timerInterval);
48
+ document.getElementById('timer').style.color = '#00cc00';
49
+ });
50
 
51
+ // Cleanup on error or page unload
52
  window.addEventListener('beforeunload', function() {
53
+ clearInterval(timerInterval);
54
  });
55
  </script>
56
  """
 
64
  def load_models():
65
  return {
66
  "img_model": pipeline("image-to-text", "cnmoro/tiny-image-captioning"),
67
+ "story_model": pipeline(
68
+ "text-generation",
69
+ "Qwen/Qwen2.5-0.5B-Instruct",
70
+ device_map="auto",
71
+ model_kwargs={
72
+ "load_in_4bit": True,
73
+ "quantization_config": {
74
+ "load_in_4bit": True,
75
+ "bnb_4bit_compute_dtype": torch.float16,
76
+ "bnb_4bit_quant_type": "nf4"
77
+ }
78
+ }
79
+ )
80
  }
81
 
82
  models = load_models()
 
151
  )
152
  progress_bar.progress(100)
153
 
154
+ # Final status and stop timer
155
  status_text.success("**✅ Generation complete!**")
156
+ html("""
157
+ <script>
158
+ document.dispatchEvent(new Event('stopTimer'));
159
+ </script>
160
+ """)
161
 
162
  # Show results
163
  st.subheader("Results")
 
165
  st.write("**Story:**", st.session_state.processed_data['story'])
166
 
167
  except Exception as e:
168
+ html("""
169
+ <script>
170
+ document.dispatchEvent(new Event('stopTimer'));
171
+ document.getElementById('timer').remove();
172
+ </script>
173
+ """)
174
  status_text.error(f"**❌ Error:** {str(e)}")
175
  progress_bar.empty()
176
  raise e
177
 
 
 
 
178
  # Audio playback
179
  if st.button("Play Audio of the Story Generated"):
180
  if st.session_state.processed_data.get('audio'):