Spaces:
Runtime error
Runtime error
Download app.py from SyntaxSpin/MahaAi: direct link, hf CLI and curl.
- Browser
- Download file 3.95 kB
-
https://huggingface.co/spaces/SyntaxSpin/MahaAi/resolve/main/app.py
- Command line
-
hf download hf://spaces/SyntaxSpin/MahaAi/app.py
-
curl -L -o app.py https://huggingface.co/spaces/SyntaxSpin/MahaAi/resolve/main/app.py
3.95 kB
| from flask import Flask, request, jsonify | |
| import google.generativeai as genai | |
| import os | |
| import logging | |
| import re | |
| # Configure logging | |
| logging.basicConfig( | |
| level=logging.DEBUG, | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
| handlers=[logging.StreamHandler()] | |
| ) | |
| logger = logging.getLogger(name) # Fix NameError issue | |
| app = Flask(name) | |
| # Initialize Gemini Model globally | |
| model = None | |
| def initialize_model(): | |
| """Initialize the Gemini model""" | |
| global model | |
| try: | |
| logger.info("Initializing Gemini model...") | |
| GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY') | |
| if not GOOGLE_API_KEY: | |
| logger.error("GOOGLE_API_KEY not found in environment variables") | |
| return False | |
| genai.configure(api_key=GOOGLE_API_KEY) | |
| model = genai.GenerativeModel('gemini-pro') | |
| logger.info("Successfully initialized Gemini model") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Failed to initialize Gemini model: {e}", exc_info=True) | |
| return False | |
| def clean_markdown(text): | |
| """Clean and format markdown text for compatibility""" | |
| text = text.replace('`', '`') # Clean code block formatting | |
| escaped = [] | |
| code_block = False | |
| for line in text.split('\n'): | |
| if '`' in line: | |
| code_block = not code_block | |
| escaped.append(line) | |
| continue | |
| if not code_block: | |
| line = re.sub(r'([_*()~`>#+=|{}.!-])', r'\\\1', line) # Escape markdown special chars | |
| escaped.append(line) | |
| return '\n'.join(escaped) | |
| def index(): | |
| """Health check endpoint""" | |
| return jsonify({ | |
| 'status': 'healthy', | |
| 'service': 'AI Service', | |
| 'model': 'gemini-pro', | |
| 'backend': 'Google Gemini' | |
| }) | |
| def ask(): | |
| """Handle chat requests (GET and POST)""" | |
| if not model: | |
| if not initialize_model(): | |
| return jsonify({'error': 'AI service not configured'}), 503 | |
| try: | |
| # Support both POST (JSON) and GET (Query Parameter) | |
| if request.method == 'POST': | |
| data = request.get_json() | |
| message = data.get('message') if data else None | |
| else: # GET request | |
| message = request.args.get('message') | |
| if not message: | |
| return jsonify({'error': 'No message provided'}), 400 | |
| # Personality prompt with Markdown | |
| personality = """You're Maha, an 18yo AI. Be sassy, use emojis, mention @syntaxspin. | |
| Use Markdown for formatting: | |
| - Use *bold* for emphasis | |
| - Use _italic_ for subtle emphasis | |
| - Use `code` for technical terms | |
| - Keep it short but stylish! 💅""" | |
| prompt = f"{personality}\n\nUser: {message}\nMaha:" | |
| logger.debug(f"Input prompt: {prompt}") | |
| # Generate response using Gemini | |
| response = model.generate_content(prompt) | |
| if not response.text: | |
| logger.warning("Empty response from Gemini") | |
| return jsonify({'error': 'Failed to generate response'}), 500 | |
| # Clean up and format the response | |
| cleaned_response = response.text.replace('User:', '').replace('Maha:', '').strip() | |
| markdown_response = clean_markdown(cleaned_response) | |
| logger.debug(f"Markdown formatted response: {markdown_response}") | |
| return jsonify({'response': markdown_response}) | |
| except Exception as e: | |
| logger.error(f"Error generating response: {e}", exc_info=True) | |
| return jsonify({'error': 'Failed to generate response'}), 500 | |
| if name == 'main': | |
| logger.info("Starting AI Service...") | |
| try: | |
| if not initialize_model(): | |
| logger.error("Model initialization failed, exiting.") | |
| exit(1) | |
| app.run(host='0.0.0.0', port=7860, debug=True) | |
| except Exception as e: | |
| logger.error(f"Failed to start AI Service: {e}", exc_info=True) |