Athspi commited on
Commit
bc43a6a
·
verified ·
1 Parent(s): 3e26e8b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -30
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # app.py - Flask Backend with spoo.me URL Shortening + Chat Memory + Audio
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 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,33 +65,54 @@ def process_response(full_response):
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"""
77
  try:
 
 
 
 
78
  payload = {
79
- "url": url,
80
- "alias": "" # Leave empty for auto-generated
81
  }
82
  headers = {
83
  "Accept": "application/json",
84
  "Content-Type": "application/x-www-form-urlencoded"
85
  }
86
- response = requests.post("https://spoo.me/", data=payload, headers=headers, timeout=5)
 
 
 
 
 
 
 
 
 
 
87
  if response.status_code == 200:
88
  result = response.json()
89
- return result.get("shorturl") or result.get("url") # spoo.me returns either
90
- else:
91
- print("spoo.me error:", response.status_code, response.text)
92
- return None
 
 
 
93
  except Exception as e:
94
- print("Request failed:", str(e))
95
  return None
96
 
97
  @app.route('/chat', methods=['POST'])
@@ -109,18 +130,24 @@ def chat():
109
  chat_sessions[session_id] = model.start_chat(history=[])
110
  chat_session = chat_sessions[session_id]
111
 
112
- # Send message to AI
113
  response = chat_session.send_message(user_message)
114
- full_text = response.text
115
 
116
- # Auto-detect any URL and shorten it using spoo.me
117
  url_match = re.search(r'https?://[^\s<>"{}|\\^`\[\]]+', user_message)
118
  if url_match:
119
  original_url = url_match.group(0)
120
  short_url = shorten_url_with_spoo_me(original_url)
121
- if short_url and "[SHORTEN]" not in full_text:
 
122
  short_tag = f"[SHORTEN]{original_url}|{short_url}[/SHORTEN]"
123
- full_text += f"\n\n{short_tag}"
 
 
 
 
 
124
 
125
  # Process final response
126
  visible_text, audio_content = process_response(full_text)
@@ -131,24 +158,23 @@ def chat():
131
  "has_audio": False
132
  }
133
 
134
- # Generate audio if needed
135
  if audio_content:
136
  audio_filename = generate_audio(audio_content)
137
- result["audio_filename"] = audio_filename
138
- result["has_audio"] = True
 
139
 
140
- # Return response + set session cookie
141
  resp = make_response(jsonify(result))
142
  resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
143
  return resp
144
 
145
  except Exception as e:
146
- print("Error:", str(e))
147
- return jsonify({"error": "Something went wrong."}), 500
148
 
149
  @app.route('/new-chat', methods=['POST'])
150
  def new_chat():
151
- """Reset chat memory"""
152
  session_id = str(uuid.uuid4())
153
  resp = make_response(jsonify({"status": "new chat started"}))
154
  resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
@@ -159,7 +185,7 @@ def download_audio(filename):
159
  try:
160
  return send_from_directory(AUDIO_FOLDER, filename, as_attachment=True)
161
  except FileNotFoundError:
162
- return jsonify({"error": "File not found"}), 404
163
 
164
  @app.route('/')
165
  def serve_index():
 
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
  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-flasho', system_instruction=system_instruction)
41
 
42
+ # In-memory session storage
43
  chat_sessions = {}
44
 
45
  def convert_markdown_to_html(text):
 
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
  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
  "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
  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():