Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
# app.py -
|
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-
|
41 |
|
42 |
-
# In-memory session storage
|
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 |
-
|
69 |
filename = f"audio_{uuid.uuid4()}.mp3"
|
70 |
filepath = os.path.join(AUDIO_FOLDER, filename)
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
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": ""
|
81 |
}
|
82 |
headers = {
|
83 |
"Accept": "application/json",
|
84 |
"Content-Type": "application/x-www-form-urlencoded"
|
85 |
}
|
86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
if response.status_code == 200:
|
88 |
result = response.json()
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
|
|
|
|
|
|
93 |
except Exception as e:
|
94 |
-
print("Request
|
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
|
113 |
response = chat_session.send_message(user_message)
|
114 |
-
full_text = response.text
|
115 |
|
116 |
-
#
|
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 |
-
|
|
|
122 |
short_tag = f"[SHORTEN]{original_url}|{short_url}[/SHORTEN]"
|
123 |
-
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
138 |
-
|
|
|
139 |
|
140 |
-
# Return response
|
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": "
|
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():
|