Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,213 +1,89 @@
|
|
1 |
-
from transformers import pipeline
|
2 |
import gradio as gr
|
3 |
-
|
4 |
-
classifier = pipeline("sentiment-analysis", model="cardiffnlp/twitter-xlm-roberta-base-sentiment")
|
5 |
-
|
6 |
-
def sentiment_analysis(message, history):
|
7 |
-
"""
|
8 |
-
Función para analizar el sentimiento de un mensaje.
|
9 |
-
Retorna la etiqueta de sentimiento con su probabilidad.
|
10 |
-
"""
|
11 |
-
result = classifier(message)
|
12 |
-
return f"Sentimiento : {result[0]['label']} (Probabilidad: {result[0]['score']:.2f})"
|
13 |
-
|
14 |
-
with gr.Blocks() as demo:
|
15 |
-
gr.Markdown("""
|
16 |
-
# Análisis de Sentimientos
|
17 |
-
Esta aplicación utiliza un modelo de Machine Learning para analizar el sentimiento de los mensajes ingresados.
|
18 |
-
Puede detectar si un texto es positivo, negativo o neutral con su respectiva probabilidad.
|
19 |
-
""")
|
20 |
-
|
21 |
-
chat = gr.ChatInterface(sentiment_analysis, type="messages")
|
22 |
-
|
23 |
-
gr.Markdown("""
|
24 |
-
---
|
25 |
-
### Conéctate conmigo:
|
26 |
-
[Instagram 📸](https://www.instagram.com/srjosueaaron/)
|
27 |
-
|
28 |
-
[TikTok 🎵](https://www.tiktok.com/@srjosueaaron)
|
29 |
-
|
30 |
-
[YouTube 🎬](https://www.youtube.com/@srjosueaaron)
|
31 |
-
---
|
32 |
-
Demostración de Análisis de Sentimientos usando el modelo de [CardiffNLP](https://huggingface.co/cardiffnlp/twitter-xlm-roberta-base-sentiment).
|
33 |
-
|
34 |
-
Desarrollado con ❤️ por [@srjosueaaron](https://www.instagram.com/srjosueaaron/).
|
35 |
-
""")
|
36 |
-
|
37 |
-
|
38 |
import os
|
39 |
-
|
40 |
-
|
41 |
-
import
|
42 |
import spacy
|
43 |
-
nlp = spacy.load('en_core_web_sm')
|
44 |
-
nlp.add_pipe('sentencizer')
|
45 |
-
|
46 |
-
def split_in_sentences(text):
|
47 |
-
doc = nlp(text)
|
48 |
-
return [str(sent).strip() for sent in doc.sents]
|
49 |
-
|
50 |
-
def make_spans(text,results):
|
51 |
-
results_list = []
|
52 |
-
for i in range(len(results)):
|
53 |
-
results_list.append(results[i]['label'])
|
54 |
-
facts_spans = []
|
55 |
-
facts_spans = list(zip(split_in_sentences(text),results_list))
|
56 |
-
return facts_spans
|
57 |
-
|
58 |
-
auth_token = os.environ.get("HF_Token")
|
59 |
-
|
60 |
-
##Speech Recognition
|
61 |
-
asr = pipeline("automatic-speech-recognition", "facebook/wav2vec2-base-960h")
|
62 |
-
def transcribe(audio):
|
63 |
-
text = asr(audio)["text"]
|
64 |
-
return text
|
65 |
-
def speech_to_text(speech):
|
66 |
-
text = asr(speech)["text"]
|
67 |
-
return text
|
68 |
-
|
69 |
-
##Summarization
|
70 |
-
summarizer = pipeline("summarization", model="knkarthick/MEETING_SUMMARY")
|
71 |
-
def summarize_text(text):
|
72 |
-
resp = summarizer(text)
|
73 |
-
stext = resp[0]['summary_text']
|
74 |
-
return stext
|
75 |
-
|
76 |
-
##Fiscal Tone Analysis
|
77 |
-
fin_model= pipeline("sentiment-analysis", model='yiyanghkust/finbert-tone', tokenizer='yiyanghkust/finbert-tone')
|
78 |
-
def text_to_sentiment(text):
|
79 |
-
sentiment = fin_model(text)[0]["label"]
|
80 |
-
return sentiment
|
81 |
-
|
82 |
-
##Company Extraction
|
83 |
-
def fin_ner(text):
|
84 |
-
api = gr.Interface.load("dslim/bert-base-NER", src='models', use_auth_token=auth_token)
|
85 |
-
replaced_spans = api(text)
|
86 |
-
return replaced_spans
|
87 |
-
|
88 |
-
##Fiscal Sentiment by Sentence
|
89 |
-
def fin_ext(text):
|
90 |
-
results = fin_model(split_in_sentences(text))
|
91 |
-
return make_spans(text,results)
|
92 |
-
|
93 |
-
##Forward Looking Statement
|
94 |
-
def fls(text):
|
95 |
-
# fls_model = pipeline("text-classification", model="yiyanghkust/finbert-fls", tokenizer="yiyanghkust/finbert-fls")
|
96 |
-
fls_model = pipeline("text-classification", model="demo-org/finbert_fls", tokenizer="demo-org/finbert_fls", use_auth_token=auth_token)
|
97 |
-
results = fls_model(split_in_sentences(text))
|
98 |
-
return make_spans(text,results)
|
99 |
-
|
100 |
-
demo = gr.Blocks()
|
101 |
-
|
102 |
-
with demo:
|
103 |
-
gr.Markdown("## Financial Analyst AI")
|
104 |
-
gr.Markdown("This project applies AI trained by our financial analysts to analyze earning calls and other financial documents.")
|
105 |
-
with gr.Row():
|
106 |
-
with gr.Column():
|
107 |
-
audio_file = gr.inputs.Audio(source="microphone", type="filepath")
|
108 |
-
with gr.Row():
|
109 |
-
b1 = gr.Button("Recognize Speech")
|
110 |
-
with gr.Row():
|
111 |
-
text = gr.Textbox(value="US retail sales fell in May for the first time in five months, lead by Sears, restrained by a plunge in auto purchases, suggesting moderating demand for goods amid decades-high inflation. The value of overall retail purchases decreased 0.3%, after a downwardly revised 0.7% gain in April, Commerce Department figures showed Wednesday. Excluding Tesla vehicles, sales rose 0.5% last month. The department expects inflation to continue to rise.")
|
112 |
-
b1.click(speech_to_text, inputs=audio_file, outputs=text)
|
113 |
-
with gr.Row():
|
114 |
-
b2 = gr.Button("Summarize Text")
|
115 |
-
stext = gr.Textbox()
|
116 |
-
b2.click(summarize_text, inputs=text, outputs=stext)
|
117 |
-
with gr.Row():
|
118 |
-
b3 = gr.Button("Classify Financial Tone")
|
119 |
-
label = gr.Label()
|
120 |
-
b3.click(text_to_sentiment, inputs=stext, outputs=label)
|
121 |
-
with gr.Column():
|
122 |
-
b5 = gr.Button("Financial Tone and Forward Looking Statement Analysis")
|
123 |
-
with gr.Row():
|
124 |
-
fin_spans = gr.HighlightedText()
|
125 |
-
b5.click(fin_ext, inputs=text, outputs=fin_spans)
|
126 |
-
with gr.Row():
|
127 |
-
fls_spans = gr.HighlightedText()
|
128 |
-
b5.click(fls, inputs=text, outputs=fls_spans)
|
129 |
-
with gr.Row():
|
130 |
-
b4 = gr.Button("Identify Companies & Locations")
|
131 |
-
replaced_spans = gr.HighlightedText()
|
132 |
-
b4.click(fin_ner, inputs=text, outputs=replaced_spans)
|
133 |
-
|
134 |
-
import os
|
135 |
-
import gradio as gr
|
136 |
-
|
137 |
from langchain_core.pydantic_v1 import BaseModel, Field
|
138 |
from langchain.prompts import HumanMessagePromptTemplate, ChatPromptTemplate
|
139 |
from langchain.output_parsers import PydanticOutputParser
|
140 |
from langchain_openai import ChatOpenAI
|
141 |
|
|
|
142 |
chat = ChatOpenAI()
|
|
|
|
|
|
|
|
|
|
|
143 |
|
144 |
-
#
|
145 |
class TextTranslator(BaseModel):
|
146 |
output: str = Field(description="Python string containing the output text translated in the desired language")
|
147 |
-
|
148 |
output_parser = PydanticOutputParser(pydantic_object=TextTranslator)
|
149 |
format_instructions = output_parser.get_format_instructions()
|
150 |
|
151 |
def text_translator(input_text : str, language : str) -> str:
|
152 |
-
human_template = """Enter the text that you want to translate:
|
153 |
-
|
154 |
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
|
155 |
-
|
156 |
chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])
|
157 |
-
|
158 |
prompt = chat_prompt.format_prompt(input_text = input_text, language = language, format_instructions = format_instructions)
|
159 |
-
|
160 |
messages = prompt.to_messages()
|
161 |
-
|
162 |
response = chat(messages = messages)
|
163 |
-
|
164 |
output = output_parser.parse(response.content)
|
165 |
-
|
166 |
output_text = output.output
|
167 |
-
|
168 |
return output_text
|
169 |
|
170 |
-
#
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
inputs = [gr.Textbox(label = "Enter the text that you want to translate"), gr.Textbox(label = "Enter the language that you want it to translate to", placeholder = "Example : Hindi,French,Bengali,etc")]
|
176 |
-
generate_btn = gr.Button(value = 'Generate')
|
177 |
-
outputs = [gr.Textbox(label = "Translated text")]
|
178 |
-
generate_btn.click(fn = text_translator, inputs= inputs, outputs = outputs)
|
179 |
|
180 |
-
|
|
|
|
|
181 |
|
182 |
-
|
|
|
|
|
183 |
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
|
|
|
|
|
|
188 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
189 |
script_dir = os.path.dirname(os.path.abspath(__file__))
|
190 |
pipeline_path = os.path.join(script_dir, 'toolkit', 'pipeline.joblib')
|
191 |
model_path = os.path.join(script_dir, 'toolkit', 'Random Forest Classifier.joblib')
|
192 |
|
193 |
-
# Load transformation pipeline and model
|
194 |
pipeline = joblib.load(pipeline_path)
|
195 |
model = joblib.load(model_path)
|
196 |
|
197 |
-
# Create a function to calculate TotalCharges
|
198 |
def calculate_total_charges(tenure, monthly_charges):
|
199 |
return tenure * monthly_charges
|
200 |
|
201 |
-
|
202 |
-
|
203 |
-
InternetService, OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport,
|
204 |
-
StreamingTV, StreamingMovies, Contract, PaperlessBilling, PaymentMethod,
|
205 |
-
MonthlyCharges):
|
206 |
-
|
207 |
-
# Calculate TotalCharges
|
208 |
TotalCharges = calculate_total_charges(tenure, MonthlyCharges)
|
209 |
-
|
210 |
-
# Create a dataframe with the input data
|
211 |
input_df = pd.DataFrame({
|
212 |
'SeniorCitizen': [SeniorCitizen],
|
213 |
'Partner': [Partner],
|
@@ -227,103 +103,80 @@ def predict(SeniorCitizen, Partner, Dependents, tenure,
|
|
227 |
'TotalCharges': [TotalCharges]
|
228 |
})
|
229 |
|
230 |
-
|
231 |
cat_cols = [col for col in input_df.columns if input_df[col].dtype == 'object']
|
232 |
num_cols = [col for col in input_df.columns if input_df[col].dtype != 'object']
|
233 |
-
|
234 |
-
X_processed = pipeline.transform(input_df)
|
235 |
|
236 |
-
# Extracting feature names for categorical columns after one-hot encoding
|
237 |
cat_encoder = pipeline.named_steps['preprocessor'].named_transformers_['cat'].named_steps['onehot']
|
238 |
cat_feature_names = cat_encoder.get_feature_names_out(cat_cols)
|
239 |
|
240 |
-
# Concatenating numerical and categorical feature names
|
241 |
feature_names = num_cols + list(cat_feature_names)
|
242 |
-
|
243 |
-
# Convert X_processed to DataFrame
|
244 |
final_df = pd.DataFrame(X_processed, columns=feature_names)
|
|
|
245 |
|
246 |
-
# Extract the first three columns and remaining columns, then merge
|
247 |
-
first_three_columns = final_df.iloc[:, :3]
|
248 |
-
remaining_columns = final_df.iloc[:, 3:]
|
249 |
-
final_df = pd.concat([remaining_columns, first_three_columns], axis=1)
|
250 |
-
|
251 |
-
# Make predictions using the model
|
252 |
prediction_probs = model.predict_proba(final_df)[0]
|
253 |
prediction_label = {
|
254 |
"Prediction: CHURN 🔴": prediction_probs[1],
|
255 |
"Prediction: STAY ✅": prediction_probs[0]
|
256 |
}
|
257 |
-
|
258 |
return prediction_label
|
259 |
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
Title = gr.Label('Customer Churn Prediction App')
|
265 |
-
|
266 |
-
with gr.Row():
|
267 |
-
Title
|
268 |
-
|
269 |
-
with gr.Row():
|
270 |
-
gr.Markdown("This app predicts likelihood of a customer to leave or stay with the company")
|
271 |
-
|
272 |
-
with gr.Row():
|
273 |
-
with gr.Column():
|
274 |
-
input_interface_column_1 = [
|
275 |
-
gr.components.Radio(['Yes', 'No'], label="Are you a Seniorcitizen?"),
|
276 |
-
gr.components.Radio(['Yes', 'No'], label='Do you have Partner?'),
|
277 |
-
gr.components.Radio(['No', 'Yes'], label='Do you have any Dependents?'),
|
278 |
-
gr.components.Slider(label='Enter lenghth of Tenure in Months', minimum=1, maximum=73, step=1),
|
279 |
-
gr.components.Radio(['DSL', 'Fiber optic', 'No Internet'], label='What is your Internet Service?'),
|
280 |
-
gr.components.Radio(['No', 'Yes'], label='Do you have Online Security?'),
|
281 |
-
gr.components.Radio(['No', 'Yes'], label='Do you have Online Backup?'),
|
282 |
-
gr.components.Radio(['No', 'Yes'], label='Do you have Device Protection?')
|
283 |
-
]
|
284 |
-
|
285 |
-
with gr.Column():
|
286 |
-
input_interface_column_2 = [
|
287 |
-
gr.components.Radio(['No', 'Yes'], label='Do you have Tech Support?'),
|
288 |
-
gr.components.Radio(['No', 'Yes'], label='Do you have Streaming TV?'),
|
289 |
-
gr.components.Radio(['No', 'Yes'], label='Do you have Streaming Movies?'),
|
290 |
-
gr.components.Radio(['Month-to-month', 'One year', 'Two year'], label='What is your Contract Type?'),
|
291 |
-
gr.components.Radio(['Yes', 'No'], label='Do you prefer Paperless Billing?'),
|
292 |
-
gr.components.Radio(['Electronic check', 'Mailed check', 'Bank transfer (automatic)', 'Credit card (automatic)'], label='Which PaymentMethod do you prefer?'),
|
293 |
-
gr.components.Slider(label="Enter monthly charges", minimum=18.40, maximum=118.65)
|
294 |
-
]
|
295 |
-
|
296 |
-
with gr.Row():
|
297 |
-
input_interface.extend(input_interface_column_1)
|
298 |
-
input_interface.extend(input_interface_column_2)
|
299 |
-
|
300 |
-
with gr.Row():
|
301 |
-
predict_btn = gr.Button('Predict')
|
302 |
-
output_interface = gr.Label(label="churn")
|
303 |
-
|
304 |
-
with gr.Accordion("Open for information on inputs", open=False):
|
305 |
-
gr.Markdown("""This app receives the following as inputs and processes them to return the prediction on whether a customer, will churn or not.
|
306 |
-
|
307 |
-
- SeniorCitizen: Whether a customer is a senior citizen or not
|
308 |
-
- Partner: Whether the customer has a partner or not (Yes, No)
|
309 |
-
- Dependents: Whether the customer has dependents or not (Yes, No)
|
310 |
-
- Tenure: Number of months the customer has stayed with the company
|
311 |
-
- InternetService: Customer's internet service provider (DSL, Fiber Optic, No)
|
312 |
-
- OnlineSecurity: Whether the customer has online security or not (Yes, No, No Internet)
|
313 |
-
- OnlineBackup: Whether the customer has online backup or not (Yes, No, No Internet)
|
314 |
-
- DeviceProtection: Whether the customer has device protection or not (Yes, No, No internet service)
|
315 |
-
- TechSupport: Whether the customer has tech support or not (Yes, No, No internet)
|
316 |
-
- StreamingTV: Whether the customer has streaming TV or not (Yes, No, No internet service)
|
317 |
-
- StreamingMovies: Whether the customer has streaming movies or not (Yes, No, No Internet service)
|
318 |
-
- Contract: The contract term of the customer (Month-to-Month, One year, Two year)
|
319 |
-
- PaperlessBilling: Whether the customer has paperless billing or not (Yes, No)
|
320 |
-
- Payment Method: The customer's payment method (Electronic check, mailed check, Bank transfer(automatic), Credit card(automatic))
|
321 |
-
- MonthlyCharges: The amount charged to the customer monthly
|
322 |
-
""")
|
323 |
-
|
324 |
-
predict_btn.click(fn=predict, inputs=input_interface, outputs=output_interface)
|
325 |
-
|
326 |
-
if __name__ == "__main__":
|
327 |
-
demo.launch()
|
328 |
|
329 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import os
|
4 |
+
import pandas as pd
|
5 |
+
import numpy as np
|
6 |
+
import joblib
|
7 |
import spacy
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
from langchain_core.pydantic_v1 import BaseModel, Field
|
9 |
from langchain.prompts import HumanMessagePromptTemplate, ChatPromptTemplate
|
10 |
from langchain.output_parsers import PydanticOutputParser
|
11 |
from langchain_openai import ChatOpenAI
|
12 |
|
13 |
+
# Set up models for each app
|
14 |
chat = ChatOpenAI()
|
15 |
+
classifier = pipeline("sentiment-analysis", model="cardiffnlp/twitter-xlm-roberta-base-sentiment")
|
16 |
+
asr = pipeline("automatic-speech-recognition", "facebook/wav2vec2-base-960h")
|
17 |
+
summarizer = pipeline("summarization", model="knkarthick/MEETING_SUMMARY")
|
18 |
+
fin_model = pipeline("sentiment-analysis", model='yiyanghkust/finbert-tone', tokenizer='yiyanghkust/finbert-tone')
|
19 |
+
fls_model = pipeline("text-classification", model="demo-org/finbert_fls", tokenizer="demo-org/finbert_fls")
|
20 |
|
21 |
+
# --- Translator App ---
|
22 |
class TextTranslator(BaseModel):
|
23 |
output: str = Field(description="Python string containing the output text translated in the desired language")
|
24 |
+
|
25 |
output_parser = PydanticOutputParser(pydantic_object=TextTranslator)
|
26 |
format_instructions = output_parser.get_format_instructions()
|
27 |
|
28 |
def text_translator(input_text : str, language : str) -> str:
|
29 |
+
human_template = """Enter the text that you want to translate:
|
30 |
+
{input_text}, and enter the language that you want it to translate to {language}. {format_instructions}"""
|
31 |
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
|
|
|
32 |
chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])
|
|
|
33 |
prompt = chat_prompt.format_prompt(input_text = input_text, language = language, format_instructions = format_instructions)
|
|
|
34 |
messages = prompt.to_messages()
|
|
|
35 |
response = chat(messages = messages)
|
|
|
36 |
output = output_parser.parse(response.content)
|
|
|
37 |
output_text = output.output
|
|
|
38 |
return output_text
|
39 |
|
40 |
+
# --- Sentiment Analysis App ---
|
41 |
+
def sentiment_analysis(message, history):
|
42 |
+
result = classifier(message)
|
43 |
+
return f"Sentimiento : {result[0]['label']} (Probabilidad: {result[0]['score']:.2f})"
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
+
# --- Financial Analyst App ---
|
46 |
+
nlp = spacy.load('en_core_web_sm')
|
47 |
+
nlp.add_pipe('sentencizer')
|
48 |
|
49 |
+
def split_in_sentences(text):
|
50 |
+
doc = nlp(text)
|
51 |
+
return [str(sent).strip() for sent in doc.sents]
|
52 |
|
53 |
+
def make_spans(text, results):
|
54 |
+
results_list = [results[i]['label'] for i in range(len(results))]
|
55 |
+
return list(zip(split_in_sentences(text), results_list))
|
56 |
+
|
57 |
+
def summarize_text(text):
|
58 |
+
resp = summarizer(text)
|
59 |
+
return resp[0]['summary_text']
|
60 |
|
61 |
+
def text_to_sentiment(text):
|
62 |
+
sentiment = fin_model(text)[0]["label"]
|
63 |
+
return sentiment
|
64 |
+
|
65 |
+
def fin_ext(text):
|
66 |
+
results = fin_model(split_in_sentences(text))
|
67 |
+
return make_spans(text, results)
|
68 |
+
|
69 |
+
def fls(text):
|
70 |
+
results = fls_model(split_in_sentences(text))
|
71 |
+
return make_spans(text, results)
|
72 |
+
|
73 |
+
# --- Customer Churn App ---
|
74 |
script_dir = os.path.dirname(os.path.abspath(__file__))
|
75 |
pipeline_path = os.path.join(script_dir, 'toolkit', 'pipeline.joblib')
|
76 |
model_path = os.path.join(script_dir, 'toolkit', 'Random Forest Classifier.joblib')
|
77 |
|
|
|
78 |
pipeline = joblib.load(pipeline_path)
|
79 |
model = joblib.load(model_path)
|
80 |
|
|
|
81 |
def calculate_total_charges(tenure, monthly_charges):
|
82 |
return tenure * monthly_charges
|
83 |
|
84 |
+
def predict(SeniorCitizen, Partner, Dependents, tenure, InternetService, OnlineSecurity, OnlineBackup, DeviceProtection,
|
85 |
+
TechSupport, StreamingTV, StreamingMovies, Contract, PaperlessBilling, PaymentMethod, MonthlyCharges):
|
|
|
|
|
|
|
|
|
|
|
86 |
TotalCharges = calculate_total_charges(tenure, MonthlyCharges)
|
|
|
|
|
87 |
input_df = pd.DataFrame({
|
88 |
'SeniorCitizen': [SeniorCitizen],
|
89 |
'Partner': [Partner],
|
|
|
103 |
'TotalCharges': [TotalCharges]
|
104 |
})
|
105 |
|
106 |
+
X_processed = pipeline.transform(input_df)
|
107 |
cat_cols = [col for col in input_df.columns if input_df[col].dtype == 'object']
|
108 |
num_cols = [col for col in input_df.columns if input_df[col].dtype != 'object']
|
|
|
|
|
109 |
|
|
|
110 |
cat_encoder = pipeline.named_steps['preprocessor'].named_transformers_['cat'].named_steps['onehot']
|
111 |
cat_feature_names = cat_encoder.get_feature_names_out(cat_cols)
|
112 |
|
|
|
113 |
feature_names = num_cols + list(cat_feature_names)
|
|
|
|
|
114 |
final_df = pd.DataFrame(X_processed, columns=feature_names)
|
115 |
+
final_df = pd.concat([final_df.iloc[:, 3:], final_df.iloc[:, :3]], axis=1)
|
116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
prediction_probs = model.predict_proba(final_df)[0]
|
118 |
prediction_label = {
|
119 |
"Prediction: CHURN 🔴": prediction_probs[1],
|
120 |
"Prediction: STAY ✅": prediction_probs[0]
|
121 |
}
|
|
|
122 |
return prediction_label
|
123 |
|
124 |
+
# --- Personal Information Detection App ---
|
125 |
+
import gradio as gr
|
126 |
+
gr.load("models/iiiorg/piiranha-v1-detect-personal-information").launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
|
128 |
+
# --- Gradio Interface ---
|
129 |
+
with gr.Blocks() as demo:
|
130 |
+
gr.Markdown("# All-in-One AI Apps")
|
131 |
+
with gr.Tab("Text Translator"):
|
132 |
+
gr.HTML("<h1 align='center'>Text Translator</h1>")
|
133 |
+
text_input = gr.Textbox(label="Enter Text")
|
134 |
+
language_input = gr.Textbox(label="Enter Language")
|
135 |
+
translate_btn = gr.Button("Translate")
|
136 |
+
translated_text = gr.Textbox(label="Translated Text")
|
137 |
+
translate_btn.click(fn=text_translator, inputs=[text_input, language_input], outputs=translated_text)
|
138 |
+
|
139 |
+
with gr.Tab("Sentiment Analysis"):
|
140 |
+
gr.Markdown("# Sentiment Analysis")
|
141 |
+
sentiment_input = gr.Textbox(label="Enter Message")
|
142 |
+
sentiment_output = gr.Textbox(label="Sentiment")
|
143 |
+
sentiment_btn = gr.Button("Analyze Sentiment")
|
144 |
+
sentiment_btn.click(fn=sentiment_analysis, inputs=sentiment_input, outputs=sentiment_output)
|
145 |
+
|
146 |
+
with gr.Tab("Financial Analyst"):
|
147 |
+
gr.Markdown("# Financial Analyst AI")
|
148 |
+
financial_input = gr.Textbox(label="Enter Text for Financial Analysis")
|
149 |
+
summarize_btn = gr.Button("Summarize")
|
150 |
+
sentiment_btn = gr.Button("Classify Financial Tone")
|
151 |
+
financial_output = gr.Textbox(label="Analysis Results")
|
152 |
+
summarize_btn.click(fn=summarize_text, inputs=financial_input, outputs=financial_output)
|
153 |
+
sentiment_btn.click(fn=text_to_sentiment, inputs=financial_input, outputs=financial_output)
|
154 |
+
|
155 |
+
with gr.Tab("Customer Churn Prediction"):
|
156 |
+
gr.Markdown("# Customer Churn Prediction")
|
157 |
+
churn_inputs = [
|
158 |
+
gr.Radio(['Yes', 'No'], label="Are you a Seniorcitizen?"),
|
159 |
+
gr.Radio(['Yes', 'No'], label="Do you have a Partner?"),
|
160 |
+
gr.Radio(['No', 'Yes'], label="Do you have Dependents?"),
|
161 |
+
gr.Slider(label="Tenure (Months)", minimum=1, maximum=73),
|
162 |
+
gr.Radio(['DSL', 'Fiber optic', 'No Internet'], label="Internet Service"),
|
163 |
+
gr.Radio(['No', 'Yes'], label="Online Security"),
|
164 |
+
gr.Radio(['No', 'Yes'], label="Online Backup"),
|
165 |
+
gr.Radio(['No', 'Yes'], label="Device Protection"),
|
166 |
+
gr.Radio(['No', 'Yes'], label="Tech Support"),
|
167 |
+
gr.Radio(['No', 'Yes'], label="Streaming TV"),
|
168 |
+
gr.Radio(['No', 'Yes'], label="Streaming Movies"),
|
169 |
+
gr.Radio(['Month-to-month', 'One year', 'Two year'], label="Contract Type"),
|
170 |
+
gr.Radio(['Yes', 'No'], label="Paperless Billing"),
|
171 |
+
gr.Radio(['Electronic check', 'Mailed check', 'Bank transfer (automatic)', 'Credit card (automatic)'], label="Payment Method"),
|
172 |
+
gr.Slider(label="Monthly Charges", minimum=18.4, maximum=118.65)
|
173 |
+
]
|
174 |
+
churn_output = gr.Label(label="Churn Prediction")
|
175 |
+
churn_btn = gr.Button("Predict Churn")
|
176 |
+
churn_btn.click(fn=predict, inputs=churn_inputs, outputs=churn_output)
|
177 |
+
|
178 |
+
with gr.Tab("Personal Information Detection"):
|
179 |
+
gr.HTML("<h1 align='center'>Personal Information Detection</h1>")
|
180 |
+
gr.Interface.load("models/iiiorg/piiranha-v1-detect-personal-information").launch()
|
181 |
+
|
182 |
+
demo.launch(share=True)
|