import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
from googleapiclient.discovery import build
import config  # Import the config module

# FastAPI app initialization
app = FastAPI()

# Pydantic model to handle requests
class EmotionRequest(BaseModel):
    video_id: str
    max_comments: int
    page: int
    page_size: int

# Analyzer class for emotion and sarcasm
class EmotionSarcasmAnalyzer:
    def __init__(self):
        # Emotion model and tokenizer setup
        self.emotion_model = AutoModelForSequenceClassification.from_pretrained('nateraw/bert-base-uncased-emotion')
        self.emotion_tokenizer = AutoTokenizer.from_pretrained('nateraw/bert-base-uncased-emotion')
        self.emotion_labels = ['anger', 'joy', 'optimism', 'sadness']

        # Sarcasm model and tokenizer setup
        self.sarcasm_model = AutoModelForSequenceClassification.from_pretrained('cardiffnlp/twitter-roberta-base-sentiment-la$
        self.sarcasm_tokenizer = AutoTokenizer.from_pretrained('cardiffnlp/twitter-roberta-base-sentiment-latest')
        self.sarcasm_labels = ['non-sarcastic', 'sarcastic']

def analyze_comment(self, comment: str):
    # Analyze emotion
    inputs = self.emotion_tokenizer(comment, return_tensors="pt", padding=True, truncation=True)
    emotion_output = self.emotion_model(**inputs)
    emotion_index = emotion_output.logits.argmax(dim=1).item()

    # Log the model output for debugging
    print("Emotion Output Logits:", emotion_output.logits)
    print("Emotion Index:", emotion_index)
   print("Emotion Output Logits:", emotion_output.logits)
    print("Emotion Index:", emotion_index)

    # Validate the emotion index
    if emotion_index < 0 or emotion_index >= len(self.emotion_labels):
        raise ValueError(f"Invalid emotion index: {emotion_index}, available labels: {self.emotion_labels}")

    emotion = self.emotion_labels[emotion_index]

    # Analyze sarcasm
    sarcasm_inputs = self.sarcasm_tokenizer(comment, return_tensors="pt", padding=True, truncation=True)
    sarcasm_output = self.sarcasm_model(**sarcasm_inputs)
    sarcasm_index = sarcasm_output.logits.argmax(dim=1).item()
    
    # Ensure sarcasm_index is within range
    if sarcasm_index >= len(self.sarcasm_labels):
        sarcasm = "unknown"  # Fallback value or handle it as required
    else:
        sarcasm = self.sarcasm_labels[sarcasm_index]

    return {
        "comment": comment,
        "emotion": emotion,
        "sarcasm": sarcasm
    }

# Instantiate the analyzer
analyzer = EmotionSarcasmAnalyzer()
        
# Function to fetch comments from YouTube
def fetch_comments(video_id: str, max_results: int):
    youtube = build("youtube", "v3", developerKey=config.YOUTUBE_API_KEY)
    comments = []
    try:
        request = youtube.commentThreads().list( 
            part="snippet",
            videoId=video_id,
            textFormat="plainText",
            maxResults=max_results
        )


            maxResults=max_results
        )
        response = request.execute()
        for item in response.get("items", []):
            comment = item["snippet"]["topLevelComment"]["snippet"]["textDisplay"]
            comments.append(comment)
    except Exception as e:
        print(f"Error fetching comments: {e}")  
    return comments
    
# FastAPI endpoint for emotion and sarcasm analysis
@app.post("/analyze_emotion_sarcasm/")
async def analyze_emotion_sarcasm(request: EmotionRequest):   
    # Fetch comments from YouTube
    comments = fetch_comments(request.video_id, request.max_comments)
    
    # Analyze each comment
    results = []
    for comment in comments:
        analysis_result = analyzer.analyze_comment(comment)
        results.append(analysis_result)
        
    # Paginate the results if necessary
    start_idx = (request.page - 1) * request.page_size
    end_idx = start_idx + request.page_size
    paginated_results = results[start_idx:end_idx]

    return {
        "video_id": request.video_id,
        "max_comments": request.max_comments,
        "page": request.page,
        "page_size": request.page_size,
        "results": paginated_results
    }   



can you fix this script, I want to use rag method to analyze comments