Nithish3115 commited on
Commit
0d297db
·
verified ·
1 Parent(s): 90b105b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -57
app.py CHANGED
@@ -1,64 +1,92 @@
 
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 os
2
  import gradio as gr
3
+ from transformers import pipeline
4
 
5
+ # Initialize the pipeline with settings that work well on Hugging Face
6
+ def initialize_model():
7
+ # HF-specific configuration for memory efficiency
8
+ pipe = pipeline(
9
+ "text-generation",
10
+ model="abhinand/tamil-llama-7b-instruct-v0.2",
11
+ device_map="auto",
12
+ torch_dtype="auto",
13
+ model_kwargs={"load_in_8bit": True} # 8-bit quantization for HF Spaces
14
+ )
15
+ return pipe
16
 
17
+ # Generate response
18
+ def generate_response(pipe, user_input, chat_history):
19
+ # Format messages for the model
20
+ messages = []
21
+ for human, bot in chat_history:
22
+ messages.append({"role": "user", "content": human})
23
+ messages.append({"role": "assistant", "content": bot})
24
+
25
+ # Add the current message
26
+ messages.append({"role": "user", "content": user_input})
27
+
28
+ try:
29
+ # Generate response with settings suitable for Spaces
30
+ response = pipe(
31
+ messages,
32
+ max_length=256, # Shorter responses to save compute
33
+ do_sample=True,
34
+ temperature=0.7,
35
+ top_p=0.9,
36
+ num_return_sequences=1
37
+ )
38
+
39
+ # Extract the generated text
40
+ generated_text = response[0]['generated_text']
41
+
42
+ # Extract only the assistant's response
43
+ for msg in generated_text:
44
+ if isinstance(msg, dict) and msg.get("role") == "assistant":
45
+ return msg.get("content", "")
46
+
47
+ # Fallback if no assistant response is found
48
+ if isinstance(generated_text, str):
49
+ return generated_text
50
+ return "சரியான பதிலைக் கண்டுபிடிக்க முடியவில்லை." # Could not find proper response
51
+
52
+ except Exception as e:
53
+ print(f"Error generating response: {e}")
54
+ return f"பிழை ஏற்பட்டது. மீண்டும் முயற்சிக்கவும்." # Error occurred, please try again
55
 
56
+ # Create the Gradio interface
57
+ def create_chatbot_interface():
58
+ with gr.Blocks() as demo:
59
+ gr.Markdown("# தமிழ் உரையாடல் பொத்தான் (Tamil Chatbot)")
60
+
61
+ chatbot = gr.Chatbot(label="உரையாடல் (Conversation)")
62
+ msg = gr.Textbox(label="உங்கள் செய்தி (Your Message)", placeholder="இங்கே தட்டச்சு செய்யவும்...")
63
+ clear = gr.Button("அழி (Clear)")
64
+
65
+ # Initialize model only once when first needed
66
+ model = gr.State(None)
67
+
68
+ def load_model_if_needed(model_state):
69
+ if model_state is None:
70
+ return initialize_model()
71
+ return model_state
72
+
73
+ def respond(message, chat_history, model_state):
74
+ # Load model if not already loaded
75
+ if model_state is None:
76
+ model_state = initialize_model()
77
+
78
+ bot_message = generate_response(model_state, message, chat_history)
79
+ chat_history.append((message, bot_message))
80
+ return "", chat_history, model_state
81
+
82
+ msg.submit(respond, [msg, chatbot, model], [msg, chatbot, model])
83
+ clear.click(lambda: None, None, chatbot, queue=False)
84
+
85
+ return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
+ # Create and launch the demo
88
+ demo = create_chatbot_interface()
89
 
90
+ # This is the key part for Hugging Face Spaces
91
  if __name__ == "__main__":
92
+ demo.launch()