File size: 10,736 Bytes
28758a3 e2ce2c6 28758a3 e2ce2c6 28758a3 e2ce2c6 28758a3 76016a4 f12d140 b013055 4fd8c80 969ba3a f12d140 28758a3 f12d140 28758a3 f12d140 e2ce2c6 f12d140 e2ce2c6 76016a4 e2ce2c6 76016a4 e2ce2c6 f12d140 e2ce2c6 f12d140 e2ce2c6 f12d140 e2ce2c6 f12d140 e2ce2c6 f12d140 e2ce2c6 f12d140 e2ce2c6 76016a4 f12d140 76016a4 e2ce2c6 f12d140 28758a3 2df7aa9 ddaf851 a73a7bc 2df7aa9 a73a7bc 2df7aa9 a73a7bc 2df7aa9 a73a7bc 2df7aa9 a73a7bc 969ba3a 8bf0323 969ba3a 2df7aa9 a73a7bc 8bf0323 a73a7bc 2df7aa9 a73a7bc 2df7aa9 a73a7bc 4cdf80c 2df7aa9 4cdf80c 2df7aa9 4cdf80c 2df7aa9 4cdf80c 969ba3a a73a7bc 2df7aa9 a73a7bc 2df7aa9 a73a7bc 7529434 969ba3a 2df7aa9 7529434 2df7aa9 7529434 969ba3a 2df7aa9 969ba3a 2df7aa9 969ba3a 7529434 2df7aa9 7529434 2df7aa9 7529434 ddaf851 a42464a ddaf851 e2ce2c6 a73a7bc e2ce2c6 c54f5d5 d0c8c26 e2ce2c6 c54f5d5 315bcc1 773081a 6fb4dc9 9448f40 4cdf80c 969ba3a c54f5d5 a42464a 76016a4 c54f5d5 76016a4 c54f5d5 a42464a f12d140 a42464a 9448f40 f12d140 76016a4 f12d140 a42464a 9448f40 f12d140 76016a4 4cdf80c a42464a f12d140 a42464a 4cdf80c a42464a 4cdf80c a42464a 4cdf80c f12d140 a42464a 4cdf80c a42464a 969ba3a 28758a3 ddaf851 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
import gradio as gr
import os
from huggingface_hub import InferenceClient
from huggingface_hub.inference._generated.types.chat_completion import ChatCompletionStreamOutput
MODEL = "nomiChroma3.1"
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
def respond(
message: str,
chat_history: list[tuple[str, str]],
max_tokens: int,
temperature: float,
top_p: float,
) -> tuple[list[tuple[str, str]], str]:
"""
Generate a response and update chat history.
Returns tuple of (new_history, None) to clear input box.
"""
system_message = "You are a maritime legal assistant with expertise strictly in Indian maritime law. Provide detailed legal advice and information within word limit based on Indian maritime legal principles and regulations."
messages = [{"role": "system", "content": system_message}]
for user_msg, assistant_msg in chat_history:
messages.extend([
{"role": "user", "content": user_msg},
{"role": "assistant", "content": assistant_msg}
])
messages.append({"role": "user", "content": message})
chat_history = chat_history + [(message, None)]
response = ""
try:
for chunk in client.chat_completion(
messages,
max_tokens=max_tokens,
stream=True,
temperature=temperature,
top_p=top_p,
):
try:
if isinstance(chunk, ChatCompletionStreamOutput):
content = chunk.choices[0].delta.content
if content:
response += content
chat_history[-1] = (message, response)
yield chat_history, ""
if chunk.choices[0].finish_reason == 'stop':
break
elif isinstance(chunk, dict):
content = chunk.get('choices', [{}])[0].get('delta', {}).get('content')
if content:
response += content
chat_history[-1] = (message, response)
yield chat_history, ""
if chunk.get('choices', [{}])[0].get('finish_reason') == 'stop':
break
elif isinstance(chunk, str) and chunk.strip():
response += chunk
chat_history[-1] = (message, response)
yield chat_history, ""
except Exception as e:
print(f"Error processing chunk: {e}")
continue
if not response:
chat_history[-1] = (message, "I apologize, but I couldn't generate a response. Please try again.")
yield chat_history, ""
except Exception as e:
error_msg = f"An error occurred: {str(e)}"
chat_history[-1] = (message, error_msg)
yield chat_history, ""
# [Previous imports and respond function remain unchanged]
custom_css = """
/* Global styles */
.gradio-container {
background-color: #1a365d !important;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif !important;
}
/* Header styling */
.header-container {
text-align: center;
padding: 1rem 0;
margin-bottom: 1rem;
border-bottom: 2px solid rgba(255, 255, 255, 0.1);
}
.header-title {
color: #ffffff;
font-size: 2rem;
margin-bottom: 0.3rem;
font-family: inherit;
}
.header-subtitle {
color: #e6f3ff;
font-size: 1rem;
margin-bottom: 0.2rem;
font-family: inherit;
}
/* Sidebar styling */
.sidebar {
background: #e6f3ff !important;
border-radius: 8px !important;
padding: 15px !important;
border: 1px solid rgba(176, 226, 255, 0.2) !important;
height: fit-content !important;
}
.sidebar-title {
color: #1a365d !important;
font-size: 1.1rem !important;
margin-bottom: 0.8rem !important;
padding-bottom: 0.4rem !important;
border-bottom: 2px solid rgba(26, 54, 93, 0.1) !important;
font-family: inherit !important;
}
/* Example queries styling */
.example-queries {
margin-bottom: 1.5rem !important;
}
.example-query-button {
background-color: #cce7ff !important;
color: #1a365d !important;
border: none !important;
margin: 3px 0 !important;
padding: 6px 10px !important;
border-radius: 4px !important;
text-align: left !important;
width: 100% !important;
cursor: pointer !important;
transition: background-color 0.3s ease !important;
font-size: 0.9rem !important;
font-family: inherit !important;
}
.example-query-button:hover {
background-color: #b0e2ff !important;
}
/* Chat container */
.chat-container {
background: #e6f3ff !important;
border-radius: 8px !important;
padding: 15px !important;
height: 300px !important;
overflow-y: auto !important;
border: 1px solid rgba(176, 226, 255, 0.2) !important;
backdrop-filter: blur(10px) !important;
font-family: inherit !important;
}
/* Message styling */
.message.user, .message.bot {
padding: 8px 12px !important;
margin: 6px 0 !important;
border-radius: 6px !important;
color: #1a365d !important;
font-size: 0.9rem !important;
font-family: inherit !important;
line-height: 1.5 !important;
}
.message.user {
background-color: #cce7ff !important;
}
.message.bot {
background-color: #e6f3ff !important;
}
/* Chat input styling */
textarea {
background-color: #e6f3ff !important;
border: 1px solid rgba(176, 226, 255, 0.3) !important;
border-radius: 6px !important;
padding: 8px !important;
color: #1a365d !important;
font-size: 0.9rem !important;
font-family: inherit !important;
}
/* Button styling */
.gr-button {
background-color: #cce7ff !important;
color: #1a365d !important;
border: none !important;
padding: 6px 12px !important;
font-size: 0.9rem !important;
font-family: inherit !important;
border-radius: 4px !important;
}
.gr-button:hover {
background-color: #1a365d !important;
color: #ffffff !important;
}
/* Markdown text styling */
.prose {
font-family: inherit !important;
}
/* All text elements */
p, span, div {
font-family: inherit !important;
}
"""
def handle_example_click(example_query: str):
"""Handle example query click by returning the query and empty chat history"""
return example_query, []
# Main application
with gr.Blocks(css=custom_css, theme=gr.themes.Base()) as demo:
# Header
gr.HTML("""
<div class="header-container">
<h1 class="header-title">Maritime Legal Compliance</h1>
<p class="header-subtitle">AI-powered assistance for Indian maritime law queries</p>
<p class="header-subtitle">This chatbot uses Fine-tuned LLAMA-3.1 model personalised specifically to provide assistance with Indian maritime legal queries.</p>
</div>
""")
with gr.Row():
# Sidebar
with gr.Column(scale=1, elem_classes="sidebar"):
gr.Markdown("### Example Queries", elem_classes="sidebar-title")
example_queries = [
"What are the key regulations governing ports in India?",
"Explain the concept of cabotage in Indian maritime law.",
"What are the legal requirements for registering a vessel in India?",
"What are the environmental regulations for ships in Indian waters?",
"Explain the Maritime Labour Convention implementation in India.",
"What are the rules for coastal cargo transportation in India?"
]
with gr.Column(elem_classes="example-queries"):
example_buttons = [gr.Button(query, elem_classes="example-query-button") for query in example_queries]
gr.Markdown("### Configuration", elem_classes="sidebar-title")
max_tokens = gr.Slider(
minimum=1,
maximum=2048,
value=512,
step=1,
label="Response Length"
)
temperature = gr.Slider(
minimum=0.1,
maximum=4.0,
value=0.7,
step=0.1,
label="Creativity Level"
)
top_p = gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.95,
step=0.05,
label="Response Focus"
)
# Main chat area
with gr.Column(scale=3):
chatbot = gr.Chatbot(height=300, elem_classes="chat-container")
msg = gr.Textbox(
show_label=False,
placeholder="Type your maritime law query here...",
container=False
)
with gr.Row():
submit = gr.Button("Send", variant="primary")
clear = gr.Button("Clear")
# Event handlers for main chat
msg.submit(
fn=respond,
inputs=[msg, chatbot, max_tokens, temperature, top_p],
outputs=[chatbot, msg]
)
submit.click(
fn=respond,
inputs=[msg, chatbot, max_tokens, temperature, top_p],
outputs=[chatbot, msg]
)
clear.click(
fn=lambda: ([], ""),
inputs=None,
outputs=[chatbot, msg],
queue=False
)
# Fixed example query handlers
for button in example_buttons:
# First click sets the query text
button.click(
fn=handle_example_click,
inputs=[button],
outputs=[msg, chatbot],
queue=False
).then( # Then immediately trigger the response
fn=respond,
inputs=[msg, chatbot, max_tokens, temperature, top_p],
outputs=[chatbot, msg]
)
if __name__ == "__main__":
demo.launch() |