File size: 3,608 Bytes
1a6123b
 
 
 
 
 
8b9b1de
1f623c7
1a6123b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b9b1de
1a6123b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df23a81
 
 
 
 
 
 
 
 
 
1a6123b
8a78480
1a6123b
 
 
 
 
8b9b1de
1f623c7
 
1a6123b
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

import os
import mimetypes
import cv2
import uuid
import streamlit as st
from google import generativeai as genai 
import urllib.parse

# Configure Gemini API
def configure_api():
    api_key = "AIzaSyBDkLcFKzE_T6r1E5XjbuXVaoW40Szn71s"  # Use your real key here
    genai.configure(api_key=api_key)
    return genai.GenerativeModel('gemini-2.0-flash')

def capture_from_webcam():
    cam = cv2.VideoCapture(0)
    if not cam.isOpened():
        st.error("Could not open webcam.")
        return None

    st.info("Capturing image... Press SPACE to capture.")
    filename = "ahmad.jpg"
    while True:
        ret, frame = cam.read()
        if not ret:
            st.error("Failed to grab frame.")
            break

        cv2.imshow("Camera Feed - Press SPACE to capture", frame)
        key = cv2.waitKey(1)
        if key % 256 == 32:  # SPACE pressed
            cv2.imwrite(filename, frame)
            break
        elif key % 256 == 27:  # ESC
            break

    cam.release()
    cv2.destroyAllWindows()
    if os.path.exists(filename):
        return filename
    return None

def process_image(image_path, model):
    mime_type, _ = mimetypes.guess_type(image_path)
    if not mime_type:
        mime_type = "image/jpeg"

    with open(image_path, "rb") as img_file:
        image_data = img_file.read()

    response = model.generate_content(
        [
            {"mime_type": mime_type, "data": image_data},
            """Analyze the given picture thoroughly, focusing on every detail of the person's appearance, expression, clothing, background, and overall mood. Based on this analysis, choose one Hindi song that best suits the personality, vibe, or emotion of the person in the picture. Just give the name of one Hindi song—no explanation, no extra text."""
        ]
    )
    return response.text.strip()

# Streamlit UI
st.set_page_config(page_title="Hindi Song Recommender", layout="centered")
st.title("🎶 Hindi Song Recommender from Image")

st.write("### Aap image kaise doge?")
option = st.radio("Choose input method:", ["Upload Image", "Capture from Webcam"])

model = configure_api()

if option == "Upload Image":
    uploaded_file = st.file_uploader("Drag and drop your image here", type=["jpg", "jpeg", "png"])
    if uploaded_file:
        path = f"temp_{uuid.uuid4().hex[:8]}.jpg"
        with open(path, "wb") as f:
            f.write(uploaded_file.read())
        st.session_state.image_path = path
        st.image(path, caption="Uploaded Image", use_container_width=True)

elif option == "Capture from Webcam":
    st.write("📸 Use your device's camera:")
    camera_photo = st.camera_input("Take a picture")
    
    if camera_photo is not None:
        # Save the captured image
        path = f"captured_{uuid.uuid4().hex[:8]}.jpg"
        with open(path, "wb") as f:
            f.write(camera_photo.read())
        st.session_state.image_path = path
        st.image(path, caption="Captured Image", use_container_width=True)


if "image_path" in st.session_state and st.button("Suggest Hindi Song"):
    with st.spinner("Analyzing image and finding a song..."):
        try:
            suggested_song = process_image(st.session_state.image_path, model)
            st.success(f"🎵 Suggested Hindi Song: {suggested_song}")
            search_query = urllib.parse.quote_plus(suggested_song)
            youtube_link = f"https://www.youtube.com/results?search_query={search_query}"
            st.markdown(f"[🔗 Click to search on YouTube]({youtube_link})", unsafe_allow_html=True)
        except Exception as e:
            st.error(f"Error: {e}")