Athspi commited on
Commit
0683728
·
verified ·
1 Parent(s): ef5465a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -28
app.py CHANGED
@@ -1,4 +1,3 @@
1
- # app.py - Flask Backend with CORRECT 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
@@ -13,14 +12,14 @@ import uuid
13
  # Load environment variables
14
  load_dotenv()
15
 
16
- # Configure paths
17
  AUDIO_FOLDER = os.path.join('static', 'audio')
18
  os.makedirs(AUDIO_FOLDER, exist_ok=True)
19
 
20
  app = Flask(__name__, static_folder='static')
21
  CORS(app)
22
 
23
- # AI Configuration
24
  system_instruction = """
25
  You are a helpful AI assistant named Athspi. When responding:
26
  1. Never mention "audio" or technical terms
@@ -73,43 +72,37 @@ def generate_audio(text):
73
  return filename
74
 
75
  def shorten_url_with_spoo_me(url):
76
- """Shorten URL using spoo.me API - FIXED WITH STRIP & CORRECT JSON KEY"""
77
  try:
78
- # Clean the input URL
79
  clean_url = url.strip()
80
  if not clean_url.startswith(('http://', 'https://')):
81
  clean_url = 'https://' + clean_url
82
 
83
- payload = {
84
- "url": clean_url
85
- }
86
  headers = {
87
  "Accept": "application/json",
88
  "Content-Type": "application/x-www-form-urlencoded"
89
  }
90
 
91
- response = requests.post(
92
- "https://spoo.me/",
93
- data=payload,
94
- headers=headers,
95
- timeout=10
96
- )
97
 
98
  if response.status_code == 200:
99
  try:
100
- result = response.json() # This is now correct
101
- short_url = result.get("short_url") # Use "short_url", not "url"
 
102
  if short_url:
103
- return short_url.strip() # CRITICAL: strip whitespace
 
104
  except Exception as json_error:
105
- print("JSON parse error:", str(json_error))
106
  return None
107
 
108
- print(f"spoo.me error: {response.status_code} - {response.text}")
109
  return None
110
 
111
  except Exception as e:
112
- print("Request failed:", str(e))
113
  return None
114
 
115
  @app.route('/chat', methods=['POST'])
@@ -127,20 +120,19 @@ def chat():
127
  chat_sessions[session_id] = model.start_chat(history=[])
128
  chat_session = chat_sessions[session_id]
129
 
130
- # Send message to AI
131
  response = chat_session.send_message(user_message)
132
  full_text = response.text
133
 
134
- # Auto-detect any URL and shorten it
135
  url_match = re.search(r'https?://[^\s<>"{}|\\^`\[\]]+', user_message)
136
  if url_match:
137
- original_url = url_match.group(0).strip() # Strip detected URL
138
  short_url = shorten_url_with_spoo_me(original_url)
139
  if short_url and "[SHORTEN]" not in full_text:
140
  short_tag = f"[SHORTEN]{original_url}|{short_url}[/SHORTEN]"
141
  full_text += f"\n\n{short_tag}"
142
 
143
- # Process final response
144
  visible_text, audio_content = process_response(full_text)
145
  html_response = convert_markdown_to_html(visible_text)
146
 
@@ -149,13 +141,12 @@ def chat():
149
  "has_audio": False
150
  }
151
 
152
- # Generate audio if needed
153
  if audio_content:
154
  audio_filename = generate_audio(audio_content)
155
  result["audio_filename"] = audio_filename
156
  result["has_audio"] = True
157
 
158
- # Return response + set session cookie
159
  resp = make_response(jsonify(result))
160
  resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
161
  return resp
@@ -166,7 +157,6 @@ def chat():
166
 
167
  @app.route('/new-chat', methods=['POST'])
168
  def new_chat():
169
- """Reset chat memory"""
170
  session_id = str(uuid.uuid4())
171
  resp = make_response(jsonify({"status": "new chat started"}))
172
  resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
@@ -188,4 +178,4 @@ def serve_static(path):
188
  return send_from_directory('static', path)
189
 
190
  if __name__ == '__main__':
191
- app.run(host="0.0.0.0", port=7860)
 
 
1
  from flask import Flask, request, jsonify, send_from_directory, make_response
2
  import google.generativeai as genai
3
  from dotenv import load_dotenv
 
12
  # Load environment variables
13
  load_dotenv()
14
 
15
+ # Directories
16
  AUDIO_FOLDER = os.path.join('static', 'audio')
17
  os.makedirs(AUDIO_FOLDER, exist_ok=True)
18
 
19
  app = Flask(__name__, static_folder='static')
20
  CORS(app)
21
 
22
+ # Gemini AI Configuration
23
  system_instruction = """
24
  You are a helpful AI assistant named Athspi. When responding:
25
  1. Never mention "audio" or technical terms
 
72
  return filename
73
 
74
  def shorten_url_with_spoo_me(url):
75
+ """Shorten URL using spoo.me API and clean output"""
76
  try:
 
77
  clean_url = url.strip()
78
  if not clean_url.startswith(('http://', 'https://')):
79
  clean_url = 'https://' + clean_url
80
 
81
+ payload = {"url": clean_url}
 
 
82
  headers = {
83
  "Accept": "application/json",
84
  "Content-Type": "application/x-www-form-urlencoded"
85
  }
86
 
87
+ response = requests.post("https://spoo.me/", data=payload, headers=headers, timeout=10)
 
 
 
 
 
88
 
89
  if response.status_code == 200:
90
  try:
91
+ result = response.json()
92
+ original_url = result.get("original_url", "").strip()
93
+ short_url = result.get("short_url", "").strip()
94
  if short_url:
95
+ print(f"Spoo.me returned: {original_url} → {short_url}")
96
+ return short_url
97
  except Exception as json_error:
98
+ print("JSON parse error:", json_error)
99
  return None
100
 
101
+ print(f"Spoo.me error: {response.status_code} - {response.text}")
102
  return None
103
 
104
  except Exception as e:
105
+ print("Request failed:", e)
106
  return None
107
 
108
  @app.route('/chat', methods=['POST'])
 
120
  chat_sessions[session_id] = model.start_chat(history=[])
121
  chat_session = chat_sessions[session_id]
122
 
123
+ # AI response
124
  response = chat_session.send_message(user_message)
125
  full_text = response.text
126
 
127
+ # Detect and shorten first URL
128
  url_match = re.search(r'https?://[^\s<>"{}|\\^`\[\]]+', user_message)
129
  if url_match:
130
+ original_url = url_match.group(0).strip()
131
  short_url = shorten_url_with_spoo_me(original_url)
132
  if short_url and "[SHORTEN]" not in full_text:
133
  short_tag = f"[SHORTEN]{original_url}|{short_url}[/SHORTEN]"
134
  full_text += f"\n\n{short_tag}"
135
 
 
136
  visible_text, audio_content = process_response(full_text)
137
  html_response = convert_markdown_to_html(visible_text)
138
 
 
141
  "has_audio": False
142
  }
143
 
 
144
  if audio_content:
145
  audio_filename = generate_audio(audio_content)
146
  result["audio_filename"] = audio_filename
147
  result["has_audio"] = True
148
 
149
+ # Set session ID in cookie
150
  resp = make_response(jsonify(result))
151
  resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
152
  return resp
 
157
 
158
  @app.route('/new-chat', methods=['POST'])
159
  def new_chat():
 
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')
 
178
  return send_from_directory('static', path)
179
 
180
  if __name__ == '__main__':
181
+ app.run(host="0.0.0.0", port=7860)