Facececersek commited on
Commit
e12d891
·
verified ·
1 Parent(s): 4335114

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +100 -72
app.py CHANGED
@@ -1,88 +1,116 @@
1
  import gradio as gr
2
- from transformers import pipeline
 
3
 
4
- # Initialize the sentiment analysis pipeline
5
- sentiment_pipeline = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
 
 
6
 
7
  # Initialize text generation pipeline
8
- generator = pipeline("text-generation", model="distilgpt2", max_length=100)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def analyze_sentiment(text):
11
- """Analyze the sentiment of the input text."""
12
- if not text.strip():
13
- return "Please enter some text to analyze."
14
 
15
- result = sentiment_pipeline(text)[0]
16
- label = result['label']
17
- score = result['score']
 
 
18
 
19
- return f"Sentiment: {label}\nConfidence: {score:.2%}"
20
-
21
- def generate_text(prompt):
22
- """Generate text based on the input prompt."""
23
- if not prompt.strip():
24
- return "Please enter a prompt to generate text."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- result = generator(prompt, max_length=100, num_return_sequences=1)
27
- return result[0]['generated_text']
28
 
29
- def chatbot(message, history):
30
- """Simple chatbot function."""
31
- if not message.strip():
32
- return "Please say something!"
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- # Simple response logic
35
- message_lower = message.lower()
 
 
 
 
 
36
 
37
- if "hello" in message_lower or "hi" in message_lower:
38
- return "Hello! How can I help you today?"
39
- elif "how are you" in message_lower:
40
- return "I'm doing great, thanks for asking! I'm an AI assistant ready to help."
41
- elif "bye" in message_lower:
42
- return "Goodbye! Have a great day!"
43
- elif "sentiment" in message_lower:
44
- return "I can analyze sentiment! Go to the Sentiment Analysis tab and enter some text."
45
- else:
46
- # Use the generator for other inputs
47
- response = generator(message, max_length=50, num_return_sequences=1)
48
- return response[0]['generated_text']
49
-
50
- # Create the Gradio interface with tabs
51
- with gr.Blocks(title="Basic AI Assistant") as demo:
52
- gr.Markdown("# 🤖 Basic AI Assistant")
53
- gr.Markdown("A simple AI-powered assistant with multiple capabilities!")
54
 
55
- with gr.Tabs():
56
- with gr.TabItem("💬 Chat"):
57
- gr.Markdown("Chat with the AI assistant!")
58
- chat_interface = gr.ChatInterface(chatbot, type="messages")
59
-
60
- with gr.TabItem("😊 Sentiment Analysis"):
61
- gr.Markdown("Analyze the sentiment of your text (positive or negative).")
62
- with gr.Row():
63
- sentiment_input = gr.Textbox(
64
- label="Enter text to analyze",
65
- placeholder="Type something like 'I love this product!'",
66
- lines=3
67
- )
68
- sentiment_output = gr.Textbox(label="Result", lines=2)
69
- sentiment_btn = gr.Button("Analyze Sentiment", variant="primary")
70
- sentiment_btn.click(analyze_sentiment, inputs=sentiment_input, outputs=sentiment_output)
71
-
72
- with gr.TabItem("✍️ Text Generation"):
73
- gr.Markdown("Generate text based on a prompt!")
74
- with gr.Row():
75
- gen_input = gr.Textbox(
76
- label="Enter your prompt",
77
- placeholder="Once upon a time...",
78
- lines=3
79
- )
80
- gen_output = gr.Textbox(label="Generated Text", lines=5)
81
- gen_btn = gr.Button("Generate Text", variant="primary")
82
- gen_btn.click(generate_text, inputs=gen_input, outputs=gen_output)
83
 
84
- gr.Markdown("---")
85
- gr.Markdown("Made with ❤️ using Gradio and Hugging Face Transformers")
 
 
 
 
 
 
86
 
87
  if __name__ == "__main__":
88
  demo.launch()
 
1
  import gradio as gr
2
+ from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
3
+ import torch
4
 
5
+ # Model: Mistral 7B Instruct - powerful open model
6
+ MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.2"
7
+
8
+ print(f"Loading model: {MODEL_NAME}...")
9
 
10
  # Initialize text generation pipeline
11
+ try:
12
+ generator = pipeline(
13
+ "text-generation",
14
+ model=MODEL_NAME,
15
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
16
+ device_map="auto" if torch.cuda.is_available() else None,
17
+ trust_remote_code=True
18
+ )
19
+ print("Model loaded successfully!")
20
+ except Exception as e:
21
+ print(f"Error loading model: {e}")
22
+ # Fallback to a smaller model
23
+ MODEL_NAME = "microsoft/DialoGPT-medium"
24
+ generator = pipeline("text-generation", model=MODEL_NAME)
25
+ print(f"Loaded fallback model: {MODEL_NAME}")
26
 
27
+ def chat_with_ai(message, history):
28
+ """Chat with the AI model."""
29
+ if not message.strip():
30
+ return history
31
 
32
+ # Build conversation prompt
33
+ conversation = ""
34
+ for user_msg, assistant_msg in history:
35
+ conversation += f"<|user|>\n{user_msg}</s>\n<|assistant|\n{assistant_msg}</s>\n"
36
+ conversation += f"<|user|>\n{message}</s>\n<|assistant|"
37
 
38
+ try:
39
+ # Generate response
40
+ response = generator(
41
+ conversation,
42
+ max_new_tokens=512,
43
+ temperature=0.7,
44
+ top_p=0.9,
45
+ do_sample=True,
46
+ pad_token_id=generator.tokenizer.eos_token_id
47
+ )
48
+
49
+ # Extract only the new response
50
+ full_text = response[0]['generated_text']
51
+ # Get the part after the last assistant tag
52
+ if "<|assistant| " in full_text:
53
+ assistant_response = full_text.split("<|assistant|")[-1].strip()
54
+ else:
55
+ assistant_response = full_text[len(conversation):].strip()
56
+
57
+ # Clean up any remaining tags
58
+ assistant_response = assistant_response.replace("</s>", "").strip()
59
+
60
+ if not assistant_response:
61
+ assistant_response = "I'm thinking... could you ask that again?"
62
+
63
+ except Exception as e:
64
+ assistant_response = f"Sorry, I encountered an error: {str(e)}"
65
 
66
+ history.append((message, assistant_response))
67
+ return history
68
 
69
+ # Create the Gradio interface
70
+ with gr.Blocks(
71
+ title="AI Chat",
72
+ theme=gr.themes.Soft(
73
+ primary_hue="purple",
74
+ secondary_hue="blue",
75
+ ),
76
+ css="""
77
+ .gradio-container {
78
+ max-width: 800px !important;
79
+ margin: auto !important;
80
+ }
81
+ """
82
+ ) as demo:
83
+ gr.Markdown("# 🤖 AI Chat Assistant")
84
+ gr.Markdown(f"Powered by **{MODEL_NAME}**")
85
 
86
+ chatbot = gr.Chatbot(
87
+ label="Chat",
88
+ height=500,
89
+ show_copy_button=True,
90
+ bubble_full_width=False,
91
+ avatar_images=(None, "🤖")
92
+ )
93
 
94
+ with gr.Row():
95
+ msg = gr.Textbox(
96
+ label="Message",
97
+ placeholder="Type your message here...",
98
+ scale=9,
99
+ container=False
100
+ )
101
+ submit_btn = gr.Button("Send", scale=1, variant="primary")
 
 
 
 
 
 
 
 
 
102
 
103
+ with gr.Row():
104
+ clear_btn = gr.Button("Clear Chat", variant="secondary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
+ # Event handlers
107
+ msg.submit(chat_with_ai, [msg, chatbot], [chatbot]).then(
108
+ lambda: "", None, [msg]
109
+ )
110
+ submit_btn.click(chat_with_ai, [msg, chatbot], [chatbot]).then(
111
+ lambda: "", None, [msg]
112
+ )
113
+ clear_btn.click(lambda: [], None, [chatbot])
114
 
115
  if __name__ == "__main__":
116
  demo.launch()