import streamlit as st
import http.client
import json
import google.generativeai as genai
import requests

# Configure the Generative AI API
genai.configure(api_key="AIzaSyDiGhxeTJVQoK8jyRge6aaZGg7CrLq0zGk")



# Function to generate summary using Generative AI
def get_gemini_response(prompt):
    model = genai.GenerativeModel('gemini-pro')
    response = model.generate_content(prompt)
    if hasattr(response.candidates[0], "content"):
        return response.candidates[0].content
    else:
        return "Failed to generate summary."

# Streamlit App
st.title("YouTube Video Summarizer")

# Input for YouTube video URL
video_url = st.text_input("Enter YouTube Video URL:")

if st.button("Generate Summary"):
    if "youtube.com" in video_url or "youtu.be" in video_url:
        # Extract video ID
        video_id = video_url.split("v=")[-1].split("&")[0] if "v=" in video_url else video_url.split("/")[-1]
        
        # Fetch transcript
        with st.spinner("Fetching transcript..."):
            api_url = "https://resumegenie-c0pc.onrender.com/fetch_captions"
            try:
                response = requests.post(api_url, json={"video_id": video_id})
                if response.status_code == 200:
                    transcript_data = response.json().get("transcript")
                    transcript = " ".join([item["text"] for item in transcript_data])
                    
                    # Generate summary using Gemini
                    with st.spinner("Generating summary..."):
                        summary = get_gemini_response(f"Summarize the following text: {transcript}")
                        st.subheader("Video Summary")
                        st.write(summary)
                else:
                    st.error(f"Error: {response.json().get('detail', 'Unknown error')}")
            except Exception as e:
                st.error(f"Error: {str(e)}")
    else:
        st.error("Invalid YouTube URL.")