deepakdethliya commited on
Commit
b101822
·
verified ·
1 Parent(s): a0df9d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -118
app.py CHANGED
@@ -1,139 +1,126 @@
1
- import os
2
- import torch
3
  import gradio as gr
4
- from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
5
- from peft import PeftModel
6
- from threading import Thread
 
 
 
 
 
 
 
 
 
 
7
 
8
- BASE_MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
9
- ADAPTER_MODEL_ID = "vsple/LegalBuddy-Qwen-1.5B"
 
10
 
11
- print("Loading tokenizer...")
12
- tokenizer = AutoTokenizer.from_pretrained(
13
- BASE_MODEL_ID,
14
- trust_remote_code=True
15
- )
 
16
 
17
- print("Loading base model...")
18
- base_model = AutoModelForCausalLM.from_pretrained(
19
- BASE_MODEL_ID,
20
- device_map="auto",
21
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
22
- trust_remote_code=True
23
- )
 
24
 
25
- print("Loading adapter...")
26
- model = PeftModel.from_pretrained(
27
- base_model,
28
- ADAPTER_MODEL_ID
29
- )
30
- model.eval()
31
 
32
- def predict(message, history, system_prompt, max_tokens, temperature, top_p):
33
  messages = [{"role": "system", "content": system_prompt}]
 
 
 
34
 
35
- # Process history (which is now a list of dictionaries)
36
- for msg in history:
37
- messages.append(msg)
38
-
39
- messages.append({"role": "user", "content": message})
40
-
41
- prompt = tokenizer.apply_chat_template(
42
- messages,
43
- tokenize=False,
44
- add_generation_prompt=True
45
- )
46
 
47
- inputs = tokenizer([prompt], return_tensors="pt").to(model.device)
48
- streamer = TextIteratorStreamer(
49
- tokenizer,
50
- skip_prompt=True,
51
- skip_special_tokens=True
52
- )
53
-
54
- generation_kwargs = dict(
55
- inputs,
56
- streamer=streamer,
57
- max_new_tokens=max_tokens,
58
- do_sample=True,
59
- temperature=temperature,
60
- top_p=top_p
61
- )
62
-
63
- thread = Thread(target=model.generate, kwargs=generation_kwargs)
64
- thread.start()
65
-
66
- partial = ""
67
- for new_text in streamer:
68
- partial += new_text
69
- yield partial
70
 
71
- def user_fn(user_message, history):
72
- # Returns the updated history as a list of dictionaries
73
- return "", history + [{"role": "user", "content": user_message}]
 
 
74
 
75
- def bot_fn(history, system_prompt, max_tokens, temperature, top_p):
76
- user_message = history[-1]["content"]
77
- # Initialize assistant message
78
- history.append({"role": "assistant", "content": ""})
79
-
80
- for response in predict(
81
- user_message,
82
- history[:-1],
83
- system_prompt,
84
- max_tokens,
85
- temperature,
86
- top_p
87
- ):
88
- history[-1]["content"] = response
89
- yield history
90
 
91
- with gr.Blocks(title="LegalBuddy AI Draft Engine") as demo:
92
- gr.Markdown("# ⚖️ LegalBuddy: The Digital Legal Chamber")
93
-
94
- chatbot = gr.Chatbot(height=600)
95
-
96
- msg = gr.Textbox(
97
- placeholder="Type your legal query or draft request..."
98
- )
99
 
100
  with gr.Row():
101
- submit = gr.Button("Send", variant="primary")
102
- clear = gr.Button("Clear")
103
-
104
- with gr.Accordion("Advanced Settings", open=False):
105
- system_prompt = gr.Textbox(
106
- value="You are a professional legal assistant specializing in Indian law and legal document drafting.",
107
- label="System Prompt"
108
- )
109
- max_tokens_slider = gr.Slider(1, 2048, value=1024, label="Max Tokens")
110
- temp_slider = gr.Slider(0.1, 1.0, value=0.1, step=0.1, label="Temperature")
111
- top_p_slider = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="Top-p")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
- submit.click(
114
- user_fn,
115
- [msg, chatbot],
116
- [msg, chatbot],
117
- queue=False
118
  ).then(
119
- bot_fn,
120
- [chatbot, system_prompt, max_tokens_slider, temp_slider, top_p_slider],
121
- chatbot
122
  )
123
-
124
- msg.submit(
125
- user_fn,
126
- [msg, chatbot],
127
- [msg, chatbot],
128
- queue=False
129
  ).then(
130
- bot_fn,
131
- [chatbot, system_prompt, max_tokens_slider, temp_slider, top_p_slider],
132
- chatbot
133
  )
134
-
135
- clear.click(lambda: [], None, chatbot, queue=False)
136
 
137
  if __name__ == "__main__":
138
- demo.queue()
139
- demo.launch()
 
 
 
1
  import gradio as gr
2
+ import os
3
+ from huggingface_hub import InferenceClient
4
+
5
+ # Setup HF Token
6
+ token_path = os.path.expanduser("~/.cache/huggingface/token")
7
+ HF_TOKEN = os.environ.get("HF_TOKEN")
8
+ if not HF_TOKEN and os.path.exists(token_path):
9
+ with open(token_path) as f:
10
+ HF_TOKEN = f.read().strip()
11
+
12
+ # Model Config - Using the STABLE base model for reliable Cloud Inference
13
+ MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
14
+ client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
15
 
16
+ # THE REAL SYSTEM PROMPT
17
+ system_prompt = """You are LegalBuddy, a professional legal document drafting assistant for Indian law.
18
+ Your objective is to help users generate highly accurate, structured legal documents.
19
 
20
+ STRICT INSTRUCTIONS:
21
+ 1. INITIAL LANGUAGE: Always start in English.
22
+ 2. DYNAMIC LANGUAGE: If the user speaks in Hindi/Hinglish, you MUST respond in the same. Otherwise, stick to English.
23
+ 3. INTERVIEW MODE: Ask structured questions ONE AT A TIME to collect missing info (Landlord, Tenant, Rent, etc.).
24
+ 4. DRAFTING: When ready, generate the full professional legal document structure with # Headers and clear clauses.
25
+ """
26
 
27
+ custom_css = """
28
+ body, .gradio-container { font-family: 'Inter', -apple-system, sans-serif !important; background-color: #f8fafc !important; }
29
+ #header { padding: 30px; background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); border-radius: 12px; margin-bottom: 25px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); text-align: center; }
30
+ #header h1 { margin: 0; font-size: 32px; font-weight: 800; color: #ffffff !important; letter-spacing: -0.5px; }
31
+ #header p { margin: 8px 0 0 0; font-size: 16px; color: #cbd5e1 !important; font-weight: 400; }
32
+ .chatbot-container { border-radius: 12px !important; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1) !important; background: white !important; }
33
+ .message-wrap { font-size: 16px !important; line-height: 1.6 !important; }
34
+ """
35
 
36
+ def setup_chat(user_text, history):
37
+ history.append((user_text, ""))
38
+ return gr.update(value="", interactive=False), history, gr.update(visible=False), gr.update(visible=True)
 
 
 
39
 
40
+ def chat_logic(history, temp, top_p_val, max_tokens):
41
  messages = [{"role": "system", "content": system_prompt}]
42
+ for u_msg, a_reply in history[:-1]:
43
+ if u_msg: messages.append({"role": "user", "content": u_msg})
44
+ if a_reply: messages.append({"role": "assistant", "content": a_reply})
45
 
46
+ messages.append({"role": "user", "content": history[-1][0]})
 
 
 
 
 
 
 
 
 
 
47
 
48
+ partial_response = ""
49
+ try:
50
+ response_stream = client.chat_completion(
51
+ messages,
52
+ max_tokens=int(max_tokens),
53
+ stream=True,
54
+ temperature=float(temp),
55
+ top_p=float(top_p_val),
56
+ )
57
+ for chunk in response_stream:
58
+ if chunk.choices and chunk.choices[0].delta.content:
59
+ partial_response += chunk.choices[0].delta.content
60
+ yield partial_response
61
+ except Exception as e:
62
+ yield f"⚠️ Connection Issue: {str(e)}"
 
 
 
 
 
 
 
 
63
 
64
+ def process_interaction(chat_history, temp, top_p_val, max_tokens):
65
+ user_input = chat_history[-1][0]
66
+ for partial_response in chat_logic(chat_history, temp, top_p_val, max_tokens):
67
+ chat_history[-1] = (user_input, partial_response)
68
+ yield chat_history
69
 
70
+ def finalize_chat():
71
+ return gr.update(interactive=True), gr.update(visible=True), gr.update(visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="slate", neutral_hue="slate"), css=custom_css, title="LegalBuddy Pro") as demo:
74
+ with gr.Column(elem_id="header"):
75
+ gr.Markdown("<h1>LegalBuddy Pro</h1>\n<p>Professional Legal Drafting Assistant</p>")
 
 
 
 
 
76
 
77
  with gr.Row():
78
+ with gr.Column(scale=12): # Full Width
79
+ chatbot = gr.Chatbot(
80
+ height=650,
81
+ show_label=False,
82
+ show_copy_button=True,
83
+ bubble_full_width=True,
84
+ avatar_images=(None, "⚖️"),
85
+ elem_classes="chatbot-container"
86
+ )
87
+
88
+ with gr.Row():
89
+ user_msg = gr.Textbox(
90
+ show_label=False,
91
+ placeholder="I need a Rent Agreement for Mumbai...",
92
+ scale=9,
93
+ container=False,
94
+ autofocus=True
95
+ )
96
+ submit_btn = gr.Button("Draft ➤", variant="primary", scale=1)
97
+ stop_btn = gr.Button("Stop 🛑", variant="stop", scale=1, visible=False)
98
+
99
+ with gr.Accordion("Advanced Settings", open=False):
100
+ with gr.Row():
101
+ temp_s = gr.Slider(0.01, 1.0, 0.05, step=0.01, label="Temperature")
102
+ top_p_s = gr.Slider(0.1, 1.0, 0.9, step=0.05, label="Top P")
103
+ max_toks = gr.Slider(500, 4096, 2048, step=100, label="Max Tokens")
104
 
105
+ # Wire up interactions
106
+ submit_event = submit_btn.click(
107
+ fn=setup_chat, inputs=[user_msg, chatbot], outputs=[user_msg, chatbot, submit_btn, stop_btn]
 
 
108
  ).then(
109
+ fn=process_interaction, inputs=[chatbot, temp_s, top_p_s, max_toks], outputs=[chatbot]
110
+ ).then(
111
+ fn=finalize_chat, outputs=[user_msg, submit_btn, stop_btn]
112
  )
113
+
114
+ user_msg.submit(
115
+ fn=setup_chat, inputs=[user_msg, chatbot], outputs=[user_msg, chatbot, submit_btn, stop_btn]
 
 
 
116
  ).then(
117
+ fn=process_interaction, inputs=[chatbot, temp_s, top_p_s, max_toks], outputs=[chatbot]
118
+ ).then(
119
+ fn=finalize_chat, outputs=[user_msg, submit_btn, stop_btn]
120
  )
121
+
122
+ stop_btn.click(fn=None, cancels=[submit_event])
123
 
124
  if __name__ == "__main__":
125
+ print("🚀 Launching LegalBuddy Pro (Full-Screen Chat)...")
126
+ demo.queue().launch(share=True, server_port=7865)