adv1102 commited on
Commit
cd87d54
·
verified ·
1 Parent(s): 34187cd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -57
app.py CHANGED
@@ -1,64 +1,168 @@
 
 
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
+ # main.py
2
+ import os
3
  import gradio as gr
4
+ import tempfile
5
+ from dotenv import load_dotenv
6
+ from modules.document_processor import process_document
7
+ from modules.model_handler import get_model_response, get_qa_response
8
+ from modules.config import MODEL_MAPPING, DEFAULT_PARAMETERS
9
 
10
+ # Load environment variables
11
+ load_dotenv()
 
 
12
 
13
+ def setup_api_key(api_key=None):
14
+ """Set up the HuggingFace API key from input or environment variables."""
15
+ if api_key and api_key.startswith('hf_'):
16
+ os.environ['HF_TOKEN'] = api_key
17
+ return True, "API key set successfully! ✅"
18
+ elif os.getenv('HF_TOKEN') and os.getenv('HF_TOKEN').startswith('hf_'):
19
+ return True, "API key already available! ✅"
20
+ else:
21
+ return False, "Please enter a valid HuggingFace API key. ⚠️"
22
 
23
+ def create_chat_interface():
24
+ """Create the main chat interface for the application."""
25
+ with gr.Blocks(title="💬 Small Language Models - POC") as demo:
26
+ # Application header
27
+ gr.Markdown("# 💬 Small Language Models - POC")
28
+ gr.Markdown("This chatbot uses various Language Models such as Llama 3.2, Gemma 2, Gemma 3, Phi 3.5, DeepSeek-V3, and DeepSeek-R1.")
29
+
30
+ with gr.Row():
31
+ with gr.Column(scale=1):
32
+ # Sidebar configuration
33
+ with gr.Group():
34
+ api_key_input = gr.Textbox(
35
+ label="HuggingFace API Token",
36
+ placeholder="Enter your HF API token (hf_...)",
37
+ type="password"
38
+ )
39
+ api_key_status = gr.Markdown("Please enter your API key.")
40
+ api_key_button = gr.Button("Set API Key")
41
+
42
+ with gr.Group():
43
+ gr.Markdown("## Models and Parameters")
44
+ model_dropdown = gr.Dropdown(
45
+ choices=list(MODEL_MAPPING.keys()),
46
+ label="Select Model",
47
+ value=list(MODEL_MAPPING.keys())[0]
48
+ )
49
+
50
+ temperature_slider = gr.Slider(
51
+ label="Temperature",
52
+ minimum=0.01,
53
+ maximum=1.0,
54
+ value=DEFAULT_PARAMETERS["temperature"],
55
+ step=0.01
56
+ )
57
+
58
+ top_p_slider = gr.Slider(
59
+ label="Top P",
60
+ minimum=0.01,
61
+ maximum=1.0,
62
+ value=DEFAULT_PARAMETERS["top_p"],
63
+ step=0.01
64
+ )
65
+
66
+ max_length_slider = gr.Slider(
67
+ label="Max Length",
68
+ minimum=20,
69
+ maximum=2040,
70
+ value=DEFAULT_PARAMETERS["max_length"],
71
+ step=5
72
+ )
73
+
74
+ clear_button = gr.Button("Clear Chat History")
75
+
76
+ with gr.Group():
77
+ gr.Markdown("## Document Upload")
78
+ file_upload = gr.File(
79
+ label="Upload Document (PDF, DOCX, TXT)",
80
+ file_types=["pdf", "docx", "txt"]
81
+ )
82
+ upload_status = gr.Markdown("")
83
 
84
+ with gr.Column(scale=2):
85
+ # Chat interface
86
+ chatbot = gr.Chatbot(
87
+ label="Conversation",
88
+ height=500,
89
+ bubble_full_width=False
90
+ )
91
+ msg = gr.Textbox(
92
+ label="Enter your message",
93
+ placeholder="Type your message here...",
94
+ show_label=False
95
+ )
96
+
97
+ # State variables to track conversation and document processing
98
+ conversation_state = gr.State([])
99
+ document_store = gr.State(None)
100
+ api_key_state = gr.State(False)
101
+
102
+ # Set up event handlers
103
+ api_key_button.click(
104
+ setup_api_key,
105
+ inputs=[api_key_input],
106
+ outputs=[api_key_state, api_key_status]
107
+ )
108
+
109
+ file_upload.upload(
110
+ process_document,
111
+ inputs=[file_upload, api_key_state],
112
+ outputs=[document_store, upload_status]
113
+ )
114
+
115
+ # Function to handle chat messages
116
+ def respond(message, conversation, model_name, temp, top_p, max_len, doc_store, api_ready):
117
+ if not api_ready:
118
+ return conversation, conversation, "Please set a valid API key first. ⚠️"
119
+
120
+ if not message.strip():
121
+ return conversation, conversation, upload_status.value
122
+
123
+ # Update conversation with user message
124
+ conversation.append([message, None])
125
+ yield conversation, conversation, upload_status.value
126
+
127
+ # Generate response based on whether document is uploaded
128
+ if doc_store is not None:
129
+ response = get_qa_response(
130
+ message,
131
+ model_name,
132
+ doc_store,
133
+ {"temperature": temp, "top_p": top_p, "max_length": max_len}
134
+ )
135
+ else:
136
+ response = get_model_response(
137
+ message,
138
+ conversation,
139
+ model_name,
140
+ {"temperature": temp, "top_p": top_p, "max_length": max_len}
141
+ )
142
+
143
+ # Update conversation with assistant response
144
+ conversation[-1][1] = response
145
+ yield conversation, conversation, upload_status.value
146
+
147
+ # Function to clear chat history
148
+ def clear_history():
149
+ return [], gr.update(value="Chat history cleared.")
150
+
151
+ # Connect events
152
+ msg.submit(
153
+ respond,
154
+ [msg, conversation_state, model_dropdown, temperature_slider, top_p_slider, max_length_slider, document_store, api_key_state],
155
+ [chatbot, conversation_state, upload_status]
156
+ )
157
+
158
+ clear_button.click(
159
+ clear_history,
160
+ outputs=[conversation_state, upload_status]
161
+ )
162
+
163
+ return demo
164
 
165
  if __name__ == "__main__":
166
+ # Create and launch the application
167
+ app = create_chat_interface()
168
+ app.launch(share=False)