File size: 1,495 Bytes
587fb3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
import PyPDF2
import torch

st.set_page_config(page_title="Perplexity Clone (Gemma)", layout="wide")
st.title("📚 Perplexity-Style AI Study Assistant using Gemma")

# Load Gemma model and tokenizer
@st.cache_resource
def load_model():
    tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b-it")
    model = AutoModelForCausalLM.from_pretrained(
        "google/gemma-7b-it",
        torch_dtype=torch.float16,
        device_map="auto"
    )
    pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=512)
    return pipe

textgen = load_model()

# Extract text from uploaded PDF
def extract_text_from_pdf(file):
    reader = PyPDF2.PdfReader(file)
    text = ""
    for page in reader.pages:
        text += page.extract_text() + "\n"
    return text.strip()

# UI Layout
query = st.text_input("Ask a question or type a query:")

uploaded_file = st.file_uploader("Or upload a PDF to analyze its content:", type=["pdf"])

context = ""
if uploaded_file:
    context = extract_text_from_pdf(uploaded_file)
    st.text_area("Extracted Content", context, height=200)

if st.button("Generate Answer"):
    with st.spinner("Generating with Gemma..."):
        prompt = query
        if context:
            prompt = f"Context:\n{context}\n\nQuestion: {query}"
        output = textgen(prompt)[0]["generated_text"]
        st.success("Answer:")
        st.write(output)