Harisri commited on
Commit
35f388b
·
verified ·
1 Parent(s): beccf73

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +13 -37
src/streamlit_app.py CHANGED
@@ -9,17 +9,16 @@ import json
9
  from langdetect import detect, DetectorFactory
10
  from gtts import gTTS
11
 
12
- # Find the directory this script is in
13
  this_dir = os.path.dirname(os.path.abspath(__file__))
14
  font_path = os.path.join(this_dir, "NotoSansTelugu-VariableFont_wdth,wght.ttf")
15
 
16
- # Initialize Mega client and login securely
17
  mega = Mega()
18
  MEGA_EMAIL = os.getenv("MEGA_EMAIL")
19
  MEGA_PASSWORD = os.getenv("MEGA_PASSWORD")
20
-
21
  if not MEGA_EMAIL or not MEGA_PASSWORD:
22
- st.error("MEGA credentials not found in environment variables. Please set MEGA_EMAIL and MEGA_PASSWORD.")
23
  st.stop()
24
 
25
  m = mega.login(MEGA_EMAIL, MEGA_PASSWORD)
@@ -38,7 +37,6 @@ def get_font_for_language(lang_code, size=28):
38
 
39
  st.set_page_config(page_title="HeritageVerse", layout="centered")
40
  st.title("HeritageVerse: Share Your Cultural Stories")
41
-
42
  st.write("""
43
  Welcome to HeritageVerse! Share your stories, proverbs, or memories in any language. We'll detect the language, generate audio, and create a beautiful story card for you.
44
  """)
@@ -50,7 +48,6 @@ with st.form("story_form"):
50
 
51
  if submitted and story.strip():
52
  st.info("Processing your submission...")
53
- # Language detection
54
  DetectorFactory.seed = 0
55
  try:
56
  detected_lang = detect(story)
@@ -64,19 +61,13 @@ if submitted and story.strip():
64
  st.error(f"Language detection failed: {e}")
65
  detected_lang = None
66
 
67
- # Use /tmp directory for saving temp files to avoid permission errors
68
- tmp_dir = "/tmp"
69
- if not os.path.exists(tmp_dir):
70
- tmp_dir = "."
71
-
72
- # Generate unique filenames and paths
73
  audio_filename = f"audio_{uuid.uuid4().hex}.mp3"
74
  audio_path = os.path.join(tmp_dir, audio_filename)
75
-
76
  card_filename = f"card_{uuid.uuid4().hex}.png"
77
  card_path = os.path.join(tmp_dir, card_filename)
78
 
79
- # Generate TTS audio
80
  try:
81
  tts = gTTS(text=story, lang=detected_lang if detected_lang else 'en')
82
  tts.save(audio_path)
@@ -88,41 +79,33 @@ if submitted and story.strip():
88
  st.error(f"TTS generation failed: {e}")
89
  st.warning("This language might not be supported for audio yet.")
90
 
91
- # Generate image card
92
  try:
93
  title_font = get_font_for_language(detected_lang if detected_lang else 'en', 36)
94
  body_font = get_font_for_language(detected_lang if detected_lang else 'en', 28)
95
-
96
  margin, offset = 40, 80
97
  max_width = 40
98
  lines = textwrap.wrap(story, width=max_width)
99
-
100
  line_heights = []
101
  for line in lines:
102
  bbox = body_font.getbbox(line)
103
  line_height = bbox[3] - bbox[1]
104
  line_heights.append(line_height + 8)
105
-
106
  total_text_height = sum(line_heights)
107
  base_height = 400
108
  extra_height = max(0, total_text_height - (base_height - offset - 60))
109
  img_height = base_height + extra_height
110
-
111
  img = Image.new('RGB', (800, img_height), color=(245, 235, 220))
112
  draw = ImageDraw.Draw(img)
113
-
114
  title_text = "Story Card"
115
  title_width = draw.textlength(title_text, font=title_font)
116
  draw.text(((800 - title_width) // 2, 20), title_text, font=title_font, fill=(90, 60, 30))
117
-
118
  y = offset
119
  for i, line in enumerate(lines):
120
  draw.text((margin, y), line, font=body_font, fill=(60, 40, 20))
121
  y += line_heights[i]
122
-
123
  if name.strip():
124
  draw.text((margin, y + 20), f"- {name.strip()}", font=body_font, fill=(100, 80, 60))
125
-
126
  draw.rectangle([(5, 5), (795, img_height - 5)], outline=(150, 120, 100), width=3)
127
  img.save(card_path)
128
  with open(card_path, "rb") as f:
@@ -132,7 +115,7 @@ if submitted and story.strip():
132
  except Exception as e:
133
  st.error(f"Story card generation failed: {e}")
134
 
135
- # Upload files to MEGA
136
  try:
137
  audio_url = upload_to_mega(audio_path)
138
  card_url = upload_to_mega(card_path)
@@ -146,7 +129,7 @@ if submitted and story.strip():
146
  audio_url = None
147
  card_url = None
148
 
149
- # Manage metadata JSON on MEGA
150
  metadata_file = "stories.json"
151
  local_metadata_path = os.path.join(tmp_dir, metadata_file)
152
  try:
@@ -159,7 +142,6 @@ if submitted and story.strip():
159
  stories = []
160
  except Exception:
161
  stories = []
162
-
163
  try:
164
  data_entry = {
165
  "name": name.strip(),
@@ -170,22 +152,16 @@ if submitted and story.strip():
170
  "card_url": card_url
171
  }
172
  stories.append(data_entry)
173
-
174
  with open(local_metadata_path, "w", encoding="utf-8") as f:
175
  json.dump(stories, f, ensure_ascii=False, indent=2)
176
-
177
  m.upload(local_metadata_path)
178
  st.success("Metadata updated on MEGA!")
179
  except Exception as e:
180
  st.error(f"Failed to update metadata JSON on MEGA: {e}")
181
 
182
- # Clean up local temp files
183
  try:
184
- if os.path.exists(audio_path):
185
- os.remove(audio_path)
186
- if os.path.exists(card_path):
187
- os.remove(card_path)
188
- if os.path.exists(local_metadata_path):
189
- os.remove(local_metadata_path)
190
- except:
191
- pass
 
9
  from langdetect import detect, DetectorFactory
10
  from gtts import gTTS
11
 
12
+ # Find this script's folder and the font there
13
  this_dir = os.path.dirname(os.path.abspath(__file__))
14
  font_path = os.path.join(this_dir, "NotoSansTelugu-VariableFont_wdth,wght.ttf")
15
 
16
+ # MEGA login
17
  mega = Mega()
18
  MEGA_EMAIL = os.getenv("MEGA_EMAIL")
19
  MEGA_PASSWORD = os.getenv("MEGA_PASSWORD")
 
20
  if not MEGA_EMAIL or not MEGA_PASSWORD:
21
+ st.error("MEGA credentials missing. Set MEGA_EMAIL and MEGA_PASSWORD env vars.")
22
  st.stop()
23
 
24
  m = mega.login(MEGA_EMAIL, MEGA_PASSWORD)
 
37
 
38
  st.set_page_config(page_title="HeritageVerse", layout="centered")
39
  st.title("HeritageVerse: Share Your Cultural Stories")
 
40
  st.write("""
41
  Welcome to HeritageVerse! Share your stories, proverbs, or memories in any language. We'll detect the language, generate audio, and create a beautiful story card for you.
42
  """)
 
48
 
49
  if submitted and story.strip():
50
  st.info("Processing your submission...")
 
51
  DetectorFactory.seed = 0
52
  try:
53
  detected_lang = detect(story)
 
61
  st.error(f"Language detection failed: {e}")
62
  detected_lang = None
63
 
64
+ tmp_dir = "/tmp" if os.path.exists("/tmp") else "."
 
 
 
 
 
65
  audio_filename = f"audio_{uuid.uuid4().hex}.mp3"
66
  audio_path = os.path.join(tmp_dir, audio_filename)
 
67
  card_filename = f"card_{uuid.uuid4().hex}.png"
68
  card_path = os.path.join(tmp_dir, card_filename)
69
 
70
+ # Text-to-speech
71
  try:
72
  tts = gTTS(text=story, lang=detected_lang if detected_lang else 'en')
73
  tts.save(audio_path)
 
79
  st.error(f"TTS generation failed: {e}")
80
  st.warning("This language might not be supported for audio yet.")
81
 
82
+ # Story card image generation
83
  try:
84
  title_font = get_font_for_language(detected_lang if detected_lang else 'en', 36)
85
  body_font = get_font_for_language(detected_lang if detected_lang else 'en', 28)
 
86
  margin, offset = 40, 80
87
  max_width = 40
88
  lines = textwrap.wrap(story, width=max_width)
 
89
  line_heights = []
90
  for line in lines:
91
  bbox = body_font.getbbox(line)
92
  line_height = bbox[3] - bbox[1]
93
  line_heights.append(line_height + 8)
 
94
  total_text_height = sum(line_heights)
95
  base_height = 400
96
  extra_height = max(0, total_text_height - (base_height - offset - 60))
97
  img_height = base_height + extra_height
 
98
  img = Image.new('RGB', (800, img_height), color=(245, 235, 220))
99
  draw = ImageDraw.Draw(img)
 
100
  title_text = "Story Card"
101
  title_width = draw.textlength(title_text, font=title_font)
102
  draw.text(((800 - title_width) // 2, 20), title_text, font=title_font, fill=(90, 60, 30))
 
103
  y = offset
104
  for i, line in enumerate(lines):
105
  draw.text((margin, y), line, font=body_font, fill=(60, 40, 20))
106
  y += line_heights[i]
 
107
  if name.strip():
108
  draw.text((margin, y + 20), f"- {name.strip()}", font=body_font, fill=(100, 80, 60))
 
109
  draw.rectangle([(5, 5), (795, img_height - 5)], outline=(150, 120, 100), width=3)
110
  img.save(card_path)
111
  with open(card_path, "rb") as f:
 
115
  except Exception as e:
116
  st.error(f"Story card generation failed: {e}")
117
 
118
+ # Upload to MEGA
119
  try:
120
  audio_url = upload_to_mega(audio_path)
121
  card_url = upload_to_mega(card_path)
 
129
  audio_url = None
130
  card_url = None
131
 
132
+ # Metadata
133
  metadata_file = "stories.json"
134
  local_metadata_path = os.path.join(tmp_dir, metadata_file)
135
  try:
 
142
  stories = []
143
  except Exception:
144
  stories = []
 
145
  try:
146
  data_entry = {
147
  "name": name.strip(),
 
152
  "card_url": card_url
153
  }
154
  stories.append(data_entry)
 
155
  with open(local_metadata_path, "w", encoding="utf-8") as f:
156
  json.dump(stories, f, ensure_ascii=False, indent=2)
 
157
  m.upload(local_metadata_path)
158
  st.success("Metadata updated on MEGA!")
159
  except Exception as e:
160
  st.error(f"Failed to update metadata JSON on MEGA: {e}")
161
 
162
+ # Cleanup
163
  try:
164
+ if os.path.exists(audio_path): os.remove(audio_path)
165
+ if os.path.exists(card_path): os.remove(card_path)
166
+ if os.path.exists(local_metadata_path): os.remove(local_metadata_path)
167
+ except: pass