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
|
@@ -29,14 +29,17 @@ You are a helpful AI assistant named Athspi. When responding:
|
|
29 |
3. Keep responses natural and friendly
|
30 |
4. Decide automatically when to include audio based on the content type
|
31 |
5. For stories, always include audio version
|
32 |
-
6. If a URL is in the user's message,
|
33 |
-
|
|
|
|
|
|
|
34 |
"""
|
35 |
|
36 |
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
37 |
model = genai.GenerativeModel('gemini-2.5-flash', system_instruction=system_instruction)
|
38 |
|
39 |
-
# In-memory session storage
|
40 |
chat_sessions = {}
|
41 |
|
42 |
def convert_markdown_to_html(text):
|
@@ -62,37 +65,24 @@ def process_response(full_response):
|
|
62 |
|
63 |
def generate_audio(text):
|
64 |
"""Generate audio file from text"""
|
65 |
-
|
66 |
-
if not clean_text.strip():
|
67 |
-
clean_text = "Hello, this is your AI assistant."
|
68 |
filename = f"audio_{uuid.uuid4()}.mp3"
|
69 |
filepath = os.path.join(AUDIO_FOLDER, filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
try:
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
74 |
except Exception as e:
|
75 |
-
print("
|
76 |
return None
|
77 |
|
78 |
-
def shorten_url_reliable(url):
|
79 |
-
"""Try multiple services to shorten URL"""
|
80 |
-
services = [
|
81 |
-
f"https://tinyurl.com/api-create.php?url={url}",
|
82 |
-
f"https://is.gd/create.php?format=simple&url={url}"
|
83 |
-
]
|
84 |
-
for service_url in services:
|
85 |
-
try:
|
86 |
-
response = requests.get(service_url, timeout=5)
|
87 |
-
if response.status_code == 200:
|
88 |
-
result = response.text.strip()
|
89 |
-
if result.startswith("http") and len(result) > 10:
|
90 |
-
return result
|
91 |
-
except Exception as e:
|
92 |
-
print(f"Shortener failed: {service_url} | Error: {e}")
|
93 |
-
continue
|
94 |
-
return None
|
95 |
-
|
96 |
@app.route('/chat', methods=['POST'])
|
97 |
def chat():
|
98 |
try:
|
@@ -108,23 +98,20 @@ def chat():
|
|
108 |
chat_sessions[session_id] = model.start_chat(history=[])
|
109 |
chat_session = chat_sessions[session_id]
|
110 |
|
111 |
-
#
|
112 |
response = chat_session.send_message(user_message)
|
113 |
full_text = response.text
|
114 |
|
115 |
-
#
|
116 |
url_match = re.search(r'https?://[^\s<>"{}|\\^`\[\]]+', user_message)
|
117 |
if url_match:
|
118 |
original_url = url_match.group(0)
|
119 |
-
short_url =
|
120 |
-
if short_url:
|
121 |
short_tag = f"[SHORTEN]{original_url}|{short_url}[/SHORTEN]"
|
122 |
-
|
123 |
-
full_text += f"\n\nHere's your shortened link:\n{short_tag}"
|
124 |
-
else:
|
125 |
-
full_text += "\n\nI found a link but couldn't shorten it right now."
|
126 |
|
127 |
-
# Process
|
128 |
visible_text, audio_content = process_response(full_text)
|
129 |
html_response = convert_markdown_to_html(visible_text)
|
130 |
|
@@ -133,24 +120,24 @@ def chat():
|
|
133 |
"has_audio": False
|
134 |
}
|
135 |
|
136 |
-
# Generate audio if
|
137 |
if audio_content:
|
138 |
audio_filename = generate_audio(audio_content)
|
139 |
-
|
140 |
-
|
141 |
-
result["has_audio"] = True
|
142 |
|
143 |
-
# Return
|
144 |
resp = make_response(jsonify(result))
|
145 |
resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
|
146 |
return resp
|
147 |
|
148 |
except Exception as e:
|
149 |
-
print("
|
150 |
-
return jsonify({"error": "
|
151 |
|
152 |
@app.route('/new-chat', methods=['POST'])
|
153 |
def new_chat():
|
|
|
154 |
session_id = str(uuid.uuid4())
|
155 |
resp = make_response(jsonify({"status": "new chat started"}))
|
156 |
resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
|
@@ -161,7 +148,7 @@ def download_audio(filename):
|
|
161 |
try:
|
162 |
return send_from_directory(AUDIO_FOLDER, filename, as_attachment=True)
|
163 |
except FileNotFoundError:
|
164 |
-
return jsonify({"error": "
|
165 |
|
166 |
@app.route('/')
|
167 |
def serve_index():
|
|
|
1 |
+
# app.py - Complete AI Chat with Memory + Auto Link Shortening + 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
|
|
|
29 |
3. Keep responses natural and friendly
|
30 |
4. Decide automatically when to include audio based on the content type
|
31 |
5. For stories, always include audio version
|
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://tinyurl.com/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_tinyurl(url):
|
76 |
+
"""Shorten URL using TinyURL public API"""
|
77 |
try:
|
78 |
+
response = requests.get(f"http://tinyurl.com/api-create.php?url={url}")
|
79 |
+
if response.status_code == 200 and response.text.strip():
|
80 |
+
return response.text.strip()
|
81 |
+
return None
|
82 |
except Exception as e:
|
83 |
+
print("TinyURL error:", e)
|
84 |
return None
|
85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
@app.route('/chat', methods=['POST'])
|
87 |
def chat():
|
88 |
try:
|
|
|
98 |
chat_sessions[session_id] = model.start_chat(history=[])
|
99 |
chat_session = chat_sessions[session_id]
|
100 |
|
101 |
+
# Send message to AI
|
102 |
response = chat_session.send_message(user_message)
|
103 |
full_text = response.text
|
104 |
|
105 |
+
# Auto-detect any URL and shorten it
|
106 |
url_match = re.search(r'https?://[^\s<>"{}|\\^`\[\]]+', user_message)
|
107 |
if url_match:
|
108 |
original_url = url_match.group(0)
|
109 |
+
short_url = shorten_url_with_tinyurl(original_url)
|
110 |
+
if short_url and "[SHORTEN]" not in full_text:
|
111 |
short_tag = f"[SHORTEN]{original_url}|{short_url}[/SHORTEN]"
|
112 |
+
full_text += f"\n\n{short_tag}"
|
|
|
|
|
|
|
113 |
|
114 |
+
# Process response
|
115 |
visible_text, audio_content = process_response(full_text)
|
116 |
html_response = convert_markdown_to_html(visible_text)
|
117 |
|
|
|
120 |
"has_audio": False
|
121 |
}
|
122 |
|
123 |
+
# Generate audio if needed
|
124 |
if audio_content:
|
125 |
audio_filename = generate_audio(audio_content)
|
126 |
+
result["audio_filename"] = audio_filename
|
127 |
+
result["has_audio"] = True
|
|
|
128 |
|
129 |
+
# Return response + set session cookie
|
130 |
resp = make_response(jsonify(result))
|
131 |
resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
|
132 |
return resp
|
133 |
|
134 |
except Exception as e:
|
135 |
+
print("Error:", str(e))
|
136 |
+
return jsonify({"error": "Something went wrong."}), 500
|
137 |
|
138 |
@app.route('/new-chat', methods=['POST'])
|
139 |
def new_chat():
|
140 |
+
"""Reset chat memory"""
|
141 |
session_id = str(uuid.uuid4())
|
142 |
resp = make_response(jsonify({"status": "new chat started"}))
|
143 |
resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
|
|
|
148 |
try:
|
149 |
return send_from_directory(AUDIO_FOLDER, filename, as_attachment=True)
|
150 |
except FileNotFoundError:
|
151 |
+
return jsonify({"error": "File not found"}), 404
|
152 |
|
153 |
@app.route('/')
|
154 |
def serve_index():
|