Athspi commited on
Commit
76e5528
·
verified ·
1 Parent(s): 018463a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -16
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # app.py - Flask Backend with Chat Memory
2
  from flask import Flask, request, jsonify, send_from_directory, make_response
3
  import google.generativeai as genai
4
  from dotenv import load_dotenv
@@ -6,6 +6,7 @@ import os
6
  from flask_cors import CORS
7
  import markdown2
8
  import re
 
9
  from gtts import gTTS
10
  import uuid
11
 
@@ -28,15 +29,17 @@ You are a helpful AI assistant named Athspi. When responding:
28
  3. Keep responses natural and friendly
29
  4. Decide automatically when to include audio based on the content type
30
  5. For stories, always include audio version
31
- Example good response:
32
- Here's a story for you!
33
- [AUDIO]Once upon a time...[/AUDIO]
 
 
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 storage for chat sessions (use Redis in production)
40
  chat_sessions = {}
41
 
42
  def convert_markdown_to_html(text):
@@ -45,11 +48,23 @@ def convert_markdown_to_html(text):
45
  return html
46
 
47
  def process_response(full_response):
48
- """Extract visible text and audio content"""
49
  audio_match = re.search(r'\[AUDIO\](.*?)\[/AUDIO\]', full_response, re.DOTALL)
50
  audio_content = audio_match.group(1).strip() if audio_match else None
51
- visible_text = re.sub(r'\[/?AUDIO\]', '', full_response).strip()
52
- return visible_text, audio_content
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  def generate_audio(text):
55
  """Generate audio file from text"""
@@ -60,6 +75,17 @@ def generate_audio(text):
60
  tts.save(filepath)
61
  return filename
62
 
 
 
 
 
 
 
 
 
 
 
 
63
  @app.route('/chat', methods=['POST'])
64
  def chat():
65
  try:
@@ -75,11 +101,24 @@ def chat():
75
  chat_sessions[session_id] = model.start_chat(history=[])
76
  chat_session = chat_sessions[session_id]
77
 
78
- # Send message to Gemini with full history
79
- response = chat_session.send_message(user_message)
80
- visible_text, audio_content = process_response(response.text)
81
-
82
- # Convert to HTML
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  html_response = convert_markdown_to_html(visible_text)
84
 
85
  result = {
@@ -87,13 +126,13 @@ def chat():
87
  "has_audio": False
88
  }
89
 
90
- # Generate audio if needed
91
  if audio_content:
92
  audio_filename = generate_audio(audio_content)
93
  result["audio_filename"] = audio_filename
94
  result["has_audio"] = True
95
 
96
- # Send response and set session cookie
97
  resp = make_response(jsonify(result))
98
  resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
99
  return resp
@@ -104,7 +143,7 @@ def chat():
104
 
105
  @app.route('/new-chat', methods=['POST'])
106
  def new_chat():
107
- """Start a new chat session (clears memory)"""
108
  session_id = str(uuid.uuid4())
109
  resp = make_response(jsonify({"status": "new chat started"}))
110
  resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
 
1
+ # app.py - Flask Backend with Auto Link Shortening (TinyURL) + Chat Memory
2
  from flask import Flask, request, jsonify, send_from_directory, make_response
3
  import google.generativeai as genai
4
  from dotenv import load_dotenv
 
6
  from flask_cors import CORS
7
  import markdown2
8
  import re
9
+ import requests
10
  from gtts import gTTS
11
  import uuid
12
 
 
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 found your link! Here's a shortened version:
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 for chat sessions
43
  chat_sessions = {}
44
 
45
  def convert_markdown_to_html(text):
 
48
  return html
49
 
50
  def process_response(full_response):
51
+ """Extract visible text, audio content, and short links"""
52
  audio_match = re.search(r'\[AUDIO\](.*?)\[/AUDIO\]', full_response, re.DOTALL)
53
  audio_content = audio_match.group(1).strip() if audio_match else None
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, short_data
68
 
69
  def generate_audio(text):
70
  """Generate audio file from text"""
 
75
  tts.save(filepath)
76
  return filename
77
 
78
+ def shorten_url_with_tinyurl(url):
79
+ """Shorten URL using TinyURL public API"""
80
+ try:
81
+ response = requests.get(f"http://tinyurl.com/api-create.php?url={url}")
82
+ if response.status_code == 200 and response.text.strip():
83
+ return response.text.strip()
84
+ return None
85
+ except Exception as e:
86
+ print("TinyURL error:", e)
87
+ return None
88
+
89
  @app.route('/chat', methods=['POST'])
90
  def chat():
91
  try:
 
101
  chat_sessions[session_id] = model.start_chat(history=[])
102
  chat_session = chat_sessions[session_id]
103
 
104
+ # Always send to AI first let AI decide if response needs audio, etc.
105
+ ai_response = chat_session.send_message(user_message)
106
+ full_text = ai_response.text
107
+
108
+ # Extract URL from user message
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
+ if "[SHORTEN]" not in full_text:
118
+ full_text += f"\n\n{short_tag}"
119
+
120
+ # Process final response
121
+ visible_text, audio_content, short_data = process_response(full_text)
122
  html_response = convert_markdown_to_html(visible_text)
123
 
124
  result = {
 
126
  "has_audio": False
127
  }
128
 
129
+ # Generate audio if AI included [AUDIO] tag
130
  if audio_content:
131
  audio_filename = generate_audio(audio_content)
132
  result["audio_filename"] = audio_filename
133
  result["has_audio"] = True
134
 
135
+ # Send response with session cookie
136
  resp = make_response(jsonify(result))
137
  resp.set_cookie('session_id', session_id, max_age=3600, httponly=True, samesite='Lax')
138
  return resp
 
143
 
144
  @app.route('/new-chat', methods=['POST'])
145
  def new_chat():
146
+ """Start a new chat session (clear memory)"""
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')