Athspi commited on
Commit
19902da
·
verified ·
1 Parent(s): 301c9ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -52
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # app.py - Fixed URL Shortening with spoo.me
2
  from flask import Flask, request, jsonify, send_from_directory, make_response
3
  import google.generativeai as genai
4
  from dotenv import load_dotenv
@@ -32,14 +32,14 @@ You are a helpful AI assistant named Athspi. When responding:
32
  6. If a URL is present in the user's message, respond with:
33
  [SHORTEN]original_url|short_url[/SHORTEN]
34
  Example:
35
- I've shortened your link:
36
  [SHORTEN]https://example.com|https://spoo.me/abc123[/SHORTEN]
37
  """
38
 
39
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
40
  model = genai.GenerativeModel('gemini-2.5-flash', system_instruction=system_instruction)
41
 
42
- # In-memory session storage
43
  chat_sessions = {}
44
 
45
  def convert_markdown_to_html(text):
@@ -65,54 +65,41 @@ def process_response(full_response):
65
 
66
  def generate_audio(text):
67
  """Generate audio file from text"""
68
- clean_text = re.sub(r'[^\w\s.,!?\-]', '', text)
69
  filename = f"audio_{uuid.uuid4()}.mp3"
70
  filepath = os.path.join(AUDIO_FOLDER, filename)
71
- try:
72
- tts = gTTS(text=clean_text, lang='en', slow=False)
73
- tts.save(filepath)
74
- return filename
75
- except Exception as e:
76
- print("TTS Error:", str(e))
77
- return None
78
 
79
  def shorten_url_with_spoo_me(url):
80
- """Shorten URL using spoo.me API with correct headers"""
81
  try:
82
- # Ensure URL has scheme
83
- if not url.startswith("http"):
84
- url = "https://" + url
85
-
86
  payload = {
87
  "url": url
88
- # alias can be added: "alias": "mycustom"
89
  }
90
  headers = {
91
- "Accept": "application/json",
92
  "Content-Type": "application/x-www-form-urlencoded"
93
  }
94
-
95
  response = requests.post(
96
- "https://spoo.me/",
97
- data=payload, # This sends as form-encoded
98
- headers=headers,
99
  timeout=10
100
  )
101
-
102
- print("spoo.me Status:", response.status_code) # Debug
103
- print("spoo.me Response:", response.text) # Debug
104
-
105
  if response.status_code == 200:
106
- result = response.json()
107
- short_url = result.get("shorturl") or result.get("url")
108
- if short_url and short_url.startswith("http"):
 
109
  return short_url
110
-
111
- print("Failed to shorten:", response.status_code, response.text)
112
- return None
113
-
114
  except Exception as e:
115
- print("Request Exception:", str(e))
116
  return None
117
 
118
  @app.route('/chat', methods=['POST'])
@@ -130,24 +117,18 @@ def chat():
130
  chat_sessions[session_id] = model.start_chat(history=[])
131
  chat_session = chat_sessions[session_id]
132
 
133
- # Send to AI first
134
  response = chat_session.send_message(user_message)
135
- full_text = response.text.strip()
136
 
137
- # Extract URL and shorten
138
  url_match = re.search(r'https?://[^\s<>"{}|\\^`\[\]]+', user_message)
139
  if url_match:
140
  original_url = url_match.group(0)
141
  short_url = shorten_url_with_spoo_me(original_url)
142
-
143
- if short_url:
144
  short_tag = f"[SHORTEN]{original_url}|{short_url}[/SHORTEN]"
145
- if "[SHORTEN]" not in full_text:
146
- full_text += f"\n\n{short_tag}"
147
- else:
148
- # Optional: Inform user
149
- # full_text += "\n\nI couldn't shorten the link right now."
150
- pass # Silent fallback
151
 
152
  # Process final response
153
  visible_text, audio_content = process_response(full_text)
@@ -158,23 +139,24 @@ def chat():
158
  "has_audio": False
159
  }
160
 
 
161
  if audio_content:
162
  audio_filename = generate_audio(audio_content)
163
- if audio_filename:
164
- result["audio_filename"] = audio_filename
165
- result["has_audio"] = True
166
 
167
- # Return response with session cookie
168
  resp = make_response(jsonify(result))
169
  resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
170
  return resp
171
 
172
  except Exception as e:
173
- print("Server Error:", str(e))
174
- return jsonify({"error": "Something went wrong. Please try again."}), 500
175
 
176
  @app.route('/new-chat', methods=['POST'])
177
  def new_chat():
 
178
  session_id = str(uuid.uuid4())
179
  resp = make_response(jsonify({"status": "new chat started"}))
180
  resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
@@ -185,7 +167,7 @@ def download_audio(filename):
185
  try:
186
  return send_from_directory(AUDIO_FOLDER, filename, as_attachment=True)
187
  except FileNotFoundError:
188
- return jsonify({"error": "Audio file not found"}), 404
189
 
190
  @app.route('/')
191
  def serve_index():
 
1
+ # app.py - Flask Backend with Working spoo.me URL Shortening
2
  from flask import Flask, request, jsonify, send_from_directory, make_response
3
  import google.generativeai as genai
4
  from dotenv import load_dotenv
 
32
  6. If a URL is present in the user's message, respond with:
33
  [SHORTEN]original_url|short_url[/SHORTEN]
34
  Example:
35
+ I've shortened your link for convenience:
36
  [SHORTEN]https://example.com|https://spoo.me/abc123[/SHORTEN]
37
  """
38
 
39
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
40
  model = genai.GenerativeModel('gemini-2.5-flash', system_instruction=system_instruction)
41
 
42
+ # In-memory session storage (use Redis in production)
43
  chat_sessions = {}
44
 
45
  def convert_markdown_to_html(text):
 
65
 
66
  def generate_audio(text):
67
  """Generate audio file from text"""
68
+ text = re.sub(r'[^\w\s.,!?\-]', '', text)
69
  filename = f"audio_{uuid.uuid4()}.mp3"
70
  filepath = os.path.join(AUDIO_FOLDER, filename)
71
+ tts = gTTS(text=text, lang='en', slow=False)
72
+ tts.save(filepath)
73
+ return filename
 
 
 
 
74
 
75
  def shorten_url_with_spoo_me(url):
76
+ """Shorten URL using spoo.me API - FIXED VERSION"""
77
  try:
 
 
 
 
78
  payload = {
79
  "url": url
 
80
  }
81
  headers = {
 
82
  "Content-Type": "application/x-www-form-urlencoded"
83
  }
 
84
  response = requests.post(
85
+ "https://spoo.me/",
86
+ data=payload,
87
+ headers=headers,
88
  timeout=10
89
  )
90
+
 
 
 
91
  if response.status_code == 200:
92
+ # spoo.me returns plain text, not JSON!
93
+ short_url = response.text.strip()
94
+ # Ensure it's a valid URL
95
+ if short_url.startswith('http'):
96
  return short_url
97
+ return f"https://spoo.me/{short_url}"
98
+ else:
99
+ print(f"spoo.me error: {response.status_code} - {response.text}")
100
+ return None
101
  except Exception as e:
102
+ print(f"Request failed: {str(e)}")
103
  return None
104
 
105
  @app.route('/chat', methods=['POST'])
 
117
  chat_sessions[session_id] = model.start_chat(history=[])
118
  chat_session = chat_sessions[session_id]
119
 
120
+ # Send message to AI
121
  response = chat_session.send_message(user_message)
122
+ full_text = response.text
123
 
124
+ # Auto-detect any URL and shorten it using spoo.me
125
  url_match = re.search(r'https?://[^\s<>"{}|\\^`\[\]]+', user_message)
126
  if url_match:
127
  original_url = url_match.group(0)
128
  short_url = shorten_url_with_spoo_me(original_url)
129
+ if short_url and "[SHORTEN]" not in full_text:
 
130
  short_tag = f"[SHORTEN]{original_url}|{short_url}[/SHORTEN]"
131
+ full_text += f"\n\n{short_tag}"
 
 
 
 
 
132
 
133
  # Process final response
134
  visible_text, audio_content = process_response(full_text)
 
139
  "has_audio": False
140
  }
141
 
142
+ # Generate audio if needed
143
  if audio_content:
144
  audio_filename = generate_audio(audio_content)
145
+ result["audio_filename"] = audio_filename
146
+ result["has_audio"] = True
 
147
 
148
+ # Return response + set session cookie
149
  resp = make_response(jsonify(result))
150
  resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
151
  return resp
152
 
153
  except Exception as e:
154
+ print("Error:", str(e))
155
+ return jsonify({"error": "Something went wrong."}), 500
156
 
157
  @app.route('/new-chat', methods=['POST'])
158
  def new_chat():
159
+ """Reset chat memory"""
160
  session_id = str(uuid.uuid4())
161
  resp = make_response(jsonify({"status": "new chat started"}))
162
  resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
 
167
  try:
168
  return send_from_directory(AUDIO_FOLDER, filename, as_attachment=True)
169
  except FileNotFoundError:
170
+ return jsonify({"error": "File not found"}), 404
171
 
172
  @app.route('/')
173
  def serve_index():