safiaa02 commited on
Commit
0dca069
·
verified ·
1 Parent(s): 90e9a8b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -41
app.py CHANGED
@@ -2,11 +2,12 @@ import os
2
  import gradio as gr
3
  import requests
4
 
5
- # Use Mistral via Hugging Face Inference API (requires token)
6
- API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.1"
7
- headers = {"Authorization": f"Bearer {os.getenv('HUGGINGFACE_TOKEN')}"}
 
8
 
9
- # Example prompts
10
  preset_prompts = [
11
  "I finally got the promotion, but I feel guilty because my best friend got laid off.",
12
  "Moving to a new city is exciting, but leaving my family breaks my heart.",
@@ -15,62 +16,51 @@ preset_prompts = [
15
  "I’m happy for her, but I wish I had that too.",
16
  ]
17
 
18
- # Call Mistral Inference API with error handling
19
- def call_model(prompt):
20
- payload = {"inputs": prompt}
21
- try:
22
- response = requests.post(API_URL, headers=headers, json=payload, timeout=45)
23
-
24
- print("Status:", response.status_code)
25
- print("Raw:", response.text)
26
-
27
- if response.status_code != 200:
28
- return f"⚠️ Error: API returned {response.status_code} - model may be loading or access may be restricted."
29
 
 
 
 
30
  data = response.json()
31
- if isinstance(data, list) and "generated_text" in data[0]:
32
- return data[0]["generated_text"]
33
- elif isinstance(data, dict) and "error" in data:
34
- return f"⚠️ API Error: {data['error']}"
35
- else:
36
- return "⚠️ Unexpected response format from model."
37
 
 
38
  except Exception as e:
39
- return f"⚠️ Request failed: {str(e)}"
40
 
41
- # Emotion analysis logic
42
- def emotion_annotator(text):
43
- prompt1 = f"""You are an expert in human emotions. Based on the sentence below, list all possible emotions the person might be feeling.
 
 
 
44
 
45
- Sentence: "{text}"
46
- Emotions:"""
47
- candidates = call_model(prompt1)
 
48
 
49
- prompt2 = f"""Given the sentence "{text}" and the following candidate emotions: {candidates}, pick the most likely emotion and explain why.
50
-
51
- Format:
52
- Most likely emotion: <emotion>
53
- Reason: <why>"""
54
- final = call_model(prompt2)
55
-
56
- return candidates.strip(), final.strip()
57
 
58
  # Gradio UI
59
  with gr.Blocks() as demo:
60
- gr.Markdown("## 🧠 Emotion Annotator AI (Mistral 7B via Hugging Face API)")
61
- gr.Markdown("Disambiguates mixed emotions using `mistralai/Mistral-7B-Instruct-v0.1`. Token required.")
62
 
63
  with gr.Row():
64
- text_input = gr.Textbox(label="Enter your sentence", placeholder="e.g., I’m proud but I feel like I let them down.", lines=2)
65
  dropdown = gr.Dropdown(preset_prompts, label="💬 Choose an example")
66
-
67
  run_button = gr.Button("Submit")
68
 
69
  with gr.Row():
70
  candidate_output = gr.Textbox(label="🧠 Candidate Emotions")
71
  final_output = gr.Textbox(label="🎯 Most Likely Emotion + Explanation")
72
 
73
- # Auto-fill from dropdown
74
  dropdown.change(fn=lambda x: x, inputs=dropdown, outputs=text_input)
75
  run_button.click(fn=emotion_annotator, inputs=text_input, outputs=[candidate_output, final_output])
76
 
 
2
  import gradio as gr
3
  import requests
4
 
5
+ # Hugging Face Chat Completion Endpoint
6
+ API_URL = "https://router.huggingface.co/novita/v3/openai/chat/completions"
7
+ HEADERS = {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"}
8
+ MODEL = "mistralai/Mistral-7B-Instruct-v0.1"
9
 
10
+ # Suggested test prompts
11
  preset_prompts = [
12
  "I finally got the promotion, but I feel guilty because my best friend got laid off.",
13
  "Moving to a new city is exciting, but leaving my family breaks my heart.",
 
16
  "I’m happy for her, but I wish I had that too.",
17
  ]
18
 
19
+ # Call the Hugging Face router endpoint with Mistral
20
+ def call_mistral_chat(messages):
21
+ payload = {
22
+ "model": MODEL,
23
+ "messages": messages
24
+ }
 
 
 
 
 
25
 
26
+ try:
27
+ response = requests.post(API_URL, headers=HEADERS, json=payload, timeout=45)
28
+ response.raise_for_status()
29
  data = response.json()
 
 
 
 
 
 
30
 
31
+ return data["choices"][0]["message"]["content"]
32
  except Exception as e:
33
+ return f"⚠️ Error: {str(e)}"
34
 
35
+ # Emotion annotation logic
36
+ def emotion_annotator(user_text):
37
+ # Step 1: Generate candidate emotions
38
+ prompt1 = f"You are an emotion analysis expert. List all possible emotions the person might be feeling in this sentence:\n\n\"{user_text}\"\n\nAnswer with just the emotion names."
39
+ messages1 = [{"role": "user", "content": prompt1}]
40
+ candidate_emotions = call_mistral_chat(messages1)
41
 
42
+ # Step 2: Disambiguate to most likely emotion
43
+ prompt2 = f"""Now from this list of emotions: {candidate_emotions}, pick the most likely one the person is feeling and explain why. Sentence: "{user_text}"\n\nFormat:\nMost likely emotion: <emotion>\nReason: <why>"""
44
+ messages2 = [{"role": "user", "content": prompt2}]
45
+ final_emotion = call_mistral_chat(messages2)
46
 
47
+ return candidate_emotions.strip(), final_emotion.strip()
 
 
 
 
 
 
 
48
 
49
  # Gradio UI
50
  with gr.Blocks() as demo:
51
+ gr.Markdown("## 🧠 Emotion Annotator AI (Powered by Mistral 7B via HF Chat API)")
52
+ gr.Markdown("Disambiguates complex emotions using `mistralai/Mistral-7B-Instruct-v0.1` through Hugging Face's Chat Completion endpoint.")
53
 
54
  with gr.Row():
55
+ text_input = gr.Textbox(label="📝 Input Sentence", placeholder="e.g., I’m proud but I feel like I let them down.", lines=2)
56
  dropdown = gr.Dropdown(preset_prompts, label="💬 Choose an example")
 
57
  run_button = gr.Button("Submit")
58
 
59
  with gr.Row():
60
  candidate_output = gr.Textbox(label="🧠 Candidate Emotions")
61
  final_output = gr.Textbox(label="🎯 Most Likely Emotion + Explanation")
62
 
63
+ # Auto-fill textbox from dropdown
64
  dropdown.change(fn=lambda x: x, inputs=dropdown, outputs=text_input)
65
  run_button.click(fn=emotion_annotator, inputs=text_input, outputs=[candidate_output, final_output])
66