from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer import torch from accelerate import Accelerator import sys # Added for input handling # Initialize accelerator accelerator = Accelerator() def load_models(): print("šŸ”„ Loading optimized models...") # 1. DistilBERT (Intent) - Lightweight intent_classifier = pipeline( "text-classification", model="distilbert-base-uncased", device=accelerator.device ) # 2. GPT-2 Small (Reply) - Faster than TinyLlama reply_generator = pipeline( "text-generation", model="gpt2", device=accelerator.device, torch_dtype=torch.float16 ) print("āœ… Models loaded!") return intent_classifier, reply_generator # Load models intent_classifier, reply_generator = load_models() def analyze_comment(comment): # 1. Intent Detection intent_result = intent_classifier(comment) # 2. Generate Reply reply = reply_generator( f"Generate a 10-word Instagram DM reply to: '{comment}'", max_length=30, do_sample=True, pad_token_id=50256 # GPT-2's pad token )[0]['generated_text'].split(":")[-1].strip() return { "intent": intent_result[0]['label'], "confidence": intent_result[0]['score'], "reply": reply } # Non-interactive mode (for Hugging Face Spaces/Docker) if __name__ == "__main__": # Test with hardcoded comments if no input test_comments = [ "Can you send me the link?", "This is awesome!", "How does this work?" ] for comment in test_comments: print(f"\nšŸ“ Comment: {comment}") result = analyze_comment(comment) print(f"šŸŽÆ Intent: {result['intent']} (Confidence: {result['confidence']:.2f})") print(f"šŸ’¬ Reply: {result['reply']}")