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
|
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 storage
|
43 |
chat_sessions = {}
|
44 |
|
45 |
def convert_markdown_to_html(text):
|
@@ -54,17 +54,14 @@ def process_response(full_response):
|
|
54 |
visible_text = re.sub(r'\[/?AUDIO\]', '', full_response)
|
55 |
|
56 |
short_link_match = re.search(r'\[SHORTEN\](.*?)\|([^|]*?)\[/SHORTEN\]', visible_text, re.DOTALL)
|
57 |
-
short_data = None
|
58 |
if short_link_match:
|
59 |
original_url = short_link_match.group(1).strip()
|
60 |
short_url = short_link_match.group(2).strip()
|
61 |
-
short_data = {"original": original_url, "short": short_url}
|
62 |
-
# Replace with formatted HTML
|
63 |
link_html = f'<p><strong>π Original:</strong> <a href="{original_url}" target="_blank">{original_url}</a></p>' \
|
64 |
f'<p><strong>βοΈ Shortened:</strong> <a href="{short_url}" target="_blank">{short_url}</a></p>'
|
65 |
visible_text = re.sub(r'\[SHORTEN\].*?\[/SHORTEN\]', link_html, visible_text)
|
66 |
|
67 |
-
return visible_text, audio_content
|
68 |
|
69 |
def generate_audio(text):
|
70 |
"""Generate audio file from text"""
|
@@ -96,29 +93,26 @@ def chat():
|
|
96 |
if not user_message:
|
97 |
return jsonify({"error": "Message required"}), 400
|
98 |
|
99 |
-
#
|
100 |
if session_id not in chat_sessions:
|
101 |
chat_sessions[session_id] = model.start_chat(history=[])
|
102 |
chat_session = chat_sessions[session_id]
|
103 |
|
104 |
-
#
|
105 |
-
|
106 |
-
full_text =
|
107 |
|
108 |
-
#
|
109 |
url_match = re.search(r'https?://[^\s<>"{}|\\^`\[\]]+', user_message)
|
110 |
-
short_url = None
|
111 |
if url_match:
|
112 |
original_url = url_match.group(0)
|
113 |
short_url = shorten_url_with_tinyurl(original_url)
|
114 |
-
if short_url:
|
115 |
-
# Inject short link into AI response
|
116 |
short_tag = f"[SHORTEN]{original_url}|{short_url}[/SHORTEN]"
|
117 |
-
|
118 |
-
full_text += f"\n\n{short_tag}"
|
119 |
|
120 |
-
# Process
|
121 |
-
visible_text, audio_content
|
122 |
html_response = convert_markdown_to_html(visible_text)
|
123 |
|
124 |
result = {
|
@@ -126,24 +120,24 @@ def chat():
|
|
126 |
"has_audio": False
|
127 |
}
|
128 |
|
129 |
-
# Generate audio if
|
130 |
if audio_content:
|
131 |
audio_filename = generate_audio(audio_content)
|
132 |
result["audio_filename"] = audio_filename
|
133 |
result["has_audio"] = True
|
134 |
|
135 |
-
#
|
136 |
resp = make_response(jsonify(result))
|
137 |
resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
|
138 |
return resp
|
139 |
|
140 |
except Exception as e:
|
141 |
print("Error:", str(e))
|
142 |
-
return jsonify({"error": "Something went wrong.
|
143 |
|
144 |
@app.route('/new-chat', methods=['POST'])
|
145 |
def new_chat():
|
146 |
-
"""
|
147 |
session_id = str(uuid.uuid4())
|
148 |
resp = make_response(jsonify({"status": "new chat started"}))
|
149 |
resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
|
@@ -154,7 +148,7 @@ def download_audio(filename):
|
|
154 |
try:
|
155 |
return send_from_directory(AUDIO_FOLDER, filename, as_attachment=True)
|
156 |
except FileNotFoundError:
|
157 |
-
return jsonify({"error": "
|
158 |
|
159 |
@app.route('/')
|
160 |
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
|
|
|
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):
|
|
|
54 |
visible_text = re.sub(r'\[/?AUDIO\]', '', full_response)
|
55 |
|
56 |
short_link_match = re.search(r'\[SHORTEN\](.*?)\|([^|]*?)\[/SHORTEN\]', visible_text, re.DOTALL)
|
|
|
57 |
if short_link_match:
|
58 |
original_url = short_link_match.group(1).strip()
|
59 |
short_url = short_link_match.group(2).strip()
|
|
|
|
|
60 |
link_html = f'<p><strong>π Original:</strong> <a href="{original_url}" target="_blank">{original_url}</a></p>' \
|
61 |
f'<p><strong>βοΈ Shortened:</strong> <a href="{short_url}" target="_blank">{short_url}</a></p>'
|
62 |
visible_text = re.sub(r'\[SHORTEN\].*?\[/SHORTEN\]', link_html, visible_text)
|
63 |
|
64 |
+
return visible_text, audio_content
|
65 |
|
66 |
def generate_audio(text):
|
67 |
"""Generate audio file from text"""
|
|
|
93 |
if not user_message:
|
94 |
return jsonify({"error": "Message required"}), 400
|
95 |
|
96 |
+
# Get or create chat session
|
97 |
if session_id not in chat_sessions:
|
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 |
|
118 |
result = {
|
|
|
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():
|