badr-mardi commited on
Commit
cdb997d
·
verified ·
1 Parent(s): db612bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -99
app.py CHANGED
@@ -1,104 +1,62 @@
1
 
 
2
  import streamlit as st
3
- import numpy as np
4
- import pandas as pd
5
- import matplotlib.pyplot as plt
6
- from sklearn.model_selection import train_test_split
7
- from sklearn.linear_model import LinearRegression
8
- from sklearn.metrics import mean_squared_error, r2_score
9
- from sklearn import datasets
10
- import io
11
-
12
- def main():
13
- st.title("California Housing Analysis")
14
-
15
- # Load the California housing dataset
16
- california = datasets.fetch_california_housing()
17
- df = pd.DataFrame(california.data, columns=california.feature_names)
18
- df['MedHouseVal'] = california.target
19
-
20
- # Displaying initial data information
21
- st.write("## Data Sample")
22
- st.write(df.head())
23
-
24
- st.write("## Data Statistics")
25
- st.write(df.describe())
26
-
27
- st.write("## Data Info")
28
- buffer = io.StringIO()
29
- df.info(buf=buffer)
30
- s = buffer.getvalue()
31
- st.text(s)
32
-
33
- st.write("## Missing Values")
34
- st.write(df.isnull().sum())
35
-
36
- # Fixed target variable
37
- target = 'MedHouseVal'
38
- st.write(f"## Target Variable: {target}")
39
-
40
- # Drop the target from the predictors list
41
- predictor_options = df.columns.drop(target).tolist()
42
-
43
- # Multiselect widget to select predictor variables for regression
44
- predictors = st.multiselect(
45
- 'Select predictor variables for regression:',
46
- options=predictor_options,
47
- default=predictor_options # default to all predictors for MLR
48
- )
49
-
50
- # Splitting data for regression
51
- X = df[predictors]
52
- y = df[target]
53
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
54
-
55
- # Perform multilinear regression
56
- mlr_model = LinearRegression()
57
- mlr_model.fit(X_train, y_train)
58
- mlr_y_pred = mlr_model.predict(X_test)
59
- mlr_rmse = np.sqrt(mean_squared_error(y_test, mlr_y_pred))
60
- mlr_r2 = r2_score(y_test, mlr_y_pred)
61
-
62
- # Perform simple linear regression using only one predictor if possible
63
- if 'AveRooms' in predictors:
64
- slr_model = LinearRegression()
65
- slr_X_train = X_train[['AveRooms']]
66
- slr_X_test = X_test[['AveRooms']]
67
- slr_model.fit(slr_X_train, y_train)
68
- slr_y_pred = slr_model.predict(slr_X_test)
69
- slr_rmse = np.sqrt(mean_squared_error(y_test, slr_y_pred))
70
- slr_r2 = r2_score(y_test, slr_y_pred)
71
-
72
- # Display RMSE and R-squared comparisons
73
- st.write("## Regression Performance Comparison")
74
- st.write(f"### Multilinear Regression (using all selected predictors)")
75
- st.write(f'RMSE: {mlr_rmse}')
76
- st.write(f'R-squared: {mlr_r2}')
77
-
78
- st.write(f"### Simple Linear Regression (using 'AveRooms')")
79
- st.write(f'RMSE: {slr_rmse}')
80
- st.write(f'R-squared: {slr_r2}')
81
-
82
- # Plotting both regressions
83
- fig, ax = plt.subplots(1, 2, figsize=(15, 6))
84
-
85
- ax[0].scatter(y_test, mlr_y_pred, color='blue')
86
- ax[0].plot(y_test, y_test, color='red')
87
- ax[0].set_title('Multilinear Regression: Actual vs Predicted')
88
- ax[0].set_xlabel('Actual Values')
89
- ax[0].set_ylabel('Predicted Values')
90
-
91
- ax[1].scatter(y_test, slr_y_pred, color='green')
92
- ax[1].plot(y_test, y_test, color='red')
93
- ax[1].set_title("Simple Linear Regression ('AveRooms'): Actual vs Predicted")
94
- ax[1].set_xlabel('Actual Values')
95
- ax[1].set_ylabel('Predicted Values')
96
-
97
- st.pyplot(fig)
98
-
99
- if __name__ == "__main__":
100
- main()
101
-
102
 
103
 
104
 
 
1
 
2
+ pip install streamlit transformers huggingface_hub
3
  import streamlit as st
4
+ from huggingface_hub import InferenceApi, AsyncInferenceApi, InferenceTimeoutError, ModelStatus
5
+ import asyncio
6
+
7
+ # Initialize the Inference API
8
+ model_id = "gpt2" # Replace with your desired model
9
+ api_token = "YOUR_HUGGING_FACE_TOKEN" # Replace with your Hugging Face API token
10
+
11
+ api = InferenceApi(repo_id=model_id, token=api_token)
12
+
13
+ # Function to get response synchronously
14
+ def get_response_sync(prompt):
15
+ try:
16
+ response = api(inputs=prompt)
17
+ return response[0]['generated_text']
18
+ except InferenceTimeoutError as e:
19
+ return f"Request timed out: {e}"
20
+
21
+ # Function to get response asynchronously
22
+ async def get_response_async(prompt):
23
+ async with AsyncInferenceApi(repo_id=model_id, token=api_token) as async_api:
24
+ try:
25
+ response = await async_api(inputs=prompt)
26
+ return response[0]['generated_text']
27
+ except InferenceTimeoutError as e:
28
+ return f"Request timed out: {e}"
29
+
30
+ # Function to check model status
31
+ def check_model_status():
32
+ status = api.status()
33
+ return status
34
+
35
+ # Streamlit App
36
+ st.title("Hugging Face Chatbot with Streamlit")
37
+ st.write("This is a chatbot powered by Hugging Face's Inference API.")
38
+
39
+ # Model status
40
+ status = check_model_status()
41
+ st.write(f"Model Status: {status}")
42
+
43
+ # Input and button
44
+ user_input = st.text_input("You: ", "")
45
+ if st.button("Send"):
46
+ if user_input:
47
+ # Synchronous response
48
+ response = get_response_sync(user_input)
49
+ st.write(f"Bot: {response}")
50
+
51
+ # Asynchronous interaction using asyncio
52
+ async def async_interaction():
53
+ if user_input:
54
+ response = await get_response_async(user_input)
55
+ st.write(f"Bot: {response}")
56
+
57
+ if st.button("Send (Async)"):
58
+ if user_input:
59
+ asyncio.run(async_interaction())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
 
62