<option value="24hours">Last 24 Hours</option>,  <option value="ta">Tamil</option> from flask import Flask, render_template, request, jsonify
import logging
import requests
import yt_dlp
import subprocess
from google.cloud import speech
from datetime import datetime, timedelta, timezone
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

app = Flask(__name__)

# Configuration
YOUTUBE_API_KEY = "AIzaSyDPGkdHCYlo84r-AT3aQvMTVbwmYOnx_mQ " # Store this in your .env file
FFMPEG_PATH = os.getenv(
    "C:/Users/Dell/AppData/Local/Programs/Python/Python310/Lib/ffmpeg/bin/ffmpeg.exe",
    "ffmpeg"
)
if not os.path.exists(FFMPEG_PATH):
    FFMPEG_PATH = "ffmpeg"  # Fallback to default ffmpeg if specific path is not found

if not YOUTUBE_API_KEY:
    raise ValueError("YouTube API Key is missing. Set it in the .env file.")

# Logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[logging.StreamHandler()],
)

# Supported languages in India
SUPPORTED_LANGUAGES = [
    "hi",  # Hindi
    "bn",  # Bengali
    "te",  # Telugu
    "mr",  # Marathi
    "ta",  # Tamil
    "ur",  # Urdu
    "gu",  # Gujarati
    "ml",  # Malayalam
    "kn",  # Kannada
    "pa",  # Punjabi
    "en",  # English
]

# Utility Functions
def preprocess_audio(input_path, output_path):
    try:
        command = [
            FFMPEG_PATH,
            "-i", input_path,
            "-ar", "16000",
            "-ac", "1",
            output_path,
        ]
        subprocess.run(command, check=True)
        return output_path
    except Exception as e:
        logging.error(f"Error processing audio: {e}")
        return None

def transcribe_audio(audio_file_path):
    client = speech.SpeechClient()
    with open(audio_file_path, "rb") as audio_file:
        content = audio_file.read()
    audio = speech.RecognitionAudio(content=content)
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code="ta-IN",  # Hardcoded to English for transcription
    )
    response = client.recognize(config=config, audio=audio)
    return " ".join(result.alternatives[0].transcript for result in response.results)

def calculate_time_range(time_filter):
    now = datetime.now(timezone.utc)
    ranges = {
        "24hours": now - timedelta(days=1),
        "week": now - timedelta(weeks=1),
        "month": now - timedelta(days=30),
        "year": now - timedelta(days=365),
    }
    if time_filter in ranges:
        return ranges[time_filter].isoformat().replace("+00:00", "Z")  # Ensure RFC 3339 format
    return None

def is_live_video(video_id):
    video_url = f"https://www.googleapis.com/youtube/v3/videos?part=snippet&id={video_id}&key={YOUTUBE_API_KEY}"
    response = requests.get(video_url)
    data = response.json()
    if "items" in data and data["items"]:
        return data["items"][0]["snippet"]["liveBroadcastContent"] == "live"
    return False

# Routes
@app.route("/")
def index():
    return render_template("index.html")

@app.route("/fetch_videos", methods=["GET"])
def fetch_videos():
    try:
        query = request.args.get("query", None)
        category_id = request.args.get("category_id", "0")
        region_code = request.args.get("region_code", "IN")  # Defaulting to 'IN' for India
        language_code = request.args.get("language_code", None)
        time_filter = request.args.get("time_filter", None)
        max_results = int(request.args.get("max_results", 10))
        page_token = request.args.get("page_token", None)

        # Validate language_code
        if language_code and language_code not in SUPPORTED_LANGUAGES:
            return jsonify({"error": "Unsupported language code."}), 400

        published_after = calculate_time_range(time_filter)

        url = (
            f"https://www.googleapis.com/youtube/v3/search?part=snippet&type=video"
            f"&regionCode={region_code}&maxResults={max_results}&key={YOUTUBE_API_KEY}"
        )
        if query:
            url += f"&q={query}"
        if category_id != "0":
            url += f"&videoCategoryId={category_id}"
        if language_code:
            url += f"&relevanceLanguage={language_code}"
        if published_after:
            url += f"&publishedAfter={published_after}"
        if page_token:
            url += f"&pageToken={page_token}"

        response = requests.get(url)
        if response.status_code != 200:
            logging.error(f"API Request Failed: {response.text}")
            return jsonify({"error": "Failed to fetch videos.", "details": response.text}), 500

        data = response.json()
        return jsonify({
            "items": data.get("items", []),
            "nextPageToken": data.get("nextPageToken", None),
            "prevPageToken": data.get("prevPageToken", None),
        })

    except Exception as e:
        logging.error(f"Error during fetch_videos: {e}")
        return jsonify({"error": "Internal Server Error", "details": str(e)}), 500

@app.route("/video_to_text", methods=["POST"])
def video_to_text():
    try:
        video_id = request.json.get("videoId")
        if not video_id:
            return jsonify({"error": "Video ID is required"}), 400

        video_url = f"https://www.youtube.com/watch?v={video_id}"
        if is_live_video(video_id):
            return jsonify({"error": "Cannot process live videos"}), 400

        audio_file_path = f"downloads/{video_id}.wav"
        ydl_opts = {
            "format": "bestaudio/best",
            "extractaudio": True,
            "audioformat": "wav",
            "outtmpl": f"downloads/{video_id}.%(ext)s",
        }
        os.makedirs("downloads", exist_ok=True)

        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            try:
                ydl.download([video_url])
            except yt_dlp.utils.DownloadError as e:
                logging.error(f"Download failed: {e}")
                return jsonify({"error": "Failed to download video", "details": str(e)}), 400

        processed_audio_path = preprocess_audio(audio_file_path, f"downloads/{video_id}_processed.wav")
        if not processed_audio_path:
            return jsonify({"error": "Audio preprocessing failed. Ensure ffmpeg is installed."}), 500

        transcription = transcribe_audio(processed_audio_path)
        os.remove(audio_file_path)
        os.remove(processed_audio_path)
        return jsonify({"transcription": transcription})

    except Exception as e:
        logging.error(f"Error processing video: {e}")
        return jsonify({"error": "Internal Server Error", "details": str(e)}), 500

if __name__ == "__main__":
    app.run(debug=True)