admin08077 commited on
Commit
37bb88e
·
verified ·
1 Parent(s): 0ff0f8f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -57
app.py CHANGED
@@ -10,6 +10,7 @@ from textblob import TextBlob
10
  import PyPDF2
11
  import tempfile
12
 
 
13
  nltk.download("punkt", quiet=True)
14
 
15
  ###############################################################################
@@ -23,36 +24,47 @@ https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
23
  # Initialize your Hugging Face model client
24
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
25
 
26
- def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p, file_content):
 
 
 
 
 
 
 
 
27
  """
28
  Streams the chat response from the Hugging Face model.
29
- The uploaded file's content is appended to the system message context.
30
- Yields tokens as they arrive.
31
  """
32
  # Append file content to the system prompt if available.
33
  if file_content and file_content.strip():
34
  system_message = system_message + "\n\nFile content:\n" + file_content
35
 
36
- # Build the messages list.
37
  messages = [{"role": "system", "content": system_message}]
38
- for val in history:
39
- if val[0]:
40
- messages.append({"role": "user", "content": val[0]})
41
- if val[1]:
42
- messages.append({"role": "assistant", "content": val[1]})
43
  messages.append({"role": "user", "content": message})
44
 
45
  response = ""
46
- for partial in client.chat_completion(
47
- messages,
48
- max_tokens=max_tokens,
49
- stream=True,
50
- temperature=temperature,
51
- top_p=top_p,
52
- ):
53
- token = partial.choices[0].delta.get("content", "")
54
- response += token
55
- yield response
 
 
 
56
 
57
  ###############################################################################
58
  # File Upload & Parsing Functionality #
@@ -71,7 +83,7 @@ def parse_file(file):
71
  text = ""
72
  for page in reader.pages:
73
  extracted = page.extract_text() or ""
74
- text += extracted
75
  return text
76
  except Exception as e:
77
  return f"Error reading PDF: {e}"
@@ -93,53 +105,81 @@ def load_files(files):
93
  return all_text
94
 
95
  ###############################################################################
96
- # Gradio UI Layout #
97
  ###############################################################################
98
 
99
  with gr.Blocks() as demo:
100
- gr.Markdown("# Combined Chat & File Upload App")
101
  gr.Markdown(
102
  """
103
- This app allows you to upload file(s) and chat with an AI assistant that references the uploaded file(s) throughout the conversation.
104
- - **Step 1:** Upload your file(s) (e.g., PDF or TXT).
105
- - **Step 2:** Click **Load File(s)** to parse and store the file content.
106
- - **Step 3:** Chat with the AI—the uploaded file's content will be appended to the context on every prompt.
107
- """
 
108
  )
109
 
110
- # Create a state to store the file's parsed content.
111
  file_content_state = gr.State("")
112
-
 
113
  with gr.Row():
114
- file_input = gr.File(label="Upload File(s)", file_count="multiple")
115
- load_button = gr.Button("Load File(s)")
116
 
117
- # When the Load button is clicked, concatenate file contents into file_content_state.
118
- load_button.click(fn=load_files, inputs=file_input, outputs=file_content_state)
 
 
 
 
 
 
119
 
120
- gr.Markdown("## Chat with AI (using the uploaded file's content as context)")
121
- # Note: We use Gradio’s ChatInterface which streams responses from the client.
122
- demo_chat = gr.ChatInterface(
123
- fn=respond,
124
- additional_inputs=[
125
- gr.Textbox(
126
- value="You are a helpful AI assistant that uses the uploaded file's content as context.",
127
- label="System message",
128
- ),
129
- gr.Slider(
130
- minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"
131
- ),
132
- gr.Slider(
133
- minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"
134
- ),
135
- gr.Slider(
136
- minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"
137
- ),
138
- file_content_state, # The uploaded file's content is passed into each chat call.
139
- ],
140
- )
141
 
142
- demo.launch()
 
 
143
 
144
- if __name__ == "__main__":
145
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  import PyPDF2
11
  import tempfile
12
 
13
+ # Download the NLTK punkt tokenizer if not already present
14
  nltk.download("punkt", quiet=True)
15
 
16
  ###############################################################################
 
24
  # Initialize your Hugging Face model client
25
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
26
 
27
+ def respond(
28
+ message,
29
+ history: list[tuple[str, str]],
30
+ system_message,
31
+ max_tokens,
32
+ temperature,
33
+ top_p,
34
+ file_content
35
+ ):
36
  """
37
  Streams the chat response from the Hugging Face model.
38
+ Includes file content as part of the system message for context.
39
+ Yields tokens as they arrive, so Gradio can display partial responses.
40
  """
41
  # Append file content to the system prompt if available.
42
  if file_content and file_content.strip():
43
  system_message = system_message + "\n\nFile content:\n" + file_content
44
 
45
+ # Build the messages list for the API request
46
  messages = [{"role": "system", "content": system_message}]
47
+ for user_msg, assistant_msg in history:
48
+ if user_msg:
49
+ messages.append({"role": "user", "content": user_msg})
50
+ if assistant_msg:
51
+ messages.append({"role": "assistant", "content": assistant_msg})
52
  messages.append({"role": "user", "content": message})
53
 
54
  response = ""
55
+ try:
56
+ for partial in client.chat_completion(
57
+ messages,
58
+ max_tokens=max_tokens,
59
+ stream=True,
60
+ temperature=temperature,
61
+ top_p=top_p,
62
+ ):
63
+ token = partial.choices[0].delta.get("content", "")
64
+ response += token
65
+ yield response
66
+ except Exception as e:
67
+ yield f"Error during model response: {e}"
68
 
69
  ###############################################################################
70
  # File Upload & Parsing Functionality #
 
83
  text = ""
84
  for page in reader.pages:
85
  extracted = page.extract_text() or ""
86
+ text += extracted + "\n"
87
  return text
88
  except Exception as e:
89
  return f"Error reading PDF: {e}"
 
105
  return all_text
106
 
107
  ###############################################################################
108
+ # Gradio UI Layout #
109
  ###############################################################################
110
 
111
  with gr.Blocks() as demo:
112
+ gr.Markdown("# **Combined Chat & File Upload App**")
113
  gr.Markdown(
114
  """
115
+ This app allows you to upload file(s) and chat with an AI assistant that references the uploaded file(s) throughout the conversation.
116
+
117
+ - **Step 1:** Upload your file(s) (e.g., PDF or TXT).
118
+ - **Step 2:** The app will automatically parse and send the file content to the AI.
119
+ - **Step 3:** Start chatting with the AI—the uploaded file's content will be used as context.
120
+ """
121
  )
122
 
123
+ # States to hold file content and chat history
124
  file_content_state = gr.State("")
125
+ chat_history_state = gr.State([])
126
+
127
  with gr.Row():
128
+ file_input = gr.File(label="Upload File(s)", file_count="multiple", type="file")
 
129
 
130
+ # Function to handle file uploads and send initial context to AI
131
+ def handle_file_upload(files):
132
+ if not files:
133
+ return "", []
134
+ file_content = load_files(files)
135
+ # Optionally, you can generate an initial AI response acknowledging the file upload
136
+ # For simplicity, we'll just store the file content
137
+ return file_content, []
138
 
139
+ file_input.change(fn=handle_file_upload, inputs=file_input, outputs=[file_content_state, chat_history_state])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
+ with gr.Column():
142
+ chatbot = gr.Chatbot(label="Chat History")
143
+ user_input = gr.Textbox(label="Your message", placeholder="Type your message here and press Enter...")
144
 
145
+ def handle_user_message(user_message, chat_history, file_content):
146
+ if not user_message.strip():
147
+ return "", chat_history # Ignore empty messages
148
+
149
+ # Append the user's message to the chat history
150
+ chat_history.append((user_message, None))
151
+
152
+ # Generate the AI's response
153
+ ai_response = ""
154
+ try:
155
+ response_generator = respond(
156
+ message=user_message,
157
+ history=chat_history,
158
+ system_message="You are a helpful AI assistant.",
159
+ max_tokens=512,
160
+ temperature=0.7,
161
+ top_p=0.95,
162
+ file_content=file_content
163
+ )
164
+ for response in response_generator:
165
+ ai_response = response
166
+ # Update the last entry in chat_history with the AI's response
167
+ chat_history[-1] = (user_message, ai_response)
168
+ yield "", chat_history # Clear the input and update the chat
169
+ except Exception as e:
170
+ chat_history[-1] = (user_message, f"Error: {e}")
171
+ yield "", chat_history
172
+
173
+ # Use Gradio's `submit` event on the textbox to handle messages
174
+ user_input.submit(
175
+ handle_user_message,
176
+ inputs=[user_input, chat_history_state, file_content_state],
177
+ outputs=[user_input, chatbot],
178
+ queue=False
179
+ )
180
+
181
+ # Alternatively, use a button to send messages (optional)
182
+ # send_button = gr.Button("Send")
183
+ # send_button.click(handle_user_message, inputs=[user_input, chat_history_state, file_content_state], outputs=[user_input, chatbot])
184
+
185
+ demo.launch(server_name="0.0.0.0", server_port=7860)