HonestGrad commited on
Commit
752bc47
·
verified ·
1 Parent(s): a440fbb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -51
app.py CHANGED
@@ -1,64 +1,97 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
 
8
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
27
 
28
- response = ""
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
+ import PyPDF2
3
+ import os
4
+ from openai import OpenAI
5
 
6
+ # Function to extract text from PDF
7
+ def extract_text_from_pdf(pdf_file):
8
+ reader = PyPDF2.PdfReader(pdf_file)
9
+ text = ""
10
+ for page in reader.pages:
11
+ if page == reader.pages[0]:
12
+ continue
13
+ text += page.extract_text() + "\n"
14
+ return text
15
 
16
+ # Mock LLM response function
17
+ # Replace this with your actual LLM integration
18
 
19
+ client = OpenAI(
20
+ base_url="https://api.studio.nebius.com/v1/",
21
+ api_key=os.environ.get("NEBIUS_API_KEY")
22
+ )
 
 
 
 
 
23
 
24
+ def answer_question(pdf_text, question, history):
25
+ # You may want to truncate pdf_text if it's too long for the model
26
+ context = pdf_text[:16000] # adjust as needed
27
+ messages = [
28
+ {"role": "system", "content": '''You are a helpful assistant who specializes in body composition, diet, and exercise.
29
+ Answer questions based on the provided document. Encourage the user to seek a professional if they have serious concerns whenever appropriate.'''},
30
+ {"role": "user", "content": f"Document: {context}"},
31
+ {"role": "user", "content": f"Question: {question}"}
32
+ ]
33
+ if history:
34
+ for msg in history:
35
+ if msg["role"] in ["user", "assistant"]:
36
+ messages.append(msg)
37
+ # Add the new user question
38
+ messages.append({"role": "user", "content": question})
39
 
40
+ response = client.chat.completions.create(
41
+ model="meta-llama/Meta-Llama-3.1-70B-Instruct",
42
+ temperature=0.6,
43
+ top_p=0.95,
44
+ messages=messages
45
+ )
46
+ return response.choices[0].message.content
47
 
48
+ # Gradio chatbot logic
49
+ class PDFChatbot:
50
+ def __init__(self):
51
+ self.pdf_text = None
52
 
53
+ def upload_pdf(self, pdf_file):
54
+ if pdf_file is None:
55
+ return "No PDF uploaded."
56
+ self.pdf_text = extract_text_from_pdf(pdf_file)
57
+ return "PDF uploaded and processed. You can now ask questions."
 
 
 
58
 
59
+ def chat(self, message, history):
60
+ if self.pdf_text is None:
61
+ return "Please upload a PDF first.", history
62
+ # Ensure history is a list of dicts with 'role' and 'content'
63
+ if history is None:
64
+ history = []
65
+ # Only keep user/assistant messages for context
66
+ context_history = [msg for msg in history if msg["role"] in ["user", "assistant"]]
67
+ answer = answer_question(self.pdf_text, message, context_history)
68
+ print("User:", message)
69
+ print("LLM Answer:", answer)
70
+ history = history + [
71
+ {"role": "user", "content": message},
72
+ {"role": "assistant", "content": answer}
73
+ ]
74
+ return "", history
75
 
76
+ pdf_bot = PDFChatbot()
77
 
78
+ with gr.Blocks() as demo:
79
+ gr.Markdown("Body Composition Agent\nUpload a PDF of your recent body spec or any other document you use to track your body composition and ask questions about its content.")
80
+ pdf_file = gr.File(label="Upload PDF", file_types=[".pdf"])
81
+ upload_btn = gr.Button("Process PDF")
82
+ upload_status = gr.Textbox(label="Status", interactive=False)
83
+ chatbot = gr.Chatbot(type="messages")
84
+ msg = gr.Textbox(label="Your question:")
85
+ submit_btn = gr.Button("Submit")
86
+
87
+ def handle_upload(pdf):
88
+ return pdf_bot.upload_pdf(pdf)
89
+
90
+ def handle_chat(message, history):
91
+ return pdf_bot.chat(message, history)
 
 
 
 
92
 
93
+ upload_btn.click(handle_upload, inputs=pdf_file, outputs=upload_status)
94
+ submit_btn.click(handle_chat, inputs=[msg, chatbot], outputs=[msg, chatbot])
95
+ msg.submit(handle_chat, inputs=[msg, chatbot], outputs=[msg, chatbot])
96
 
97
+ demo.launch()