Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

smsprocessor.py import subprocess import re import requests import logging import…

  1. User

    sms_processor.py

    import subprocess import re import requests import logging import sqlite3 import sys import json from urllib.parse import quote

    Logging yapılandırması

    logging.basicConfig( level=logging.DEBUG, # Daha fazla detay için DEBUG seviyesine çektik format='%(asctime)s [%(levelname)s] %(message)s', handlers=[ logging.FileHandler("sms_processor.log"), logging.StreamHandler() ] )

    DB_FILE = "smsai.db" PROCESSED_SMS_FILE = "processed_sms.json"

    Model listesi

    MODEL_LIST = [ { "name": "openai", "type": "chat", "censored": True, "description": "OpenAI GPT-4o modeli", "baseModel": True, "max_tokens": 200, # OpenAI modeli için max_tokens "use_history": True, # Konuşma geçmişini kullanır "system_prompt": "You are an AI that answers questions received via SMS. Answer TUrkish and do not use any markdown characters in your messages." # OpenAI için sistem promptu }, { "name": "karma", "type": "chat", "censored": True, "description": "Bu modelin internet erişimi mevcuttur. Son dakika haberlerini veya namaz saatlerini güncel olarak alabilirsiniz.", "baseModel": False, "max_tokens": 200, # Karma modeli için max_tokens "use_history": False, # Konuşma geçmişini kullanmaz "system_prompt": "You are an AI assistant specialized in providing up-to-date news and requested information from the web. Answer in Turkish and do not use any markdown characters such as *, -, #, @, `, _, >." # Karma için sistem promptu } ]

    def sanitize_message(message): """Mesaj içindeki yeni satır karakterlerini kaldırır veya boşlukla değiştirir.""" message = message.replace('\n', ' ') message = message.replace('*', '') message = message.replace('/', '') message = message.replace('-', '') message = message.replace('#', '') message = message.replace('@', '') message = message.replace('`', '') message = message.replace('_', '') message = message.replace('>', '') return message

    def init_db(): """Veritabanını başlatır ve gerekli tabloları oluşturur.""" conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() # numbers tablosu cursor.execute(''' CREATE TABLE IF NOT EXISTS numbers ( number TEXT PRIMARY KEY, coin INTEGER DEFAULT 20, name TEXT, mail TEXT, model TEXT DEFAULT 'openai' ) ''')

    # numbers tablosunda 'model' sütunu olup olmadığını kontrol et
    cursor.execute("PRAGMA table_info(numbers)")
    columns = [info[1] for info in cursor.fetchall()]
    if 'model' not in columns:
        logging.info("numbers tablosuna 'model' sütunu ekleniyor.")
        cursor.execute("ALTER TABLE numbers ADD COLUMN model TEXT DEFAULT 'openai'")
        # Mevcut kullanıcılar için varsayılan model ataması
        cursor.execute("UPDATE numbers SET model = 'openai' WHERE model IS NULL")
        conn.commit()
    
    # messages tablosu
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS messages (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            number TEXT,
            direction TEXT,
            content TEXT,
            ai_response_id INTEGER,
            receivedno INTEGER,
            FOREIGN KEY(number) REFERENCES numbers(number)
        )
    ''')
    # messages_history tablosu (konuşma geçmişi için)
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS messages_history (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            number TEXT,
            role TEXT,
            content TEXT,
            FOREIGN KEY(number) REFERENCES numbers(number)
        )
    ''')
    conn.commit()
    conn.close()
    

    def load_processed_sms(): """Processed SMS ID'lerini JSON dosyasından yükler.""" try: with open(PROCESSED_SMS_FILE, 'r') as f: processed = json.load(f) processed_set = set(str(id_) for id_ in processed) logging.debug(f"Processed SMS IDs loaded: {processed_set}") return processed_set except FileNotFoundError: logging.debug("Processed SMS file not found. Creating a new one.") return set() except json.JSONDecodeError as e: logging.error(f"Processed SMS JSON decode error: {e}") return set()

    def save_processed_sms(processed_sms): """Processed SMS ID'lerini JSON dosyasına kaydeder.""" try: with open(PROCESSED_SMS_FILE, 'w') as f: json.dump(list(processed_sms), f) logging.debug(f"Processed SMS IDs saved: {processed_sms}") except Exception as e: logging.error(f"Error saving processed SMS IDs: {e}")

    def get_number(number): """Veritabanında numarayı kontrol eder.""" conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute("SELECT * FROM numbers WHERE number = ?", (number,)) result = cursor.fetchone() conn.close() return result

    def add_number(number, name="", mail="", coin=20, model='openai'): """Yeni bir numara ekler.""" conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute("INSERT OR IGNORE INTO numbers (number, coin, name, mail, model) VALUES (?, ?, ?, ?, ?)", (number, coin, name, mail, model)) conn.commit() conn.close()

    def update_coins(number, amount): """Kullanıcının coin bakiyesini günceller.""" conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute("UPDATE numbers SET coin = coin + ? WHERE number = ?", (amount, number)) conn.commit() cursor.execute("SELECT coin FROM numbers WHERE number = ?", (number,)) coin = cursor.fetchone()[0] conn.close() return coin

    def deduct_coin(number, amount=1): """Kullanıcının coin bakiyesinden belirtilen miktarı düşer.""" conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute("UPDATE numbers SET coin = coin - ? WHERE number = ?", (amount, number)) conn.commit() cursor.execute("SELECT coin FROM numbers WHERE number = ?", (number,)) result = cursor.fetchone() if result: coin = result[0] else: coin = 0 conn.close() return coin

    def log_message(number, direction, content, ai_response_id=None, receivedno=None): """Mesajı veritabanına kaydeder.""" conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute(''' INSERT INTO messages (number, direction, content, ai_response_id, receivedno) VALUES (?, ?, ?, ?, ?) ''', (number, direction, content, ai_response_id, receivedno)) message_id = cursor.lastrowid conn.commit() # Eğer mesaj kullanıcıdan ise, konuşma geçmişine ekle if direction == 'received': cursor.execute(''' INSERT INTO messages_history (number, role, content) VALUES (?, ?, ?) ''', (number, 'user', content)) conn.commit() # Eğer mesaj AI'dan ise, konuşma geçmişine ekle if direction == 'sent': cursor.execute(''' INSERT INTO messages_history (number, role, content) VALUES (?, ?, ?) ''', (number, 'assistant', content)) conn.commit() conn.close() return message_id

    def get_conversation_history(number, limit=7): """Kullanıcının konuşma geçmişini alır, son 'limit' mesajla sınırlar.""" conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute(''' SELECT role, content FROM messages_history WHERE number = ? ORDER BY id DESC LIMIT ? ''', (number, limit)) history = cursor.fetchall() conn.close() # Reverse the history to have chronological order history = history[::-1] messages = [{"role": role, "content": content} for role, content in history] return messages

    def normalize_text(text): """Türkçe karakterleri uygun şekilde dönüştürür.""" replacements = { 'ç': 'c', 'Ç': 'C', 'ğ': 'g', 'Ğ': 'G', 'ı': 'i', 'İ': 'I', 'ö': 'o', 'Ö': 'O', 'ş': 's', 'Ş': 'S', 'ü': 'u', 'Ü': 'U', } return ''.join(replacements.get(c, c) for c in text)

    def send_to_ai(number, prompt): """Sends the SMS message to the AI service and returns the response.""" # Normalize and prepare the prompt normalized_prompt = normalize_text(prompt)

    # Define the API endpoint
    url = "https://text.pollinations.ai/openai"
    
    # Get the user's selected model
    user = get_number(number)
    if not user:
        logging.error(f"Kullanıcı {number} veritabanında bulunamadı.")
        return "Kullanıcı veritabanında bulunamadı."
    
    selected_model = user[4]  # model column
    
    # Get model details from MODEL_LIST
    model_details = next((model for model in MODEL_LIST if model['name'].lower() == selected_model.lower()), None)
    if not model_details:
        logging.error(f"Seçilen model {selected_model} bulunamadı.")
        return "Seçilen model bulunamadı."
    
    model_type = model_details['type']          # 'chat' veya 'completion'
    max_tokens = model_details.get('max_tokens', 200)
    use_history = model_details.get('use_history', True)
    system_prompt = model_details.get('system_prompt', "You are an AI assistant.")  # Varsayılan sistem promptu
    
    try:
        if model_type == 'chat':
            if use_history:
                # Get conversation history
                # To include system prompt as first message, limit to last 6 messages
                conversation_history = get_conversation_history(number, limit=6)  # 6
                # 6 + 1 system message = 7 total
    
                # Construct the payload following OpenAI's ChatGPT API format
                payload = {
                    "model": selected_model,
                    "messages": [{"role": "system", "content": system_prompt}] + conversation_history + [{"role": "user", "content": normalized_prompt}],
                    "max_tokens": max_tokens,
                    "stream": False  # Disable streaming
                }
            else:
                # For models that do not use history, send only the system prompt and the user's last message
                messages = [
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": normalized_prompt}
                ]
                payload = {
                    "model": selected_model,
                    "messages": messages,
                    "max_tokens": max_tokens,
                    "stream": False  # Disable streaming
                }
        elif model_type == 'completion':
            # For completion models, send only the prompt
            payload = {
                "model": selected_model,
                "prompt": normalized_prompt,
                "max_tokens": max_tokens  # Adjust as needed
            }
        else:
            logging.error(f"Bilinmeyen model tipi: {model_type}")
            return "Bilinmeyen model tipi kullanılıyor."
    
        headers = {
            "Content-Type": "application/json"
            # No Authorization header needed since no API key is required
        }
    
        logging.debug(f"Sending request to AI endpoint: {url} with payload: {payload}")
        
        # Make a POST request without streaming
        response = requests.post(url, headers=headers, data=json.dumps(payload))
        
        if response.status_code != 200:
            logging.warning(f"AI service returned status code {response.status_code}: {response.text}")
            return "AI servisine bağlanılamadı."
    
        ai_response_json = response.json()
    
        if model_type == 'chat':
            # AI yanıtının beklendiği yapıyı kontrol et
            if "choices" in ai_response_json and len(ai_response_json["choices"]) > 0:
                ai_response = ai_response_json["choices"][0].get("message", {}).get("content", "").strip()
            else:
                ai_response = "AI'dan geçersiz yanıt alındı."
        elif model_type == 'completion':
            # Completion modeli için yanıt farklı bir yapıda olabilir
            if "choices" in ai_response_json and len(ai_response_json["choices"]) > 0:
                ai_response = ai_response_json["choices"][0].get("text", "").strip()
            else:
                ai_response = "AI'dan geçersiz yanıt alındı."
        else:
            ai_response = "AI model türü desteklenmiyor."
    
        # Mesaj içinde yeni satır karakterlerini temizle
        ai_response = sanitize_message(ai_response)
        
        logging.info("AI yanıtı alındı.")
        return ai_response
    
    except Exception as e:
        logging.error(f"AI servisi hatası: {e}")
        return f"AI servisi hatası: {e}"
    

    def extract_sms_id(log_line): """Log satırından SMS ID'sini çıkartır.""" match = re.search(r'uri:\s+content://sms/(\d+)', log_line) if match: sms_id = match.group(1).strip() logging.debug(f"Extracted SMS ID: {sms_id}") return sms_id return None

    def parse_sms_content(sms_id): """SMS içeriğini sorgular ve adres ile body'yi döndürür.""" try: cmd = [ 'adb', 'shell', 'content', 'query', '--uri', f'content://sms/{sms_id}', '--projection', 'address,body,type' ] logging.debug(f"Running command: {' '.join(cmd)}") result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        if result.stderr:
            logging.error(f"SMS query hatası: {result.stderr}")
            return None, None
        
        # Tam çıktıyı loglama
        logging.debug(f"SMS query output: {result.stdout}")
        
        address = None
        body = None
        sms_type = None
    
        # 'address', 'body' ve 'type' alanlarını regex ile çıkarma
        address_search = re.search(r'address=([^,]+)', result.stdout)
        if address_search:
            address = address_search.group(1).strip()
            logging.debug(f"Address: {address}")
        else:
            logging.debug("Address bulunamadı.")
    
        body_search = re.search(r'body=(.*)', result.stdout)
        if body_search:
            body_full = body_search.group(1).strip()
            # Remove ', type=1' or similar suffix
            body = re.sub(r',\s*type=\d+', '', body_full).strip()
            logging.debug(f"Body (cleaned): {body}")
        else:
            logging.debug("Body bulunamadı.")
    
        type_search = re.search(r'type=(\d+)', result.stdout)
        if type_search:
            sms_type = int(type_search.group(1))
            logging.debug(f"SMS Type: {sms_type}")
        else:
            logging.debug("Type bulunamadı.")
        
        # Sadece gelen SMS'leri işle
        if sms_type != 1:
            logging.debug("SMS tipi alındı ancak gelen SMS değil, işlenmiyor.")
            return None, None
    
        logging.debug(f"Parsed SMS - Address: {address}, Body: {body}, Type: {sms_type}")
        return address, body
    except Exception as e:
        logging.error(f"SMS parse hatası: {e}")
        return None, None
    

    def escape_message(message): """SMS mesajındaki boşluk ve özel karakterleri kaçırır.""" message = sanitize_message(message) escape_chars = { ' ': '\ ', '-': '\-', '!': '\!', '"': '\"', "'": "\'", '\': '\\', '(': '\(', # Açık parantez ')': '\)', # Kapalı parantez '&': '\&', # Ampersand ';': '\;', # Noktalı virgül '|': '\|', # Boru '<': '\<', # Küçük eşit '>': '\>', # Büyük eşit '′:′': '\\', # Dolar işareti '': '\\', # Backtick '': '\', # Yıldız '?': '\?', # Soru işareti } escaped = ''.join([escape_chars.get(c, c) for c in message]) return escaped

    def send_sms(number, message): """Yanıt mesajını ShellMS aracılığıyla gönderir.""" try: escaped_message = escape_message(message) cmd = [ 'adb', 'shell', 'am', 'startservice', '--user', '0', '-n', 'com.android.shellms/.sendSMS', '--es', 'contact', number, '--es', 'msg', escaped_message # Mesajı kaçırılmış şekilde gönder ] # Komutun loglanması için, 'shell' altındaki tüm argümanları loglamalıyız. logging.debug(f"Executing ShellMS command: adb {' '.join(cmd[1:])}") subprocess.run(cmd, check=True) logging.info(f"Yanıt SMS olarak gönderildi: {number} -> {message}") except subprocess.CalledProcessError as e: logging.error(f"SMS gönderim hatası: {e}") except Exception as e: logging.error(f"SMS gönderim hatası: {e}")

    def handle_commands(number, body, received_message_id): """Kullanıcının gönderdiği komutları işler.""" body_lower = body.lower().strip()

    # /yardım komutunu işleme
    if re.fullmatch(r'/?(yardım)', body_lower, re.IGNORECASE):
        help_message = (
            "Yardım Komutları: "
            "/yardım - Bu mesajı gösterir. "
            "/model [model_adı] - Modelinizi değiştirir. "
            "Mevcut Modeller: "
        )
        for model in MODEL_LIST:
            help_message += f"- {model['name']}: {model['description']} "
        help_message += "Modelinizi değiştirmek için /model [model_adı] yazabilirsiniz."
        help_message = sanitize_message(help_message)  # Yeni satır karakterlerini temizle
        send_sms(number, help_message)
        log_message(number, 'sent', help_message, receivedno=received_message_id)
        return True
    
    # /model komutunu işleme
    match = re.match(r'/?model\s+([\w\-]+)', body, re.IGNORECASE)
    if match:
        selected_model_input = match.group(1).lower()
        # Model ismi varyasyonlarını normalize et
        selected_model_key = selected_model_input.replace('-', '')
        # Bulunan modeli kontrol et
        valid_models = {model['name'].lower().replace('-', ''): model for model in MODEL_LIST}
        if selected_model_key in valid_models:
            actual_model_name = valid_models[selected_model_key]['name']
            # Güncelle
            conn = sqlite3.connect(DB_FILE)
            cursor = conn.cursor()
            cursor.execute("UPDATE numbers SET model = ? WHERE number = ?", (actual_model_name, number))
            conn.commit()
            conn.close()
            user = get_number(number)
            remaining_coins = user[1] if user else 0
            confirmation_message = f"Modeliniz güncellendi: {valid_models[selected_model_key]['name']} modeli aktif. C:{remaining_coins} M:{actual_model_name}"
            confirmation_message = sanitize_message(confirmation_message)  # Yeni satır karakterlerini temizle
            send_sms(number, confirmation_message)
            log_message(number, 'sent', confirmation_message, receivedno=received_message_id)
            return True
        else:
            error_message = "Geçersiz model adı. /yardım yazarak mevcut modelleri görebilirsiniz."
            error_message = sanitize_message(error_message)  # Yeni satır karakterlerini temizle
            send_sms(number, error_message)
            log_message(number, 'sent', error_message, receivedno=received_message_id)
            return True
    
    # /yardım veya /model komutu değilse False döner
    return False
    

    def main(): """Ana döngü.""" init_db() logging.info("SMS dinleniyor...")

    processed_sms = load_processed_sms()
    
    try:
        # adb logcat komutunu çalıştır
        process = subprocess.Popen(
            ['adb', 'logcat', '-v', 'time'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            universal_newlines=True
        )
    except Exception as e:
        logging.error(f"Logcat başlatma hatası: {e}")
        sys.exit(1)
    
    # Logcat satırlarını oku
    try:
        for line in process.stdout:
            line = line.strip()
            if 'ReceiveSmsMessageHelper: Received SMS message' in line:
                logging.debug(f"Detected SMS log line: {line}")
                sms_id = extract_sms_id(line)
                if sms_id and sms_id not in processed_sms:
                    logging.debug(f"Processing SMS ID: {sms_id}")
                    # Parse SMS content
                    address, body = parse_sms_content(sms_id)
                    if address and body:
                        logging.debug(f"Parsed SMS - Address: {address}, Body: {body}")
                        # Log the received message in the database
                        received_message_id = log_message(address, 'received', body)
                        
                        # Add Sms ID to processed list
                        processed_sms.add(sms_id)
                        save_processed_sms(processed_sms)
                        
                        # Check if the number is registered
                        user = get_number(address)
                        if user:
                            coins = user[1]
                            selected_model = user[4]
                            logging.debug(f"Kullanıcı {address} bulundu. Coin: {coins}, Model: {selected_model}")
                            
                            # Komutları kontrol et
                            if handle_commands(address, body, received_message_id):
                                continue  # Komut işlendi, devam et
                            
                            if coins >= 1:
                                prompt = body.strip()
                                if prompt.startswith('#'):
                                    prompt = prompt.lstrip('#').strip()
                                logging.info(f"Gelen SMS: {address} - {prompt}")
                                ai_response = send_to_ai(address, prompt)
                                
                                if ai_response:
                                    # Deduct coins
                                    remaining_coins = deduct_coin(address, 1)
                                    logging.debug(f"{address} numaralı kullanıcının kalan coin sayısı: {remaining_coins}")
                                    
                                    # Prepare AI message with coin and model info
                                    model_info = f"M:{selected_model}"
                                    ai_message = f"{ai_response} C:{remaining_coins} {model_info}"
                                    
                                    # Gönderilecek mesajın yeni satır karakterlerini temizle
                                    ai_message = sanitize_message(ai_message)
                                    
                                    # Send AI response
                                    send_sms(address, ai_message)
                                    
                                    # Log the sent message with reference to received message
                                    sent_message_id = log_message(address, 'sent', ai_message, receivedno=received_message_id)
                                    
                                    # Update AI response ID in received message
                                    conn = sqlite3.connect(DB_FILE)
                                    cursor = conn.cursor()
                                    cursor.execute("UPDATE messages SET ai_response_id = ? WHERE id = ?", (sent_message_id, received_message_id))
                                    conn.commit()
                                    conn.close()
                                    
                                    # Save changes
                                    logging.info(f"Yanıt SMS olarak gönderildi: {address} -> {ai_message}")
                                else:
                                    logging.warning(f"AI yanıtı boş geldi: {address}")
                            else:
                                # Coin yeterli değil, gönderim yapma
                                zero_coin_message = "Coininiz bulunmamaktadır, coin yüklemesi yapmak için https://example.com sitesinden yükleme yapabilirsiniz."
                                zero_coin_message = sanitize_message(zero_coin_message)  # Yeni satır karakterlerini temizle
                                send_sms(address, zero_coin_message)
                                logging.info(f"Coin eksik, mesaj gönderilmedi: {address}")
                                # Log the sent zero coin message
                                sent_zero_coin_id = log_message(address, 'sent', zero_coin_message, receivedno=received_message_id)
                        else:
                            # Kullanıcı kayıtlı değil, ekle ve abonelik mesajı gönder
                            add_number(address, coin=30)  # Yeni kullanıcıya 30 kredi tanımla
                            welcome_message = "Hoş geldiniz! SMSGPT servisine hoş geldiniz. Hesabınıza 30 kredi tanımlandı. Modeliniz 'openai GPT-4o' olarak ayarlandı. /yardım yazarak komutları görebilirsiniz."
                            welcome_message = sanitize_message(welcome_message)  # Yeni satır karakterlerini temizle
                            send_sms(address, welcome_message)
                            logging.info(f"Hoş geldin mesajı gönderildi ve {address} numarası veritabanına eklendi.")
                            # Log the sent welcome message
                            sent_welcome_id = log_message(address, 'sent', welcome_message, receivedno=received_message_id)
    except KeyboardInterrupt:
        logging.info("Program sonlandırıldı.")
    except Exception as e:
        logging.error(f"Logcat dinleme hatası: {e}")
    finally:
        process.terminate()
    

    if name == "main": main() kullanıcıdan gelen smsi alma ve yapay zeka bağlantısı ardından geri dönme ve smsi geri gönderme gibi işlemler yapılıyor ancak biraz gecikmeli oluyor. sunucu tarafından yapacak bir şeyimiz yok ancak bu kodda daha hızlandırmak için yapabileceğimiz bir şey var mı

  2. Assistant

    Elbette! Mevcut sms_processor.py kodunuzda gecikmeyi azaltmak için çeşitli iyileştirmeler yapabilirsiniz. Aşağıda, performansı artırmak için önerilen değişiklikler ve bunların nasıl uygulanabileceğine dair açıklamalar bulunmaktadır:

    1. Veritabanı Bağlantısını Optimize Etme

    Her mesaj işlendiğinde veritabanına bağlanmak ve kapatmak, zaman kaybına neden olabilir. Bunun yerine, tek bir kalıcı veritabanı bağlantısı kullanabilirsiniz.

    Uygulama:

    • Veritabanı bağlantısını global olarak açın ve tüm fonksiyonlarda bu bağlantıyı kullanın.
    • Fonksiyonları bu kalıcı bağlantıya göre güncelleyin.
    # Veritabanı bağlantısını global hale getir
    conn = sqlite3.connect(DB_FILE, check_same_thread=False)
    cursor = conn.cursor()
    
    def init_db():
        """Veritabanını başlatır ve gerekli tabloları oluşturur."""
        global conn, cursor
        # ... mevcut kodunuz ...
        conn.commit()
    

    2. Processed SMS ID Yönetimini İyileştirme

    Her SMS işlendiğinde processed_sms.json dosyasını okumak ve yazmak zaman alır. Bunun yerine, bu ID'leri bellekte tutabilir ve belirli aralıklarla diske yazabilirsiniz.

    Uygulama:

    • load_processed_sms ve save_processed_sms fonksiyonlarını kullanmak yerine, processed_sms set'ini bellekte tutun.
    • Düzenli aralıklarla veya belirli sayıda SMS işlendiğinde bu set'i diske kaydedin.
    import threading
    import time
    
    # Processed SMS set
    processed_sms = load_processed_sms()
    
    # Periodic saver
    def periodic_save():
        while True:
            time.sleep(60)  # Her 60 saniyede bir kaydet
            save_processed_sms(processed_sms)
    
    # Başlangıçta kaydetme thread'i başlat
    save_thread = threading.Thread(target=periodic_save, daemon=True)
    save_thread.start()
    

    3. Asenkron SMS İşleme

    SMS işleme sürecini ana döngüden ayırmak, logcat dinlemesini daha hızlı hale getirebilir. Bunun için bir iş kuyruğu ve işçi (worker) thread'leri kullanabilirsiniz.

    Uygulama:

    • queue.Queue kullanarak gelen SMS ID'lerini bir kuyruğa ekleyin.
    • Belirli sayıda işçi thread'i oluşturun ve kuyruğu tüketmelerini sağlayın.
    import queue
    import threading
    
    # SMS işleme kuyruğu
    sms_queue = queue.Queue()
    
    def worker():
        while True:
            sms_id = sms_queue.get()
            if sms_id is None:
                break
            process_sms(sms_id)
            sms_queue.task_done()
    
    def process_sms(sms_id):
        """SMS'yi işleyen fonksiyon."""
        address, body = parse_sms_content(sms_id)
        if address and body:
            # Mevcut işleme mantığınız
            # ...
            pass
    
    # İşçi thread'lerini başlat
    num_workers = 4  # İhtiyaca göre artırabilirsiniz
    threads = []
    for _ in range(num_workers):
        t = threading.Thread(target=worker, daemon=True)
        t.start()
        threads.append(t)
    
    # Main döngüde SMS ID'lerini kuyruğa ekle
    def main():
        """Ana döngü."""
        init_db()
        logging.info("SMS dinleniyor...")
        
        try:
            process = subprocess.Popen(
                ['adb', 'logcat', '-v', 'time'],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                universal_newlines=True
            )
        except Exception as e:
            logging.error(f"Logcat başlatma hatası: {e}")
            sys.exit(1)
        
        try:
            for line in process.stdout:
                line = line.strip()
                if 'ReceiveSmsMessageHelper: Received SMS message' in line:
                    sms_id = extract_sms_id(line)
                    if sms_id and sms_id not in processed_sms:
                        sms_queue.put(sms_id)
        except KeyboardInterrupt:
            logging.info("Program sonlandırıldı.")
        except Exception as e:
            logging.error(f"Logcat dinleme hatası: {e}")
        finally:
            process.terminate()
            # İşçi thread'lerini durdur
            for _ in threads:
                sms_queue.put(None)
            for t in threads:
                t.join()
    
    if __name__ == "__main__":
            main()
    

    4. Subprocess Çağrılarını Azaltma ve Optimize Etme

    Subprocess çağrıları genellikle maliyetlidir. Özellikle adb ile yapılan çağrılar zaman alabilir. Mümkünse, bu çağrıları azaltmak veya daha verimli hale getirmek performansı artırabilir.

    Öneriler:

    • ADB İle Sürekli Bağlantı: adb ile sürekli yeni çağrılar yapmak yerine, bir socket veya başka bir yöntemle daha hızlı iletişim kurmayı deneyebilirsiniz.
    • SMS Ayrıştırmayı İyileştirme: parse_sms_content fonksiyonundaki regex kullanımlarını optimize edin veya daha hızlı ayrıştırma yöntemleri kullanın.

    Örnek Optimizasyon:

    def parse_sms_content(sms_id):
        """SMS içeriğini sorgular ve adres ile body'yi döndürür."""
        try:
            cmd = [
                'adb', 'shell', 'content', 'query',
                '--uri', f'content://sms/{sms_id}',
                '--projection', 'address,body,type'
            ]
            result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=5)
            
            if result.stderr:
                logging.error(f"SMS query hatası: {result.stderr}")
                return None, None
            
            # Daha hızlı ayrıştırma için split kullan
            parts = result.stdout.split(',')
            data = {}
            for part in parts:
                key, sep, value = part.partition('=')
                data[key.strip()] = value.strip()
            
            address = data.get('address')
            body = data.get('body')
            sms_type = int(data.get('type', '0'))
            
            # Gelen SMS kontrolü
            if sms_type != 1:
                return None, None
            
            return address, body
        except subprocess.TimeoutExpired:
            logging.error("SMS query komutu zaman aşımına uğradı.")
            return None, None
        except Exception as e:
            logging.error(f"SMS parse hatası: {e}")
            return None, None
    

    5. SMS Gönderimini Optimize Etme

    SMS gönderimi de subprocess çağrısıyla yapılıyor. Bunun süresini minimize etmek için mesajları toplu göndermeyi veya asenkron hale getirmeyi düşünebilirsiniz.

    Uygulama:

    • SMS gönderimini işçi thread'lerine ekleyin.
    • Gönderim için ayrı bir kuyruk oluşturun.
    # SMS gönderim kuyruğu
    send_queue = queue.Queue()
    
    def send_worker():
        while True:
            item = send_queue.get()
            if item is None:
                break
            number, message = item
            send_sms(number, message)
            send_queue.task_done()
    
    def send_sms(number, message):
        """Yanıt mesajını ShellMS aracılığıyla gönderir."""
        try:
            escaped_message = escape_message(message)
            cmd = [
                'adb', 'shell', 'am', 'startservice', '--user', '0',
                '-n', 'com.android.shellms/.sendSMS',
                '--es', 'contact', number,
                '--es', 'msg', escaped_message
            ]
            logging.debug(f"Executing ShellMS command: adb {' '.join(cmd[1:])}")
            subprocess.run(cmd, check=True)
            logging.info(f"Yanıt SMS olarak gönderildi: {number} -> {message}")
        except subprocess.CalledProcessError as e:
            logging.error(f"SMS gönderim hatası: {e}")
        except Exception as e:
            logging.error(f"SMS gönderim hatası: {e}")
    
    # Gönderim işçi thread'lerini başlat
    send_threads = []
    for _ in range(2):  # Gönderim için daha az sayıda işçi yeterli olabilir
        t = threading.Thread(target=send_worker, daemon=True)
        t.start()
        send_threads.append(t)
    
    def main():
        """Ana döngü."""
        init_db()
        logging.info("SMS dinleniyor...")
        
        # ... mevcut kodunuz ...
        
        try:
            for line in process.stdout:
                line = line.strip()
                if 'ReceiveSmsMessageHelper: Received SMS message' in line:
                    sms_id = extract_sms_id(line)
                    if sms_id and sms_id not in processed_sms:
                        sms_queue.put(sms_id)
        except KeyboardInterrupt:
            logging.info("Program sonlandırıldı.")
        except Exception as e:
            logging.error(f"Logcat dinleme hatası: {e}")
        finally:
            process.terminate()
            # İşçi thread'lerini durdur
            for _ in threads:
                sms_queue.put(None)
            for t in threads:
                t.join()
            for _ in send_threads:
                send_queue.put(None)
            for t in send_threads:
                t.join()
    
    def send_response(number, message):
        """Yanıt mesajını göndermek için kuyruktan ekle."""
        send_queue.put((number, message))
    
    # İşlem fonksiyonunda SMS gönderimini send_response ile değiştirin
    def process_sms(sms_id):
        """SMS'yi işleyen fonksiyon."""
        address, body = parse_sms_content(sms_id)
        if address and body:
            received_message_id = log_message(address, 'received', body)
            processed_sms.add(sms_id)
            # ...
    
            # Örneğin, command handler'da:
            if handle_commands(address, body, received_message_id):
                return
    
            # AI yanıtını aldıktan sonra gönderim
            if ai_response:
                # ...
                send_response(address, ai_message)
                # ...
    

    6. Diğer Optimizasyonlar

    • Logging Seviyesini Ayarlama: DEBUG seviyesindeki loglamalar performansı olumsuz etkileyebilir. Geliştirme aşamasında faydalı olsa da, üretim ortamında seviyeyi INFO veya daha üst seviyelere çekebilirsiniz.

      logging.basicConfig(
          level=logging.INFO,  # Üretim için INFO seviyesine çekildi
          format='%(asctime)s [%(levelname)s] %(message)s',
          handlers=[
              logging.FileHandler("sms_processor.log"),
              logging.StreamHandler()
          ]
      )
      
    • Regex Optimizasyonu: Regex desenlerinizin gereksiz yere karmaşık olmadığından emin olun. Alternatif olarak, daha hızlı string ayrıştırma yöntemleri kullanabilirsiniz.

    • Türkçe Karakter Dönüştürme: normalize_text fonksiyonunda çok fazla replace çağrısı var. Bunun yerine str.translate kullanarak daha hızlı bir dönüşüm gerçekleştirebilirsiniz.

      def normalize_text(text):
          """Türkçe karakterleri uygun şekilde dönüştürür."""
          translation_table = str.maketrans({
              'ç': 'c', 'Ç': 'C',
              'ğ': 'g', 'Ğ': 'G',
              'ı': 'i', 'İ': 'I',
              'ö': 'o', 'Ö': 'O',
              'ş': 's', 'Ş': 'S',
              'ü': 'u', 'Ü': 'U',
          })
          return text.translate(translation_table)
      

    7. Örnek İyileştirilmiş Kod

    Aşağıda, yukarıdaki önerilerin bazılarını entegre eden örnek bir yapı sunuyorum:

    import subprocess
    import re
    import requests
    import logging
    import sqlite3
    import sys
    import json
    from urllib.parse import quote
    import threading
    import queue
    import time
    
    # Logging yapılandırması
    logging.basicConfig(
        level=logging.INFO,  # Üretim için INFO seviyesine çekildi
        format='%(asctime)s [%(levelname)s] %(message)s',
        handlers=[
            logging.FileHandler("sms_processor.log"),
            logging.StreamHandler()
        ]
    )
    
    DB_FILE = "smsai.db"
    PROCESSED_SMS_FILE = "processed_sms.json"
    
    # Model listesi
    MODEL_LIST = [
        # ... mevcut model tanımlarınız ...
    ]
    
    def sanitize_message(message):
        """Mesaj içindeki özel karakterleri temizler."""
        forbidden_chars = ['\n', '*', '/', '-', '#', '@', '`', '_', '>', '']
        for char in forbidden_chars:
            message = message.replace(char, ' ')
        return message
    
    def normalize_text(text):
        """Türkçe karakterleri uygun şekilde dönüştürür."""
        translation_table = str.maketrans({
            'ç': 'c', 'Ç': 'C',
            'ğ': 'g', 'Ğ': 'G',
            'ı': 'i', 'İ': 'I',
            'ö': 'o', 'Ö': 'O',
            'ş': 's', 'Ş': 'S',
            'ü': 'u', 'Ü': 'U',
        })
        return text.translate(translation_table)
    
    # Veritabanı bağlantısını kalıcı hale getir
    conn = sqlite3.connect(DB_FILE, check_same_thread=False)
    cursor = conn.cursor()
    
    def init_db():
        """Veritabanını başlatır ve gerekli tabloları oluşturur."""
        # numbers tablosu
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS numbers (
                number TEXT PRIMARY KEY,
                coin INTEGER DEFAULT 20,
                name TEXT,
                mail TEXT,
                model TEXT DEFAULT 'openai'
            )
        ''')
    
        # numbers tablosunda 'model' sütunu olup olmadığını kontrol et
        cursor.execute("PRAGMA table_info(numbers)")
        columns = [info[1] for info in cursor.fetchall()]
        if 'model' not in columns:
            logging.info("numbers tablosuna 'model' sütunu ekleniyor.")
            cursor.execute("ALTER TABLE numbers ADD COLUMN model TEXT DEFAULT 'openai'")
            # Mevcut kullanıcılar için varsayılan model ataması
            cursor.execute("UPDATE numbers SET model = 'openai' WHERE model IS NULL")
            conn.commit()
    
        # messages tablosu
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS messages (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                number TEXT,
                direction TEXT,
                content TEXT,
                ai_response_id INTEGER,
                receivedno INTEGER,
                FOREIGN KEY(number) REFERENCES numbers(number)
            )
        ''')
    
        # messages_history tablosu (konuşma geçmişi için)
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS messages_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                number TEXT,
                role TEXT,
                content TEXT,
                FOREIGN KEY(number) REFERENCES numbers(number)
            )
        ''')
        conn.commit()
    
    def load_processed_sms():
        """Processed SMS ID'lerini JSON dosyasından yükler."""
        try:
            with open(PROCESSED_SMS_FILE, 'r') as f:
                processed = json.load(f)
                processed_set = set(str(id_) for id_ in processed)
                logging.info(f"Processed SMS IDs loaded: {len(processed_set)}")
                return processed_set
        except FileNotFoundError:
            logging.info("Processed SMS file not found. Creating a new one.")
            return set()
        except json.JSONDecodeError as e:
            logging.error(f"Processed SMS JSON decode error: {e}")
            return set()
    
    def save_processed_sms(processed_sms):
        """Processed SMS ID'lerini JSON dosyasına kaydeder."""
        try:
            with open(PROCESSED_SMS_FILE, 'w') as f:
                json.dump(list(processed_sms), f)
                logging.info(f"Processed SMS IDs saved: {len(processed_sms)}")
        except Exception as e:
            logging.error(f"Error saving processed SMS IDs: {e}")
    
    # Global processed_sms set
    processed_sms = load_processed_sms()
    processed_sms_lock = threading.Lock()
    
    # Periodic saver thread
    def periodic_save():
        while True:
            time.sleep(60)  # Her 60 saniyede bir kaydet
            with processed_sms_lock:
                save_processed_sms(processed_sms)
    
    save_thread = threading.Thread(target=periodic_save, daemon=True)
    save_thread.start()
    
    def get_number(number):
        """Veritabanında numarayı kontrol eder."""
        cursor.execute("SELECT * FROM numbers WHERE number = ?", (number,))
        result = cursor.fetchone()
        return result
    
    def add_number(number, name="", mail="", coin=20, model='openai'):
        """Yeni bir numara ekler."""
        cursor.execute("INSERT OR IGNORE INTO numbers (number, coin, name, mail, model) VALUES (?, ?, ?, ?, ?)",
                       (number, coin, name, mail, model))
        conn.commit()
    
    def update_coins(number, amount):
        """Kullanıcının coin bakiyesini günceller."""
        cursor.execute("UPDATE numbers SET coin = coin + ? WHERE number = ?", (amount, number))
        conn.commit()
        cursor.execute("SELECT coin FROM numbers WHERE number = ?", (number,))
        coin = cursor.fetchone()[0]
        return coin
    
    def deduct_coin(number, amount=1):
        """Kullanıcının coin bakiyesinden belirtilen miktarı düşer."""
        cursor.execute("UPDATE numbers SET coin = coin - ? WHERE number = ?", (amount, number))
        conn.commit()
        cursor.execute("SELECT coin FROM numbers WHERE number = ?", (number,))
        result = cursor.fetchone()
        if result:
            coin = result[0]
        else:
            coin = 0
        return coin
    
    def log_message(number, direction, content, ai_response_id=None, receivedno=None):
        """Mesajı veritabanına kaydeder."""
        cursor.execute('''
            INSERT INTO messages (number, direction, content, ai_response_id, receivedno)
            VALUES (?, ?, ?, ?, ?)
        ''', (number, direction, content, ai_response_id, receivedno))
        message_id = cursor.lastrowid
        conn.commit()
        # Eğer mesaj kullanıcıdan ise, konuşma geçmişine ekle
        if direction == 'received':
            cursor.execute('''
                INSERT INTO messages_history (number, role, content)
                VALUES (?, ?, ?)
            ''', (number, 'user', content))
            conn.commit()
        # Eğer mesaj AI'dan ise, konuşma geçmişine ekle
        if direction == 'sent':
            cursor.execute('''
                INSERT INTO messages_history (number, role, content)
                VALUES (?, ?, ?)
            ''', (number, 'assistant', content))
            conn.commit()
        return message_id
    
    def get_conversation_history(number, limit=6):
        """Kullanıcının konuşma geçmişini alır, son 'limit' mesajla sınırlar."""
        cursor.execute('''
            SELECT role, content FROM messages_history
            WHERE number = ?
            ORDER BY id DESC
            LIMIT ?
        ''', (number, limit))
        history = cursor.fetchall()
        # Reverse the history to have chronological order
        history = history[::-1]
        messages = [{"role": role, "content": content} for role, content in history]
        return messages
    
    def escape_message(message):
        """SMS mesajındaki boşluk ve özel karakterleri kaçırır."""
        message = sanitize_message(message)
        escape_chars = {
            ' ': '\\ ',
            '-': '\\-',
            '!': '\\!',
            '"': '\\"',
            "'": "\\'",
            '\\': '\\\\',
            '(': '\\(',   # Açık parantez
            ')': '\\)',   # Kapalı parantez
            '&': '\\&',   # Ampersand
            ';': '\\;',   # Noktalı virgül
            '|': '\\|',   # Boru
            '<': '\\<',   # Küçük eşit
            '>': '\\>',   # Büyük eşit
            '$': '\\$',   # Dolar işareti
            '`': '\\`',   # Backtick
            '*': '\\*',   # Yıldız
            '?': '\\?',   # Soru işareti
        }
        escaped = ''.join([escape_chars.get(c, c) for c in message])
        return escaped
    
    def send_sms(number, message):
        """Yanıt mesajını ShellMS aracılığıyla gönderir."""
        try:
            escaped_message = escape_message(message)
            cmd = [
                'adb', 'shell', 'am', 'startservice', '--user', '0',
                '-n', 'com.android.shellms/.sendSMS',
                '--es', 'contact', number,
                '--es', 'msg', escaped_message  # Mesajı kaçırılmış şekilde gönder
            ]
            logging.debug(f"Executing ShellMS command: adb {' '.join(cmd[1:])}")
            subprocess.run(cmd, check=True)
            logging.info(f"Yanıt SMS olarak gönderildi: {number} -> {message}")
        except subprocess.CalledProcessError as e:
            logging.error(f"SMS gönderim hatası: {e}")
        except Exception as e:
            logging.error(f"SMS gönderim hatası: {e}")
    
    def handle_commands(number, body, received_message_id):
        """Kullanıcının gönderdiği komutları işler."""
        body_lower = body.lower().strip()
        
        # /yardım komutunu işleme
        if re.fullmatch(r'/?(yardım)', body_lower, re.IGNORECASE):
            help_message = (
                "Yardım Komutları: "
                "/yardım - Bu mesajı gösterir. "
                "/model [model_adı] - Modelinizi değiştirir. "
                "Mevcut Modeller: "
            )
            for model in MODEL_LIST:
                help_message += f"- {model['name']}: {model['description']} "
            help_message += "Modelinizi değiştirmek için /model [model_adı] yazabilirsiniz."
            help_message = sanitize_message(help_message)  # Yeni satır karakterlerini temizle
            send_response(number, help_message)
            log_message(number, 'sent', help_message, receivedno=received_message_id)
            return True
        
        # /model komutunu işleme
        match = re.match(r'/?model\s+([\w\-]+)', body, re.IGNORECASE)
        if match:
            selected_model_input = match.group(1).lower()
            # Model ismi varyasyonlarını normalize et
            selected_model_key = selected_model_input.replace('-', '')
            # Bulunan modeli kontrol et
            valid_models = {model['name'].lower().replace('-', ''): model for model in MODEL_LIST}
            if selected_model_key in valid_models:
                actual_model_name = valid_models[selected_model_key]['name']
                # Güncelle
                cursor.execute("UPDATE numbers SET model = ? WHERE number = ?", (actual_model_name, number))
                conn.commit()
                user = get_number(number)
                remaining_coins = user[1] if user else 0
                confirmation_message = f"Modeliniz güncellendi: {valid_models[selected_model_key]['name']} modeli aktif. C:{remaining_coins} M:{actual_model_name}"
                confirmation_message = sanitize_message(confirmation_message)  # Yeni satır karakterlerini temizle
                send_response(number, confirmation_message)
                log_message(number, 'sent', confirmation_message, receivedno=received_message_id)
                return True
            else:
                error_message = "Geçersiz model adı. /yardım yazarak mevcut modelleri görebilirsiniz."
                error_message = sanitize_message(error_message)  # Yeni satır karakterlerini temizle
                send_response(number, error_message)
                log_message(number, 'sent', error_message, receivedno=received_message_id)
                return True
        
        # /yardım veya /model komutu değilse False döner
        return False
    
    def send_response(number, message):
        """Yanıt mesajını göndermek için kuyruktan ekle."""
        send_queue.put((number, message))
    
    def send_worker():
        while True:
            item = send_queue.get()
            if item is None:
                break
            number, message = item
            send_sms(number, message)
            send_queue.task_done()
    
    def extract_sms_id(log_line):
        """Log satırından SMS ID'sini çıkartır."""
        match = re.search(r'uri:\s+content://sms/(\d+)', log_line)
        if match:
            sms_id = match.group(1).strip()
            logging.debug(f"Extracted SMS ID: {sms_id}")
            return sms_id
        return None
    
    def parse_sms_content(sms_id):
        """SMS içeriğini sorgular ve adres ile body'yi döndürür."""
        try:
            cmd = [
                'adb', 'shell', 'content', 'query',
                '--uri', f'content://sms/{sms_id}',
                '--projection', 'address,body,type'
            ]
            logging.debug(f"Running command: {' '.join(cmd)}")
            result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=5)
            
            if result.stderr:
                logging.error(f"SMS query hatası: {result.stderr}")
                return None, None
            
            # Daha hızlı ayrıştırma için split kullan
            parts = result.stdout.split(',')
            data = {}
            for part in parts:
                key, sep, value = part.partition('=')
                data[key.strip()] = value.strip()
            
            address = data.get('address')
            body = data.get('body')
            sms_type = int(data.get('type', '0'))
            
            # Gelen SMS kontrolü
            if sms_type != 1:
                logging.debug("SMS tipi alındı ancak gelen SMS değil, işlenmiyor.")
                return None, None
            
            logging.debug(f"Parsed SMS - Address: {address}, Body: {body}, Type: {sms_type}")
            return address, body
        except subprocess.TimeoutExpired:
            logging.error("SMS query komutu zaman aşımına uğradı.")
            return None, None
        except Exception as e:
            logging.error(f"SMS parse hatası: {e}")
            return None, None
    
    def send_to_ai(number, prompt):
        """Sends the SMS message to the AI service and returns the response."""
        # Normalize and prepare the prompt
        normalized_prompt = normalize_text(prompt)
        
        # Define the API endpoint
        url = "https://text.pollinations.ai/openai"
    
        # Get the user's selected model
        user = get_number(number)
        if not user:
            logging.error(f"Kullanıcı {number} veritabanında bulunamadı.")
            return "Kullanıcı veritabanında bulunamadı."
    
        selected_model = user[4]  # model column
    
        # Get model details from MODEL_LIST
        model_details = next((model for model in MODEL_LIST if model['name'].lower() == selected_model.lower()), None)
        if not model_details:
            logging.error(f"Seçilen model {selected_model} bulunamadı.")
            return "Seçilen model bulunamadı."
    
        model_type = model_details['type']          # 'chat' veya 'completion'
        max_tokens = model_details.get('max_tokens', 200)
        use_history = model_details.get('use_history', True)
        system_prompt = model_details.get('system_prompt', "You are an AI assistant.")  # Varsayılan sistem promptu
    
        try:
            if model_type == 'chat':
                if use_history:
                    # Get conversation history
                    # To include system prompt as first message, limit to last 6 messages
                    conversation_history = get_conversation_history(number, limit=6)  # 6
                    # 6 + 1 system message = 7 total
    
                    # Construct the payload following OpenAI's ChatGPT API format
                    payload = {
                        "model": selected_model,
                        "messages": [{"role": "system", "content": system_prompt}] + conversation_history + [{"role": "user", "content": normalized_prompt}],
                        "max_tokens": max_tokens,
                        "stream": False  # Disable streaming
                    }
                else:
                    # For models that do not use history, send only the system prompt and the user's last message
                    messages = [
                        {"role": "system", "content": system_prompt},
                        {"role": "user", "content": normalized_prompt}
                    ]
                    payload = {
                        "model": selected_model,
                        "messages": messages,
                        "max_tokens": max_tokens,
                        "stream": False  # Disable streaming
                    }
            elif model_type == 'completion':
                # For completion models, send only the prompt
                payload = {
                    "model": selected_model,
                    "prompt": normalized_prompt,
                    "max_tokens": max_tokens  # Adjust as needed
                }
            else:
                logging.error(f"Bilinmeyen model tipi: {model_type}")
                return "Bilinmeyen model tipi kullanılıyor."
    
            headers = {
                "Content-Type": "application/json"
                # No Authorization header needed since no API key is required
            }
    
            logging.debug(f"Sending request to AI endpoint: {url} with payload: {payload}")
            
            # Make a POST request without streaming
            response = requests.post(url, headers=headers, data=json.dumps(payload), timeout=10)
            
            if response.status_code != 200:
                logging.warning(f"AI service returned status code {response.status_code}: {response.text}")
                return "AI servisine bağlanılamadı."
    
            ai_response_json = response.json()
    
            if model_type == 'chat':
                # AI yanıtının beklendiği yapıyı kontrol et
                if "choices" in ai_response_json and len(ai_response_json["choices"]) > 0:
                    ai_response = ai_response_json["choices"][0].get("message", {}).get("content", "").strip()
                else:
                    ai_response = "AI'dan geçersiz yanıt alındı."
            elif model_type == 'completion':
                # Completion modeli için yanıt farklı bir yapıda olabilir
                if "choices" in ai_response_json and len(ai_response_json["choices"]) > 0:
                    ai_response = ai_response_json["choices"][0].get("text", "").strip()
                else:
                    ai_response = "AI'dan geçersiz yanıt alındı."
            else:
                ai_response = "AI model türü desteklenmiyor."
    
            # Mesaj içinde yeni satır karakterlerini temizle
            ai_response = sanitize_message(ai_response)
            
            logging.info("AI yanıtı alındı.")
            return ai_response
    
        except Exception as e:
            logging.error(f"AI servisi hatası: {e}")
            return f"AI servisi hatası: {e}"
    
    def handle_commands(number, body, received_message_id):
        """Kullanıcının gönderdiği komutları işler."""
        # ... mevcut handle_commands kodunuz ...
        pass
    
    def process_sms(sms_id):
        """SMS'yi işleyen fonksiyon."""
        address, body = parse_sms_content(sms_id)
        if address and body:
            logging.debug(f"Parsed SMS - Address: {address}, Body: {body}")
            # Log the received message in the database
            received_message_id = log_message(address, 'received', body)
            
            with processed_sms_lock:
                # Add Sms ID to processed list
                processed_sms.add(sms_id)
            
            # Check if the number is registered
            user = get_number(address)
            if user:
                coins = user[1]
                selected_model = user[4]
                logging.debug(f"Kullanıcı {address} bulundu. Coin: {coins}, Model: {selected_model}")
                
                # Komutları kontrol et
                if handle_commands(address, body, received_message_id):
                    return  # Komut işlendi, devam et
                
                if coins >= 1:
                    prompt = body.strip()
                    if prompt.startswith('#'):
                        prompt = prompt.lstrip('#').strip()
                    logging.info(f"Gelen SMS: {address} - {prompt}")
                    ai_response = send_to_ai(address, prompt)
                    
                    if ai_response:
                        # Deduct coins
                        remaining_coins = deduct_coin(address, 1)
                        logging.debug(f"{address} numaralı kullanıcının kalan coin sayısı: {remaining_coins}")
                        
                        # Prepare AI message with coin and model info
                        model_info = f"M:{selected_model}"
                        ai_message = f"{ai_response} C:{remaining_coins} {model_info}"
                        
                        # Gönderilecek mesajın yeni satır karakterlerini temizle
                        ai_message = sanitize_message(ai_message)
                        
                        # Send AI response
                        send_response(address, ai_message)
                        
                        # Log the sent message with reference to received message
                        sent_message_id = log_message(address, 'sent', ai_message, receivedno=received_message_id)
                        
                        # Update AI response ID in received message
                        cursor.execute("UPDATE messages SET ai_response_id = ? WHERE id = ?", (sent_message_id, received_message_id))
                        conn.commit()
                        
                        logging.info(f"Yanıt SMS olarak gönderildi: {address} -> {ai_message}")
                    else:
                        logging.warning(f"AI yanıtı boş geldi: {address}")
                else:
                    # Coin yeterli değil, gönderim yapma
                    zero_coin_message = "Coininiz bulunmamaktadır, coin yüklemesi yapmak için https://example.com sitesinden yükleme yapabilirsiniz."
                    zero_coin_message = sanitize_message(zero_coin_message)  # Yeni satır karakterlerini temizle
                    send_response(address, zero_coin_message)
                    logging.info(f"Coin eksik, mesaj gönderilmedi: {address}")
                    # Log the sent zero coin message
                    sent_zero_coin_id = log_message(address, 'sent', zero_coin_message, receivedno=received_message_id)
            else:
                # Kullanıcı kayıtlı değil, ekle ve abonelik mesajı gönder
                add_number(address, coin=30)  # Yeni kullanıcıya 30 kredi tanımla
                welcome_message = "Hoş geldiniz! SMSGPT servisine hoş geldiniz. Hesabınıza 30 kredi tanımlandı. Modeliniz 'openai GPT-4o' olarak ayarlandı. /yardım yazarak komutları görebilirsiniz."
                welcome_message = sanitize_message(welcome_message)  # Yeni satır karakterlerini temizle
                send_response(address, welcome_message)
                logging.info(f"Hoş geldin mesajı gönderildi ve {address} numarası veritabanına eklendi.")
                # Log the sent welcome message
                sent_welcome_id = log_message(address, 'sent', welcome_message, receivedno=received_message_id)
    
    # SMS gönderim kuyruğu ve işçi thread'leri
    send_queue = queue.Queue()
    send_thread = threading.Thread(target=send_worker, daemon=True)
    send_thread.start()
    
    def main():
        """Ana döngü."""
        init_db()
        logging.info("SMS dinleniyor...")
        
        try:
            # adb logcat komutunu çalıştır
            process = subprocess.Popen(
                ['adb', 'logcat', '-v', 'time'],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                universal_newlines=True
            )
        except Exception as e:
            logging.error(f"Logcat başlatma hatası: {e}")
            sys.exit(1)
        
        # Logcat satırlarını oku
        try:
            for line in process.stdout:
                line = line.strip()
                if 'ReceiveSmsMessageHelper: Received SMS message' in line:
                    logging.debug(f"Detected SMS log line: {line}")
                    sms_id = extract_sms_id(line)
                    if sms_id:
                        with processed_sms_lock:
                            if sms_id not in processed_sms:
                                logging.debug(f"Processing SMS ID: {sms_id}")
                                sms_queue.put(sms_id)
        except KeyboardInterrupt:
            logging.info("Program sonlandırıldı.")
        except Exception as e:
            logging.error(f"Logcat dinleme hatası: {e}")
        finally:
            process.terminate()
            # İşçi thread'lerini durdur
            for _ in range(4):  # İşçi sayısına eşit
                sms_queue.put(None)
            for _ in range(2):  # Gönderim thread'leri için
                send_queue.put(None)
            save_thread.join()
            send_queue.join()
    
    if __name__ == "__main__":
        main()
    

    Sonuç

    Yukarıda belirtilen optimizasyonlar, SMS işleme sürecinizi daha hızlı ve verimli hale getirecektir. Anahtar noktalar:

    1. Kalıcı Veritabanı Bağlantısı: Her SMS için yeni bağlantı açmak yerine, tek bir bağlantıyı kullanın.
    2. Bellek İçinde Processed SMS: processed_sms set'ini bellekte tutarak sürekli dosya okuma/yazma işlemlerini azaltın.
    3. Asenkron İşleme: SMS işleme ve gönderimini ana döngüden ayırarak paralel çalışmayı sağlayın.
    4. Subprocess Optimizasyonu: Gerekli subprocess çağrılarını minimize edin ve daha verimli ayrıştırma yöntemleri kullanın.
    5. Logging Seviyesini Ayarlama: Geliştirme ve üretim ortamları için uygun log seviyelerini kullanın.

    Bu iyileştirmeler, SMS işleme sürecinizdeki gecikmeleri azaltmanıza yardımcı olacaktır. Her adımı dikkatlice uyguladığınızdan ve değişikliklerin her aşamasında test ettiğinizden emin olun.