omar721 commited on
Commit
09aeaac
Β·
verified Β·
1 Parent(s): 431b26d

update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -48
app.py CHANGED
@@ -3,38 +3,61 @@ import requests
3
  import os
4
  import time
5
 
6
- # Configuration
7
  API_TOKEN = os.environ.get("HF_TOKEN", "")
8
  MODEL_NAME = "deepseek-ai/Janus-Pro-7B"
9
  API_URL = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"
10
- headers = {"Authorization": f"Bearer {API_TOKEN}"}
 
 
 
 
 
 
 
 
 
11
 
12
  def query_janus_model(payload):
13
  """Send request to Hugging Face Inference API"""
 
 
 
14
  try:
15
- response = requests.post(API_URL, headers=headers, json=payload, timeout=30)
16
 
17
  if response.status_code == 503:
18
- return {"error": "Model is loading, please try again in 30-60 seconds..."}
 
 
 
 
19
  elif response.status_code != 200:
20
- return {"error": f"API Error: {response.status_code} - {response.text}"}
21
 
22
  return response.json()
23
  except requests.exceptions.Timeout:
24
- return {"error": "Request timeout - model might be loading"}
25
  except Exception as e:
26
- return {"error": f"Connection error: {str(e)}"}
27
 
28
  def chat_with_janus(message, history):
29
  """Chat function for Janus-Pro model"""
30
- if not API_TOKEN:
31
- return "⚠️ Please add your Hugging Face token in Space Settings β†’ Repository secrets β†’ HF_TOKEN"
 
 
 
 
 
 
 
32
 
33
  # Prepare the payload
34
  payload = {
35
  "inputs": message,
36
  "parameters": {
37
- "max_new_tokens": 300,
38
  "temperature": 0.7,
39
  "top_p": 0.9,
40
  "do_sample": True,
@@ -46,19 +69,23 @@ def chat_with_janus(message, history):
46
  }
47
 
48
  # Show loading message
49
- yield "πŸ”„ Processing your request... (Model might take 30-60 seconds to load)"
50
 
51
  # Query the model
52
  result = query_janus_model(payload)
53
 
54
  # Process the response
55
  if "error" in result:
56
- yield f"❌ {result['error']}"
57
  elif isinstance(result, list) and len(result) > 0:
58
  if 'generated_text' in result[0]:
59
- yield result[0]['generated_text']
 
 
 
 
60
  else:
61
- yield str(result[0])
62
  elif isinstance(result, dict) and 'generated_text' in result:
63
  yield result['generated_text']
64
  else:
@@ -68,69 +95,75 @@ def clear_chat():
68
  """Clear chat history"""
69
  return [], []
70
 
71
- # Custom CSS for better appearance
72
- css = """
73
- .gradio-container {
74
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
75
- }
76
- .chatbot {
77
- background: white;
78
- border-radius: 10px;
79
- }
80
- """
81
-
82
  # Create the chat interface
83
- with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
84
  gr.Markdown(
85
  """
86
  # πŸš€ Janus-Pro-7B Chat API
87
- **Multimodal AI Model** - Understanding & Generation Capabilities
88
 
89
- *Note: First request may take 30-60 seconds while the model loads*
90
  """
91
  )
92
 
 
 
 
93
  with gr.Row():
94
  with gr.Column(scale=1):
95
- gr.Markdown("### ℹ️ About Janus-Pro")
96
  gr.Markdown("""
97
- - **Model**: Janus-Pro-7B by DeepSeek
98
- - **Capabilities**: Text understanding & generation
 
 
 
 
 
 
 
 
 
99
  - **License**: MIT
100
- - **Framework**: Unified multimodal transformer
101
  """)
102
 
103
  with gr.Column(scale=2):
104
  chatbot = gr.Chatbot(
105
- label="Chat with Janus-Pro",
106
  height=400,
107
- show_copy_button=True
 
108
  )
109
 
110
  with gr.Row():
111
  msg = gr.Textbox(
112
- label="Your message",
113
- placeholder="Type your message here... (Press Enter to send)",
114
  scale=4,
115
- container=False
 
116
  )
117
- clear_btn = gr.Button("πŸ—‘οΈ Clear", scale=1)
118
 
119
  with gr.Row():
120
  gr.Examples(
121
  examples=[
122
- "Explain quantum computing in simple terms",
123
- "Write a short poem about artificial intelligence",
124
- "What are the benefits of renewable energy?",
125
- "How does machine learning work?"
126
  ],
127
  inputs=msg,
128
- label="Try these examples:"
129
  )
130
 
131
  # Event handlers
 
 
 
 
132
  msg.submit(
133
- fn=chat_with_janus,
134
  inputs=[msg, chatbot],
135
  outputs=chatbot
136
  ).then(
@@ -146,10 +179,12 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
146
  gr.Markdown(
147
  """
148
  ---
149
- **Tips**:
150
- - Be specific in your questions for better responses
151
- - The model excels at technical explanations and creative writing
152
- - First message may be slow as the model loads
 
 
153
  """
154
  )
155
 
 
3
  import os
4
  import time
5
 
6
+ # Get the token from environment variables
7
  API_TOKEN = os.environ.get("HF_TOKEN", "")
8
  MODEL_NAME = "deepseek-ai/Janus-Pro-7B"
9
  API_URL = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"
10
+ headers = {"Authorization": f"Bearer {API_TOKEN}"} if API_TOKEN else {}
11
+
12
+ def check_token_setup():
13
+ """Check if token is properly set up"""
14
+ if not API_TOKEN:
15
+ return "❌ HF_TOKEN not found. Please add your Hugging Face token in Space Settings β†’ Secrets β†’ HF_TOKEN"
16
+ elif not API_TOKEN.startswith("hf_"):
17
+ return "❌ Invalid token format. Token should start with 'hf_'"
18
+ else:
19
+ return "βœ… Token is properly configured!"
20
 
21
  def query_janus_model(payload):
22
  """Send request to Hugging Face Inference API"""
23
+ if not API_TOKEN:
24
+ return {"error": "No API token configured"}
25
+
26
  try:
27
+ response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
28
 
29
  if response.status_code == 503:
30
+ return {"error": "πŸ”„ Model is loading, please try again in 30-60 seconds..."}
31
+ elif response.status_code == 401:
32
+ return {"error": "πŸ” Invalid API token. Please check your HF_TOKEN secret."}
33
+ elif response.status_code == 404:
34
+ return {"error": "❌ Model not found. The model might be temporarily unavailable."}
35
  elif response.status_code != 200:
36
+ return {"error": f"API Error {response.status_code}: {response.text}"}
37
 
38
  return response.json()
39
  except requests.exceptions.Timeout:
40
+ return {"error": "⏰ Request timeout - model might be loading"}
41
  except Exception as e:
42
+ return {"error": f"πŸ”Œ Connection error: {str(e)}"}
43
 
44
  def chat_with_janus(message, history):
45
  """Chat function for Janus-Pro model"""
46
+ # First check token setup
47
+ token_status = check_token_setup()
48
+ if "❌" in token_status:
49
+ yield token_status
50
+ return
51
+
52
+ # Show token status
53
+ yield "βœ… Token configured! Processing your request..."
54
+ time.sleep(1)
55
 
56
  # Prepare the payload
57
  payload = {
58
  "inputs": message,
59
  "parameters": {
60
+ "max_new_tokens": 350,
61
  "temperature": 0.7,
62
  "top_p": 0.9,
63
  "do_sample": True,
 
69
  }
70
 
71
  # Show loading message
72
+ yield "πŸ”„ Sending request to Janus-Pro-7B... (First time may take 30-60 seconds)"
73
 
74
  # Query the model
75
  result = query_janus_model(payload)
76
 
77
  # Process the response
78
  if "error" in result:
79
+ yield f"{result['error']}"
80
  elif isinstance(result, list) and len(result) > 0:
81
  if 'generated_text' in result[0]:
82
+ generated_text = result[0]['generated_text']
83
+ # Clean up the response
84
+ if generated_text.startswith(message):
85
+ generated_text = generated_text[len(message):].strip()
86
+ yield generated_text
87
  else:
88
+ yield f"πŸ“„ Response: {str(result[0])}"
89
  elif isinstance(result, dict) and 'generated_text' in result:
90
  yield result['generated_text']
91
  else:
 
95
  """Clear chat history"""
96
  return [], []
97
 
 
 
 
 
 
 
 
 
 
 
 
98
  # Create the chat interface
99
+ with gr.Blocks(theme=gr.themes.Soft(), title="Janus-Pro-7B API") as demo:
100
  gr.Markdown(
101
  """
102
  # πŸš€ Janus-Pro-7B Chat API
103
+ **Free API for DeepSeek's Multimodal AI Model**
104
 
105
+ *Understanding & Generation Capabilities*
106
  """
107
  )
108
 
109
+ # Token status display
110
+ token_status = gr.Markdown(check_token_setup())
111
+
112
  with gr.Row():
113
  with gr.Column(scale=1):
114
+ gr.Markdown("### πŸ“‹ Instructions")
115
  gr.Markdown("""
116
+ 1. **First message may take 30-60 seconds** (model loading)
117
+ 2. **Subsequent messages are faster**
118
+ 3. **Be specific** for better responses
119
+ 4. Model supports **technical explanations** and **creative writing**
120
+ """)
121
+
122
+ gr.Markdown("### ℹ️ Model Info")
123
+ gr.Markdown("""
124
+ - **Name**: Janus-Pro-7B
125
+ - **Developer**: DeepSeek AI
126
+ - **Type**: Multimodal (Text + Image)
127
  - **License**: MIT
 
128
  """)
129
 
130
  with gr.Column(scale=2):
131
  chatbot = gr.Chatbot(
132
+ label="πŸ’¬ Chat with Janus-Pro",
133
  height=400,
134
+ show_copy_button=True,
135
+ placeholder="Your conversation will appear here..."
136
  )
137
 
138
  with gr.Row():
139
  msg = gr.Textbox(
140
+ label="Type your message",
141
+ placeholder="Ask me anything... (Press Enter to send)",
142
  scale=4,
143
+ container=False,
144
+ autofocus=True
145
  )
146
+ clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", scale=1)
147
 
148
  with gr.Row():
149
  gr.Examples(
150
  examples=[
151
+ "Explain quantum computing like I'm 10 years old",
152
+ "Write a short story about a robot learning to paint",
153
+ "What are the main differences between AI and human intelligence?",
154
+ "How do transformers work in machine learning?"
155
  ],
156
  inputs=msg,
157
+ label="πŸ’‘ Try these examples:"
158
  )
159
 
160
  # Event handlers
161
+ def respond_and_clear(message, history):
162
+ for response in chat_with_janus(message, history):
163
+ yield response
164
+
165
  msg.submit(
166
+ fn=respond_and_clear,
167
  inputs=[msg, chatbot],
168
  outputs=chatbot
169
  ).then(
 
179
  gr.Markdown(
180
  """
181
  ---
182
+ **Note**: This is a free API using Hugging Face's Inference API. There might be rate limits for high usage.
183
+
184
+ **Troubleshooting**:
185
+ - If you get token errors, check your HF_TOKEN secret in Space Settings
186
+ - If model is loading, wait 30-60 seconds and try again
187
+ - For persistent issues, check the Space logs
188
  """
189
  )
190