import os
import gradio as gr
import asyncio
from langchain_core.prompts import PromptTemplate
from langchain_community.document_loaders import PyPDFLoader
from langchain_google_genai import ChatGoogleGenerativeAI
import google.generativeai as genai
from langchain.chains.question_answering import load_qa_chain
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

# Gemini PDF QA System
async def initialize_gemini(file_path, question):
    genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
    model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
    prompt_template = """Answer the question as precise as possible using the provided context. If the answer is
                          not contained in the context, say "answer not available in context" \n\n
                          Context: \n {context}?\n
                          Question: \n {question} \n
                          Answer:
                        """
    prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
    if os.path.exists(file_path):
        pdf_loader = PyPDFLoader(file_path)
        pages = pdf_loader.load_and_split()
        context = "\n".join(str(page.page_content) for page in pages[:30])
        stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
        stuff_answer = await stuff_chain.acall({"input_documents": pages, "question": question, "context": context}, return_only_outputs=True)
        return stuff_answer['output_text']
    else:
        return "Error: Unable to process the document. Please ensure the PDF file is valid."

# Improved Mistral Text Completion
class MistralModel:
    def __init__(self):
        self.model_path = "nvidia/Mistral-NeMo-Minitron-8B-Base"
        self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
        self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
        self.dtype = torch.bfloat16
        self.model = AutoModelForCausalLM.from_pretrained(self.model_path, torch_dtype=self.dtype, device_map=self.device)

    def generate_text(self, prompt, max_length=200):
        # Improve the prompt for better context
        enhanced_prompt = f"Question: {prompt}\n\nAnswer: Let's approach this step-by-step:\n1."
        inputs = self.tokenizer.encode(enhanced_prompt, return_tensors='pt').to(self.model.device)
        
        # Generate with more nuanced parameters
        outputs = self.model.generate(
            inputs, 
            max_length=max_length,
            num_return_sequences=1,
            no_repeat_ngram_size=3,
            top_k=50,
            top_p=0.95,
            temperature=0.7,
            do_sample=True
        )
        
        return self.tokenizer.decode(outputs[0], skip_special_tokens=True)

mistral_model = MistralModel()

# Combined function for both models
async def process_input(file, question):
    gemini_answer = await initialize_gemini(file.name, question)
    mistral_answer = mistral_model.generate_text(question)
    return gemini_answer, mistral_answer

# Gradio Interface
with gr.Blocks() as demo:
    gr.Markdown("# Enhanced PDF Question Answering and Text Completion System")
    
    input_file = gr.File(label="Upload PDF File (Optional)")
    input_question = gr.Textbox(label="Ask a question or provide a prompt")
    process_button = gr.Button("Process")
    
    output_text_gemini = gr.Textbox(label="Answer - Gemini (PDF-based if file uploaded)")
    output_text_mistral = gr.Textbox(label="Answer - Mistral (General knowledge)")

    process_button.click(
        fn=process_input,
        inputs=[input_file, input_question],
        outputs=[output_text_gemini, output_text_mistral]
    )

demo.launch()