Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import os | |
| from dotenv import load_dotenv | |
| from azure.ai.textanalytics import TextAnalyticsClient | |
| from azure.core.credentials import AzureKeyCredential | |
| # Load .env file | |
| load_dotenv() | |
| # this is the end point for the Azure service I created | |
| azure_endpoint = os.getenv("AZURE_API_ENDPOINT") | |
| # this is the KEY for the Azure API Service I created. | |
| azure_api_key = os.getenv("AZURE_API_KEY") | |
| print(f"Azure API token: {azure_api_key}") | |
| # call to the Azure TextAnalyticsClient API | |
| text_analytics_client = TextAnalyticsClient(endpoint=azure_endpoint, credential=AzureKeyCredential(azure_api_key)) | |
| # function which take sthe inut text from the user , then make a call to Azure text analytics service and returns the output in json format with key putput parameter | |
| def classify_text_azure(text): | |
| try: | |
| # Ensure input is in the correct format (list of strings) | |
| documents = [text] | |
| result = text_analytics_client.analyze_sentiment(documents=documents) | |
| # Format the response | |
| return [ | |
| { | |
| "id": i, | |
| "sentiment": doc.sentiment, | |
| "confidence_scores": doc.confidence_scores | |
| } for i, doc in enumerate(result) | |
| ] | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def main(): | |
| """ | |
| Launch the Gradio interface for sentiment analysis. | |
| """ | |
| # Define the Gradio interface | |
| interface = gr.Interface( | |
| fn=classify_text_azure, | |
| inputs=gr.Textbox(lines=2, placeholder="Enter Text Here..."), | |
| outputs="json", | |
| title="Text Classification with Azure Text Analytics", | |
| description="This interface uses Azure Text Analytics to classify text sentiments. Enter a sentence to see its classification." | |
| ) | |
| # Launch the Gradio app | |
| interface.launch() | |
| if __name__ == "__main__": | |
| main() | |