syncmaster8 / force_reset_models.py
aseelflihan's picture
Initial commit without node_modules
33d3592
# force_reset_models.py - Force reset all AI models and cache
import os
import sys
import shutil
import glob
from dotenv import load_dotenv
def force_clear_all_cache():
"""Force clear all Python cache and compiled files"""
print("🧹 Force clearing all cache...")
try:
# Remove all __pycache__ directories
pycache_dirs = glob.glob("**/__pycache__", recursive=True)
for cache_dir in pycache_dirs:
shutil.rmtree(cache_dir, ignore_errors=True)
print(f"πŸ—‘οΈ Removed {cache_dir}")
# Remove all .pyc files
pyc_files = glob.glob("**/*.pyc", recursive=True)
for pyc_file in pyc_files:
try:
os.remove(pyc_file)
print(f"πŸ—‘οΈ Removed {pyc_file}")
except:
pass
# Remove .streamlit cache if exists
streamlit_cache = ".streamlit"
if os.path.exists(streamlit_cache):
shutil.rmtree(streamlit_cache, ignore_errors=True)
print(f"πŸ—‘οΈ Removed {streamlit_cache}")
print("βœ… All cache cleared")
return True
except Exception as e:
print(f"❌ Error clearing cache: {str(e)}")
return False
def force_reload_environment():
"""Force reload environment variables"""
print("πŸ”„ Force reloading environment...")
try:
# Clear environment variables
env_vars_to_clear = [
'OPENROUTER_MODEL',
'OPENROUTER_API_KEY',
'GROQ_API_KEY',
'GEMINI_API_KEY'
]
for var in env_vars_to_clear:
if var in os.environ:
del os.environ[var]
print(f"πŸ—‘οΈ Cleared {var} from environment")
# Reload from .env file
load_dotenv(override=True)
# Verify reload
for var in env_vars_to_clear:
value = os.getenv(var)
if value:
if 'KEY' in var:
print(f"βœ… Reloaded {var}: {value[:20]}...{value[-10:]}")
else:
print(f"βœ… Reloaded {var}: {value}")
else:
print(f"⚠️ {var}: Not found")
return True
except Exception as e:
print(f"❌ Error reloading environment: {str(e)}")
return False
def force_reimport_modules():
"""Force reimport all AI-related modules"""
print("πŸ”„ Force reimporting modules...")
try:
# Modules to reimport
modules_to_reload = [
'translator',
'ai_questions',
'exporter'
]
for module_name in modules_to_reload:
if module_name in sys.modules:
del sys.modules[module_name]
print(f"πŸ—‘οΈ Removed {module_name} from sys.modules")
# Force reimport
import importlib
try:
import translator
importlib.reload(translator)
print("βœ… Reloaded translator module")
except Exception as e:
print(f"⚠️ Could not reload translator: {str(e)}")
try:
import ai_questions
importlib.reload(ai_questions)
print("βœ… Reloaded ai_questions module")
except Exception as e:
print(f"⚠️ Could not reload ai_questions: {str(e)}")
return True
except Exception as e:
print(f"❌ Error reimporting modules: {str(e)}")
return False
def test_after_reset():
"""Test AI models after reset"""
print("πŸ§ͺ Testing after reset...")
try:
from translator import get_translator
translator = get_translator()
print(f"πŸ“‹ OpenRouter Model: {translator.openrouter_model}")
# Test OpenRouter
result, error = translator._openrouter_complete("Test message")
if result:
print("βœ… OpenRouter working after reset!")
return True
else:
print(f"❌ OpenRouter still failing: {error}")
return False
except Exception as e:
print(f"❌ Test failed: {str(e)}")
return False
def create_fresh_env_file():
"""Create a fresh .env file with correct values"""
print("πŸ“ Creating fresh .env file...")
env_content = """GEMINI_API_KEY=AIzaSyAS7JtrXjlNjyuo3RG5z6rkwocCwFy1YuA
GROQ_API_KEY=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
OPENROUTER_API_KEY=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
OPENROUTER_MODEL=meta-llama/llama-3.2-3b-instruct:free
GROQ_WHISPER_MODEL=whisper-large-v3
# Google Docs API Configuration
# Get these from: https://console.cloud.google.com/
GOOGLE_CLIENT_ID=your_google_client_id_here
GOOGLE_CLIENT_SECRET=your_google_client_secret_here
"""
try:
with open('.env', 'w', encoding='utf-8') as f:
f.write(env_content)
print("βœ… Fresh .env file created")
return True
except Exception as e:
print(f"❌ Error creating .env file: {str(e)}")
return False
def main():
"""Main force reset function"""
print("πŸš€ Force Reset AI Models")
print("=" * 60)
# Step 1: Create fresh .env file
env_success = create_fresh_env_file()
# Step 2: Clear all cache
cache_success = force_clear_all_cache()
# Step 3: Reload environment
env_reload_success = force_reload_environment()
# Step 4: Reimport modules
import_success = force_reimport_modules()
# Step 5: Test after reset
test_success = test_after_reset()
print("\n" + "=" * 60)
print("πŸ“Š Force Reset Results:")
print(f" Fresh .env: {'βœ… CREATED' if env_success else '❌ FAILED'}")
print(f" Cache Clear: {'βœ… CLEARED' if cache_success else '❌ FAILED'}")
print(f" Env Reload: {'βœ… RELOADED' if env_reload_success else '❌ FAILED'}")
print(f" Module Import: {'βœ… IMPORTED' if import_success else '❌ FAILED'}")
print(f" Final Test: {'βœ… WORKING' if test_success else '❌ FAILED'}")
if all([env_success, cache_success, env_reload_success, test_success]):
print("\nπŸŽ‰ Force reset successful! AI models should work now.")
print("πŸ’‘ Now restart your Streamlit app: streamlit run app.py")
else:
print("\n⚠️ Some issues remain. Check the logs above.")
return test_success
if __name__ == "__main__":
main()