g0th commited on
Commit
d881f5c
Β·
verified Β·
1 Parent(s): 9cb64f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -39
app.py CHANGED
@@ -1,49 +1,91 @@
1
- import streamlit as st
2
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
3
- import PyPDF2
4
- import torch
5
  import os
 
 
 
 
6
 
7
- st.set_page_config(page_title="Perplexity-style Q&A (Mistral Auth)", layout="wide")
8
- st.title("🧠 AI Study Assistant using Mistral 7B (Authenticated)")
9
 
10
- # βœ… Load Hugging Face token securely
11
- hf_token = os.getenv("HF_TOKEN") # your Hugging Face secret name
12
 
13
- # βœ… Load the gated model using your token
14
- @st.cache_resource
15
- def load_model():
16
- tokenizer = AutoTokenizer.from_pretrained(
17
- "mistralai/Mistral-7B-Instruct-v0.1",
18
- token=hf_token
19
- )
20
  model = AutoModelForCausalLM.from_pretrained(
21
  "mistralai/Mistral-7B-Instruct-v0.1",
22
  torch_dtype=torch.float16,
23
  device_map="auto",
24
  token=hf_token
25
  )
26
- return pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=512)
27
-
28
- textgen = load_model()
29
-
30
- # βœ… PDF parsing
31
- def extract_text_from_pdf(file):
32
- reader = PyPDF2.PdfReader(file)
33
- return "\n".join([p.extract_text() for p in reader.pages if p.extract_text()])
34
-
35
- # βœ… UI
36
- query = st.text_input("Ask a question or enter a topic:")
37
- uploaded_file = st.file_uploader("Or upload a PDF to use as context:", type=["pdf"])
38
-
39
- context = ""
40
- if uploaded_file:
41
- context = extract_text_from_pdf(uploaded_file)
42
- st.text_area("πŸ“„ Extracted PDF Text", context, height=200)
43
-
44
- if st.button("Generate Answer"):
45
- with st.spinner("Generating answer..."):
46
- prompt = f"[INST] Use the following context to answer the question:\n\n{context}\n\nQuestion: {query} [/INST]"
47
- result = textgen(prompt)[0]["generated_text"]
48
- st.success("Answer:")
49
- st.write(result.replace(prompt, "").strip())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
 
 
 
2
  import os
3
+ import json
4
+ import torch
5
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
6
+ from ppt_parser import transfer_to_structure
7
 
8
+ # βœ… Hugging Face token for gated model access
9
+ hf_token = os.getenv("HF_TOKEN")
10
 
11
+ # βœ… Load summarization pipeline
12
+ summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
13
 
14
+ # βœ… Load Mistral 7B Instruct model
15
+ @gr.cache()
16
+ def load_mistral():
17
+ tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1", token=hf_token)
 
 
 
18
  model = AutoModelForCausalLM.from_pretrained(
19
  "mistralai/Mistral-7B-Instruct-v0.1",
20
  torch_dtype=torch.float16,
21
  device_map="auto",
22
  token=hf_token
23
  )
24
+ pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=512)
25
+ return pipe
26
+
27
+ mistral_pipe = load_mistral()
28
+
29
+ # βœ… Global text buffer
30
+ extracted_text = ""
31
+
32
+ def extract_text_from_pptx_json(parsed_json: dict) -> str:
33
+ text = ""
34
+ for slide in parsed_json.values():
35
+ for shape in slide.values():
36
+ if shape.get('type') == 'group':
37
+ for group_shape in shape.get('group_content', {}).values():
38
+ if group_shape.get('type') == 'text':
39
+ for para_key, para in group_shape.items():
40
+ if para_key.startswith("paragraph_"):
41
+ text += para.get("text", "") + "\n"
42
+ elif shape.get('type') == 'text':
43
+ for para_key, para in shape.items():
44
+ if para_key.startswith("paragraph_"):
45
+ text += para.get("text", "") + "\n"
46
+ return text.strip()
47
+
48
+ def handle_pptx_upload(pptx_file):
49
+ global extracted_text
50
+ tmp_path = pptx_file.name
51
+ parsed_json_str, _ = transfer_to_structure(tmp_path, "images")
52
+ parsed_json = json.loads(parsed_json_str)
53
+ extracted_text = extract_text_from_pptx_json(parsed_json)
54
+ return extracted_text or "No readable text found in slides."
55
+
56
+ def summarize_text():
57
+ global extracted_text
58
+ if not extracted_text:
59
+ return "Please upload and extract text from a PPTX file first."
60
+ summary = summarizer(extracted_text, max_length=200, min_length=50, do_sample=False)[0]['summary_text']
61
+ return summary
62
+
63
+ def clarify_concept(question):
64
+ global extracted_text
65
+ if not extracted_text:
66
+ return "Please upload and extract text from a PPTX file first."
67
+ prompt = f"[INST] Use the following context to answer the question:\n\n{extracted_text}\n\nQuestion: {question} [/INST]"
68
+ response = mistral_pipe(prompt)[0]["generated_text"]
69
+ return response.replace(prompt, "").strip()
70
+
71
+ # βœ… Gradio UI
72
+ with gr.Blocks() as demo:
73
+ gr.Markdown("## 🧠 AI-Powered Study Assistant for PowerPoint Lectures (Mistral 7B)")
74
+
75
+ pptx_input = gr.File(label="πŸ“‚ Upload PPTX File", file_types=[".pptx"])
76
+ extract_btn = gr.Button("πŸ“œ Extract & Summarize")
77
+
78
+ extracted_output = gr.Textbox(label="πŸ“„ Extracted Text", lines=10, interactive=False)
79
+ summary_output = gr.Textbox(label="πŸ“ Summary", interactive=False)
80
+
81
+ extract_btn.click(handle_pptx_upload, inputs=[pptx_input], outputs=[extracted_output])
82
+ extract_btn.click(summarize_text, outputs=[summary_output])
83
+
84
+ question = gr.Textbox(label="❓ Ask a Question")
85
+ ask_btn = gr.Button("πŸ’¬ Ask Mistral")
86
+ ai_answer = gr.Textbox(label="πŸ€– Mistral Answer", lines=4)
87
+
88
+ ask_btn.click(clarify_concept, inputs=[question], outputs=[ai_answer])
89
+
90
+ if __name__ == "__main__":
91
+ demo.launch()