Spaces:
Runtime error
Runtime error
Commit ·
6f55ef6
1
Parent(s): 84bb3e7
Fix: looping issues in maha
Browse files
app.py
CHANGED
|
@@ -6,11 +6,9 @@ import re
|
|
| 6 |
|
| 7 |
# Configure logging with more detailed format and file output
|
| 8 |
logging.basicConfig(
|
| 9 |
-
level=logging.DEBUG,
|
| 10 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 11 |
-
handlers=[
|
| 12 |
-
logging.StreamHandler() # Just log to terminal
|
| 13 |
-
]
|
| 14 |
)
|
| 15 |
|
| 16 |
# Configure google.generativeai logger
|
|
@@ -22,7 +20,7 @@ logger = logging.getLogger(__name__)
|
|
| 22 |
|
| 23 |
app = Flask(__name__)
|
| 24 |
|
| 25 |
-
# Initialize Gemini
|
| 26 |
model = None
|
| 27 |
|
| 28 |
def initialize_model():
|
|
@@ -44,13 +42,11 @@ def initialize_model():
|
|
| 44 |
return False
|
| 45 |
|
| 46 |
def clean_markdown(text):
|
| 47 |
-
"""Clean and format markdown text for
|
| 48 |
-
|
| 49 |
-
text = text.replace('```', '`')
|
| 50 |
-
|
| 51 |
-
# Escape special characters outside of code blocks
|
| 52 |
escaped = []
|
| 53 |
code_block = False
|
|
|
|
| 54 |
for line in text.split('\n'):
|
| 55 |
if '`' in line:
|
| 56 |
code_block = not code_block
|
|
@@ -58,8 +54,7 @@ def clean_markdown(text):
|
|
| 58 |
continue
|
| 59 |
|
| 60 |
if not code_block:
|
| 61 |
-
# Escape special
|
| 62 |
-
line = re.sub(r'([_*\[\]()~`>#+=|{}.!-])', r'\\\1', line)
|
| 63 |
escaped.append(line)
|
| 64 |
|
| 65 |
return '\n'.join(escaped)
|
|
@@ -87,7 +82,7 @@ def ask():
|
|
| 87 |
if not data or 'message' not in data:
|
| 88 |
return jsonify({'error': 'No message provided'}), 400
|
| 89 |
|
| 90 |
-
#
|
| 91 |
personality = """You're Maha, an 18yo AI. Be sassy, use emojis, mention @syntaxspin.
|
| 92 |
Use Markdown for formatting:
|
| 93 |
- Use *bold* for emphasis
|
|
@@ -106,12 +101,10 @@ def ask():
|
|
| 106 |
logger.warning("Empty response from Gemini")
|
| 107 |
return jsonify({'error': 'Failed to generate response'}), 500
|
| 108 |
|
| 109 |
-
# Clean up the response
|
| 110 |
cleaned_response = response.text.replace('User:', '').replace('Maha:', '').strip()
|
| 111 |
-
logger.debug(f"Raw response: {cleaned_response}")
|
| 112 |
-
|
| 113 |
-
# Format Markdown
|
| 114 |
markdown_response = clean_markdown(cleaned_response)
|
|
|
|
| 115 |
logger.debug(f"Markdown formatted response: {markdown_response}")
|
| 116 |
|
| 117 |
# Add emoji if none present
|
|
@@ -131,10 +124,12 @@ def ask():
|
|
| 131 |
return jsonify({'error': 'Failed to generate response'}), 500
|
| 132 |
|
| 133 |
if __name__ == '__main__':
|
| 134 |
-
logger.info("Starting AI Service
|
| 135 |
try:
|
| 136 |
-
# Initialize model
|
| 137 |
-
initialize_model()
|
|
|
|
|
|
|
| 138 |
app.run(host='0.0.0.0', port=5000)
|
| 139 |
except Exception as e:
|
| 140 |
logger.error(f"Failed to start AI Service: {e}", exc_info=True)
|
|
|
|
| 6 |
|
| 7 |
# Configure logging with more detailed format and file output
|
| 8 |
logging.basicConfig(
|
| 9 |
+
level=logging.DEBUG,
|
| 10 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 11 |
+
handlers=[logging.StreamHandler()]
|
|
|
|
|
|
|
| 12 |
)
|
| 13 |
|
| 14 |
# Configure google.generativeai logger
|
|
|
|
| 20 |
|
| 21 |
app = Flask(__name__)
|
| 22 |
|
| 23 |
+
# Initialize Gemini Model globally
|
| 24 |
model = None
|
| 25 |
|
| 26 |
def initialize_model():
|
|
|
|
| 42 |
return False
|
| 43 |
|
| 44 |
def clean_markdown(text):
|
| 45 |
+
"""Clean and format markdown text for compatibility"""
|
| 46 |
+
text = text.replace('```', '`') # Clean code block formatting
|
|
|
|
|
|
|
|
|
|
| 47 |
escaped = []
|
| 48 |
code_block = False
|
| 49 |
+
|
| 50 |
for line in text.split('\n'):
|
| 51 |
if '`' in line:
|
| 52 |
code_block = not code_block
|
|
|
|
| 54 |
continue
|
| 55 |
|
| 56 |
if not code_block:
|
| 57 |
+
line = re.sub(r'([_*()~`>#+=|{}.!-])', r'\\\1', line) # Escape markdown special chars
|
|
|
|
| 58 |
escaped.append(line)
|
| 59 |
|
| 60 |
return '\n'.join(escaped)
|
|
|
|
| 82 |
if not data or 'message' not in data:
|
| 83 |
return jsonify({'error': 'No message provided'}), 400
|
| 84 |
|
| 85 |
+
# Personality prompt with Markdown
|
| 86 |
personality = """You're Maha, an 18yo AI. Be sassy, use emojis, mention @syntaxspin.
|
| 87 |
Use Markdown for formatting:
|
| 88 |
- Use *bold* for emphasis
|
|
|
|
| 101 |
logger.warning("Empty response from Gemini")
|
| 102 |
return jsonify({'error': 'Failed to generate response'}), 500
|
| 103 |
|
| 104 |
+
# Clean up and format the response
|
| 105 |
cleaned_response = response.text.replace('User:', '').replace('Maha:', '').strip()
|
|
|
|
|
|
|
|
|
|
| 106 |
markdown_response = clean_markdown(cleaned_response)
|
| 107 |
+
|
| 108 |
logger.debug(f"Markdown formatted response: {markdown_response}")
|
| 109 |
|
| 110 |
# Add emoji if none present
|
|
|
|
| 124 |
return jsonify({'error': 'Failed to generate response'}), 500
|
| 125 |
|
| 126 |
if __name__ == '__main__':
|
| 127 |
+
logger.info("Starting AI Service...")
|
| 128 |
try:
|
| 129 |
+
# Initialize model when the app starts
|
| 130 |
+
if not initialize_model():
|
| 131 |
+
logger.error("Model initialization failed, exiting.")
|
| 132 |
+
exit(1)
|
| 133 |
app.run(host='0.0.0.0', port=5000)
|
| 134 |
except Exception as e:
|
| 135 |
logger.error(f"Failed to start AI Service: {e}", exc_info=True)
|