AIHumanizer / diagnose_and_fix.py
Jay-Rajput's picture
adv humanizer
5c9a55b
#!/usr/bin/env python3
"""
Production Diagnostics and Quick Fix for AI Text Humanizer
This script will identify exactly what's wrong and fix it
"""
import sys
import subprocess
import importlib
import os
def test_import(module_name, component=None):
"""Test if a module/component can be imported"""
try:
if component:
module = importlib.import_module(module_name)
getattr(module, component)
return True, "OK"
else:
importlib.import_module(module_name)
return True, "OK"
except ImportError as e:
return False, f"ImportError: {str(e)}"
except AttributeError as e:
return False, f"AttributeError: {str(e)}"
except Exception as e:
return False, f"Error: {str(e)}"
def run_pip_command(cmd):
"""Run pip command safely"""
try:
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, check=True)
return True, result.stdout
except subprocess.CalledProcessError as e:
return False, e.stderr
def main():
print("πŸ”§ AI TEXT HUMANIZER - PRODUCTION DIAGNOSTICS & FIX")
print("=" * 60)
print("This will diagnose and fix your advanced model issues\n")
# Test current imports
print("πŸ“‹ CURRENT STATUS:")
print("-" * 20)
tests = [
("sentence_transformers", "SentenceTransformer"),
("transformers", "pipeline"),
("torch", None),
("sklearn", None),
("nltk", None),
("gradio", None)
]
results = {}
for module, component in tests:
success, message = test_import(module, component)
status = "βœ… WORKING" if success else "❌ FAILED"
print(f"{module}: {status}")
if not success:
print(f" Error: {message}")
results[module] = success
# Check specific model loading
print(f"\nπŸ€– TESTING MODEL LOADING:")
print("-" * 30)
if results.get('sentence_transformers'):
try:
print("πŸ”„ Testing sentence transformer model...")
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('all-MiniLM-L6-v2')
test_result = model.encode(["test"])
print("βœ… Sentence transformer: MODEL LOADED")
results['sentence_model'] = True
except Exception as e:
print(f"❌ Sentence transformer: MODEL FAILED - {e}")
results['sentence_model'] = False
else:
results['sentence_model'] = False
if results.get('transformers'):
try:
print("πŸ”„ Testing paraphrasing model...")
from transformers import pipeline
paraphraser = pipeline("text2text-generation", model="google/flan-t5-small")
test_result = paraphraser("test sentence", max_length=50)
print("βœ… Paraphrasing: MODEL LOADED")
results['paraphrase_model'] = True
except Exception as e:
print(f"❌ Paraphrasing: MODEL FAILED - {e}")
results['paraphrase_model'] = False
else:
results['paraphrase_model'] = False
# Analyze issues and provide fixes
print(f"\n🎯 DIAGNOSIS & SOLUTIONS:")
print("-" * 30)
if not results['sentence_transformers']:
print("🚨 ISSUE: sentence-transformers not working")
print("πŸ’‘ SOLUTION:")
print(" pip uninstall -y sentence-transformers huggingface_hub")
print(" pip install huggingface_hub==0.17.3")
print(" pip install sentence-transformers==2.2.2")
print()
fix = input("πŸ”§ Apply this fix now? (y/n): ").lower().strip()
if fix == 'y':
print("πŸ”„ Applying sentence-transformers fix...")
success1, _ = run_pip_command("pip uninstall -y sentence-transformers huggingface_hub")
success2, _ = run_pip_command("pip install huggingface_hub==0.17.3")
success3, _ = run_pip_command("pip install sentence-transformers==2.2.2")
if success1 and success2 and success3:
print("βœ… Fix applied successfully!")
# Test again
success, message = test_import('sentence_transformers', 'SentenceTransformer')
if success:
print("βœ… sentence-transformers now working!")
results['sentence_transformers'] = True
else:
print(f"❌ Still not working: {message}")
else:
print("❌ Fix failed")
if not results['transformers']:
print("🚨 ISSUE: transformers not working")
print("πŸ’‘ SOLUTION:")
print(" pip install transformers==4.35.0 torch")
print()
fix = input("πŸ”§ Apply this fix now? (y/n): ").lower().strip()
if fix == 'y':
print("πŸ”„ Applying transformers fix...")
success1, _ = run_pip_command("pip install transformers==4.35.0")
success2, _ = run_pip_command("pip install torch")
if success1 and success2:
print("βœ… Fix applied successfully!")
success, message = test_import('transformers', 'pipeline')
if success:
print("βœ… transformers now working!")
results['transformers'] = True
else:
print(f"❌ Still not working: {message}")
else:
print("❌ Fix failed")
# Final test with our humanizer
print(f"\nπŸ§ͺ FINAL TEST:")
print("-" * 15)
try:
# Try importing our production version
if os.path.exists("text_humanizer_production.py"):
sys.path.insert(0, ".")
from text_humanizer_production import ProductionAITextHumanizer
print("πŸ”„ Creating production humanizer...")
humanizer = ProductionAITextHumanizer()
print("πŸ”„ Testing humanization...")
result = humanizer.humanize_text_production(
"Furthermore, it is important to note that these systems demonstrate significant capabilities.",
style="conversational",
intensity=0.8
)
print("βœ… PRODUCTION TEST SUCCESSFUL!")
print(f"Original: Furthermore, it is important to note that...")
print(f"Humanized: {result['humanized_text']}")
print(f"Quality Score: {result['quality_score']:.3f}")
# Check what features are working
working_features = sum([
results.get('sentence_model', False),
results.get('paraphrase_model', False),
True, # Basic features always work
])
if working_features >= 2:
print("πŸŽ‰ PRODUCTION READY!")
else:
print("⚠️ Limited features - but still functional")
else:
print("❌ text_humanizer_production.py not found")
except Exception as e:
print(f"❌ Final test failed: {e}")
# Summary and next steps
print(f"\nπŸ“Š SUMMARY:")
print("-" * 12)
working_count = sum([
results.get('sentence_transformers', False),
results.get('transformers', False),
results.get('sentence_model', False),
results.get('paraphrase_model', False)
])
if working_count >= 3:
print("πŸŽ‰ ALL ADVANCED FEATURES WORKING!")
print("βœ… Your AI Text Humanizer is production-ready")
print("\nπŸš€ Next steps:")
print(" python text_humanizer_production.py # Test it")
print(" python fastapi_server.py # Run API")
print(" python gradio_app.py # Run web UI")
elif working_count >= 1:
print("⚠️ SOME FEATURES WORKING")
print("βœ… Your humanizer will work with reduced functionality")
print("\nπŸš€ To enable all features, run the fixes above")
else:
print("❌ CRITICAL ISSUES DETECTED")
print("πŸ’‘ Run this command for a fresh start:")
print(" python install_production.py")
print(f"\nπŸ“ž Need help? Check:")
print(" - README.md for detailed setup")
print(" - DEPENDENCY_FIX.md for troubleshooting")
print(" - Run: python install_production.py")
if __name__ == "__main__":
main()