ankban commited on
Commit
ae01722
Β·
verified Β·
1 Parent(s): 4cbb464

Update file_viewer_panel.py

Browse files
Files changed (1) hide show
  1. file_viewer_panel.py +51 -41
file_viewer_panel.py CHANGED
@@ -1,76 +1,81 @@
1
  import gradio as gr
2
  import os
 
3
  import json
4
  from pdf2image import convert_from_path
5
- from file_utils import extract_text_from_file, call_llm
6
 
7
  def file_viewer_dashboard():
8
- with gr.Column(scale=4, elem_id="main-column") as file_panel: # βœ… define this
 
 
9
  with gr.Row():
10
- file_upload = gr.File(label="πŸ“‚ Upload a File", file_types=[".pdf", ".txt", ".md", ".pptx"])
11
- file_viewer = gr.HTML(label="πŸ“„ File Preview")
 
 
12
 
13
- with gr.Column(scale=2):
14
- generate_quiz_btn = gr.Button("🧠 Practice Questions")
15
- quiz_container = gr.Column(visible=False)
16
- chat_output = gr.Chatbot(label="Ask a question to learn more about the file")
17
- chat_input = gr.Textbox(label="", placeholder="Ask ChatEDU a question...")
18
 
19
  file_text_state = gr.State("")
20
  chat_state = gr.State([])
21
 
22
- def render_file(file):
23
- if not file:
24
- return "", "", []
25
-
26
- ext = os.path.splitext(file.name)[1].lower()
27
- text = extract_text_from_file(file)
28
-
29
  if ext == ".pdf":
30
  output_dir = "/tmp/pdf_images"
31
  os.makedirs(output_dir, exist_ok=True)
32
- images = convert_from_path(file.name, dpi=150, fmt="png", output_folder=output_dir)
33
- img_tags = [
34
- f"<img src='/file={os.path.join(output_dir, f'page_{i}.png')}' style='width:100%; margin-bottom: 10px; border-radius: 8px;'/>"
35
- for i in range(len(images))
36
- ]
37
  for i, img in enumerate(images):
38
  img.save(os.path.join(output_dir, f"page_{i}.png"), "PNG")
39
- viewer_html = "".join(img_tags)
40
- else:
41
- viewer_html = f"<pre style='padding:12px; background:#f9f9f9; white-space:pre-wrap;'>{text}</pre>"
 
 
42
 
43
- return viewer_html, text, [] # Reset chat on new file
 
 
44
 
45
- def ask_question_with_context(user_input, text, history):
46
- if not user_input.strip():
47
- return history, history
48
 
49
- messages = [{"role": "system", "content": "You are a helpful tutor. Answer only using the content provided."}]
50
- if len(text) > 8000:
51
- text = text[:8000] + "\n\n[Truncated due to token limits]"
52
 
53
- messages.append({"role": "user", "content": f"Document Content:\n{text}"})
 
54
 
 
 
 
 
 
 
 
55
  for user_msg, bot_reply in history:
56
  messages.append({"role": "user", "content": user_msg})
57
  messages.append({"role": "assistant", "content": bot_reply})
58
-
59
  messages.append({"role": "user", "content": user_input})
60
  response = call_llm(messages=messages)
61
-
62
  history.append((user_input, response))
63
  return history, history
64
 
65
  def generate_quiz(text):
66
  prompt = (
67
- "Generate 5 multiple choice questions from this document. "
68
- "Return a JSON list where each item has:\n- question\n- options (list)\n- answer (correct one)"
69
  )
70
  try:
71
  result = call_llm(prompt=prompt)
72
  questions = json.loads(result)
73
-
74
  components = []
75
  for idx, q in enumerate(questions):
76
  q_md = gr.Markdown(f"**Q{idx+1}. {q['question']}**")
@@ -82,14 +87,19 @@ def file_viewer_dashboard():
82
 
83
  radio.change(fn=check, inputs=[radio], outputs=[feedback])
84
  components.extend([q_md, radio, feedback])
85
-
86
  return gr.update(visible=True), components
87
  except:
88
  return gr.update(visible=False), []
89
 
90
- # Hook up logic
91
- file_upload.change(fn=render_file, inputs=[file_upload], outputs=[file_viewer, file_text_state, chat_output])
92
- chat_input.submit(fn=ask_question_with_context, inputs=[chat_input, file_text_state, chat_state], outputs=[chat_output, chat_state])
 
 
 
 
 
 
93
  generate_quiz_btn.click(fn=generate_quiz, inputs=[file_text_state], outputs=[quiz_container])
94
 
95
  return file_panel
 
1
  import gradio as gr
2
  import os
3
+ import shutil
4
  import json
5
  from pdf2image import convert_from_path
6
+ from file_utils import extract_text_from_file, call_llm, save_user_file, fetch_user_files
7
 
8
  def file_viewer_dashboard():
9
+ with gr.Column(scale=4, elem_id="main-column") as file_panel:
10
+ nickname_input = gr.Textbox(label="πŸ‘€ Your Nickname", placeholder="Enter your name")
11
+
12
  with gr.Row():
13
+ with gr.Column(scale=3):
14
+ user_file_list = gr.Radio(label="πŸ“ Your Uploaded Files", choices=[], interactive=True)
15
+ file_upload = gr.File(label="πŸ“‚ Upload a New File", file_types=[".pdf", ".txt", ".md", ".pptx"])
16
+ file_viewer = gr.HTML(label="πŸ“„ File Preview")
17
 
18
+ with gr.Column(scale=2):
19
+ generate_quiz_btn = gr.Button("🧠 Practice Questions")
20
+ quiz_container = gr.Column(visible=False)
21
+ chat_output = gr.Chatbot(label="Ask a question about the file")
22
+ chat_input = gr.Textbox(label="", placeholder="Ask ChatEDU a question...")
23
 
24
  file_text_state = gr.State("")
25
  chat_state = gr.State([])
26
 
27
+ def render_file_as_html(filename, text):
28
+ ext = os.path.splitext(filename)[1].lower()
 
 
 
 
 
29
  if ext == ".pdf":
30
  output_dir = "/tmp/pdf_images"
31
  os.makedirs(output_dir, exist_ok=True)
32
+ images = convert_from_path(filename, dpi=150, fmt="png", output_folder=output_dir)
 
 
 
 
33
  for i, img in enumerate(images):
34
  img.save(os.path.join(output_dir, f"page_{i}.png"), "PNG")
35
+ return "".join([
36
+ f"<img src='/file={os.path.join(output_dir, f'page_{i}.png')}' style='width:100%; margin-bottom:10px;'/>"
37
+ for i in range(len(images))
38
+ ])
39
+ return f"<pre style='padding:12px; background:#f9f9f9; white-space:pre-wrap;'>{text}</pre>"
40
 
41
+ def handle_file_upload(file, nickname):
42
+ if not file or not nickname:
43
+ return "", "", [], []
44
 
45
+ filename = os.path.basename(file.name)
46
+ saved_path = f"/tmp/{filename}"
47
+ shutil.copy(file.name, saved_path)
48
 
49
+ save_user_file(nickname, filename, saved_path)
50
+ text = extract_text_from_file(file)
51
+ html = render_file_as_html(file.name, text)
52
 
53
+ user_files = fetch_user_files(nickname)
54
+ file_choices = [f"{f.filename} ({f.timestamp})" for f in user_files]
55
 
56
+ return html, text, file_choices, []
57
+
58
+ def ask_question(user_input, text, history):
59
+ if not user_input.strip():
60
+ return history, history
61
+ messages = [{"role": "system", "content": "You are a tutor. Only use the document below."}]
62
+ messages.append({"role": "user", "content": f"Document:\n{text}"})
63
  for user_msg, bot_reply in history:
64
  messages.append({"role": "user", "content": user_msg})
65
  messages.append({"role": "assistant", "content": bot_reply})
 
66
  messages.append({"role": "user", "content": user_input})
67
  response = call_llm(messages=messages)
 
68
  history.append((user_input, response))
69
  return history, history
70
 
71
  def generate_quiz(text):
72
  prompt = (
73
+ "Generate 5 multiple choice questions from the document. "
74
+ "Each question should have:\n- question\n- options (list)\n- answer (string). Return JSON."
75
  )
76
  try:
77
  result = call_llm(prompt=prompt)
78
  questions = json.loads(result)
 
79
  components = []
80
  for idx, q in enumerate(questions):
81
  q_md = gr.Markdown(f"**Q{idx+1}. {q['question']}**")
 
87
 
88
  radio.change(fn=check, inputs=[radio], outputs=[feedback])
89
  components.extend([q_md, radio, feedback])
 
90
  return gr.update(visible=True), components
91
  except:
92
  return gr.update(visible=False), []
93
 
94
+ def load_user_files(nickname):
95
+ files = fetch_user_files(nickname)
96
+ return [f"{f.filename} ({f.timestamp})" for f in files]
97
+
98
+ nickname_input.change(fn=load_user_files, inputs=[nickname_input], outputs=[user_file_list])
99
+ file_upload.change(fn=handle_file_upload, inputs=[file_upload, nickname_input],
100
+ outputs=[file_viewer, file_text_state, user_file_list, chat_output])
101
+ chat_input.submit(fn=ask_question, inputs=[chat_input, file_text_state, chat_state],
102
+ outputs=[chat_output, chat_state])
103
  generate_quiz_btn.click(fn=generate_quiz, inputs=[file_text_state], outputs=[quiz_container])
104
 
105
  return file_panel