Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import pandas as pd | |
| import openai | |
| import os | |
| import io | |
| import time | |
| # Language dictionary for translations | |
| LANGUAGES = { | |
| "English": { | |
| "title": "π Sentiment Analysis of Comments", | |
| "upload_prompt": "Upload an Excel (.xlsx), CSV (.csv), or text (.txt) file with comments and get sentiment analysis!", | |
| "upload_button": "Upload a file", | |
| "error_column": "The file must contain text in the first column", | |
| "results": "### Analysis Results:", | |
| "download": "π₯ Download Report Excel", | |
| "unsupported_format": "Unsupported format. Please upload a .xlsx, .csv, or .txt file." | |
| } | |
| } | |
| # Function to get API Key securely | |
| def get_openai_api_key(): | |
| return os.getenv("OPENAI_API_KEY") | |
| # OpenAI API Key setup | |
| openai.api_key = os.environ.get("OPENAI_API_KEY", None) | |
| # Cost tracking variables | |
| MAX_DAILY_COST = 1.0 # Maximum daily cost in USD | |
| TOKEN_COST = 0.002 / 1000 # Approximate cost per input token (GPT-3.5-turbo) | |
| TOKEN_LIMIT = int(MAX_DAILY_COST / TOKEN_COST) # Max tokens per day | |
| daily_token_usage = 0 # Track daily token usage | |
| last_reset_time = time.time() | |
| def analyze_sentiment(text): | |
| global daily_token_usage, last_reset_time | |
| # Reset usage if a new day starts | |
| if time.time() - last_reset_time > 86400: | |
| daily_token_usage = 0 | |
| last_reset_time = time.time() | |
| if daily_token_usage >= TOKEN_LIMIT: | |
| return "Daily limit reached" | |
| if not openai.api_key: | |
| return "API Key Missing" | |
| prompt = f"Classifica il sentiment del seguente commento come 'Positive', 'Negative' o 'Neutral': \"{text}\"" | |
| try: | |
| response = openai.ChatCompletion.create( | |
| model="gpt-4", | |
| messages=[{"role": "system", "content": "Sei un assistente che esegue sentiment analysis."}, | |
| {"role": "user", "content": prompt}], | |
| temperature=0.0 | |
| ) | |
| sentiment = response["choices"][0]["message"]["content"].strip() | |
| token_used = response["usage"]["total_tokens"] | |
| daily_token_usage += token_used | |
| return sentiment if sentiment in ["Positive", "Negative", "Neutral"] else "Neutral" | |
| except Exception as e: | |
| return f"Error: {str(e)}" | |
| def analyze_file(uploaded_file): | |
| try: | |
| # Load the file depending on the format | |
| if uploaded_file.name.endswith(".xlsx"): | |
| df = pd.read_excel(uploaded_file, engine='openpyxl') | |
| elif uploaded_file.name.endswith(".csv"): | |
| df = pd.read_csv(uploaded_file) | |
| else: | |
| return "Unsupported file format. Please upload a .xlsx or .csv file.", None | |
| # Check if the first column contains text | |
| if df.shape[1] == 0: | |
| return "Error: No valid columns found in the file.", None | |
| df = df.rename(columns={df.columns[0]: "Comment"}) | |
| df["Sentiment"] = df["Comment"].astype(str).apply(analyze_sentiment) | |
| excel_output = io.BytesIO() | |
| with pd.ExcelWriter(excel_output, engine='openpyxl') as writer: | |
| df.to_excel(writer, index=False) | |
| excel_output.seek(0) | |
| return df, excel_output.getvalue() | |
| except Exception as e: | |
| return f"Error processing file: {str(e)}", None | |
| def sentiment_analysis_interface(): | |
| language = gr.Radio(["English"], label="π Select Language", value="English") | |
| file_input = gr.File(label="π₯ Upload a file (CSV, XLSX)") | |
| results_output = gr.Dataframe() | |
| download_button = gr.File(label="π₯ Download Excel") | |
| def process_file(language, uploaded_file): | |
| df, excel_data = analyze_file(uploaded_file) | |
| if isinstance(df, str): | |
| return df, None | |
| with open("sentiment_analysis.xlsx", "wb") as f: | |
| f.write(excel_data) | |
| return df, "sentiment_analysis.xlsx" | |
| return gr.Interface( | |
| fn=process_file, | |
| inputs=[language, file_input], | |
| outputs=[results_output, download_button], | |
| title="π Sentiment Analysis", | |
| description="Upload a file with comments and get sentiment analysis using GPT-3.5-turbo!" | |
| ) | |
| iface = sentiment_analysis_interface() | |
| if __name__ == "__main__": | |
| iface.launch() | |