import os import numpy as np from keras_applications.mobilenet_v2 import MobileNetV2, preprocess_input, decode_predictions from keras_preprocessing import image import cv2 # Load the model once at import time mobilenet_model = MobileNetV2(weights='imagenet') def generate_image_hashtags(img_path, top_n=5): """ Generate hashtags for an image file using MobileNetV2. """ if not os.path.exists(img_path): return [] try: img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = mobilenet_model.predict(x) decoded = decode_predictions(preds, top=top_n)[0] hashtags = ['#' + label.replace('_', '') for (_, label, _) in decoded] return hashtags except Exception as e: print(f"Error generating hashtags for image: {e}") return [] def extract_first_frame(video_path, out_img_path): """ Extract the first frame from a video and save it as an image. Returns the image path if successful, else None. """ if not os.path.exists(video_path): return None try: cap = cv2.VideoCapture(video_path) ret, frame = cap.read() if ret: cv2.imwrite(out_img_path, frame) cap.release() return out_img_path cap.release() return None except Exception as e: print(f"Error extracting frame from video: {e}") return None def generate_video_hashtags(video_path, top_n=5): """ Generate hashtags for a video file by extracting the first frame and running image tagging. """ frame_path = video_path + "_frame.jpg" img_path = extract_first_frame(video_path, frame_path) if img_path: hashtags = generate_image_hashtags(img_path, top_n=top_n) # Optionally, remove the frame image after use try: os.remove(img_path) except Exception: pass return hashtags return []