Spaces:
Running
Running
from flask import Flask, request, jsonify | |
import streamlit as st | |
from transformers import pipeline | |
import os | |
from ldclient import LDClient, Config, Context | |
app = Flask(__name__) | |
# Retrieve the LaunchDarkly SDK key from environment variables | |
ld_sdk_key = os.getenv("LAUNCHDARKLY_SDK_KEY") | |
# Initialize LaunchDarkly client with the correct configuration | |
ld_client = LDClient(Config(ld_sdk_key)) | |
# Function to get the AI model configuration from LaunchDarkly | |
def get_model_config(user_name): | |
flag_key = "model-swap" # Replace with your flag key | |
# Create a context using Context Builder—it can be anything, but for this use case, I’m just defaulting to myself. | |
context = Context.builder( | |
f"context-key-{user_name}").name(user_name).build() | |
flag_variation = ld_client.variation(flag_key, context, default={}) | |
model_id = flag_variation.get("modelID", "distilbert-base-uncased") | |
return model_id | |
# Function to translate sentiment labels to user-friendly terms | |
def translate_label(label): | |
label_mapping = { | |
"LABEL_0": "🤬 Negative", | |
"LABEL_1": "😶 Neutral", | |
"LABEL_2": "😃 Positive", | |
"1 star": "🤬 Negative", | |
"2 stars": "🤬 Negative", | |
"3 stars": "😶 Neutral", | |
"4 stars": "😃 Positive", | |
"5 stars": "😃 Positive" | |
} | |
return label_mapping.get(label, "Unknown") | |
def analyze_sentiment(): | |
data = request.json | |
name = data.get('name', 'Anonymous') | |
user_input = data.get('text', '') | |
if not user_input: | |
return jsonify({"error": "No text provided for analysis"}), 400 | |
model_id = get_model_config(name) | |
model = pipeline("sentiment-analysis", model=model_id) | |
results = model(user_input) | |
translated_results = [{"Sentiment": translate_label( | |
result['label']), "Confidence": result['score'], "User_input": user_input} for result in results] | |
return jsonify({"name": name, "results": translated_results}) | |
if __name__ == '__main__': | |
app.run(debug=True) | |