diff --git a/README.md b/README.md index b9eb6f50a41aa6219c6009043b4bfd6cc12cd0be..49721940597f5bda8d64ac42f87c3b9cfbc5b2d3 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,33 @@ # Module 2 +## Кейс РѕС‚ Glowbyte: +Кейс заключается РІ том, что РјС‹ создадим Web сервис, который запрашивает файл СЃ данными Рё после вычислений РјС‹ сравниванем предугаданные данные СЃ реальными -## Getting started +## Состав команды: +- Халимов Рсмоилджон Рбрагимджонович - __Тимлид__ +- Цыбулько Даниил Викторович – __ML-инженер__ +- Рбрагимов Далгат Магомедалиевич – __Fullstack разработчик__ +- Соловьёва Мария - __Дизайнер, Front-end__ +- Зайцев Рван Денисов – __Back-end, ML разработчик__ -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +--- -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +## Обсуждение СЃ экспертами -## Add your files +РќРµ думать Рѕ том как изменить показатели печи для концентрации -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +РњС‹ как лаборатория - нам дают данные РјС‹ РіРѕРІРѕСЂРёРј концентрацию -``` -cd existing_repo -git remote add origin https://gitlab.mai.ru/serviece/module-2.git -git branch -M main -git push -uf origin main -``` +Далее РјС‹ получаем реальные данные Рё сравниваем РёС… СЃ тем, что вычислили -## Integrate with your tools +## Рабочие пространства -- [ ] [Set up project integrations](https://gitlab.mai.ru/serviece/module-2/-/settings/integrations) +Отслеживание прогресса разработки: +https://trello.com/b/Ezp8cVZ3/модуль-2 -## Collaborate with your team +Концепция Рё архитектура: +https://miro.com/app/board/uXjVKJSOnIs=/?share_link_id=233803184182 -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +Canva: +https://www.canva.com/design/DAGFJ-IB2I4/Fz1ViN4W-Q6FItqwHfBC_w/edit?utm_content=DAGFJ-IB2I4&utm_campaign=designshare&utm_medium=link2&utm_source=sharebutton diff --git a/backend/.gitkeep b/backend/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/__pycache__/database.cpython-310.pyc b/backend/__pycache__/database.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8352bbad59cb35b016a5e918cab1ec8ac551f4f Binary files /dev/null and b/backend/__pycache__/database.cpython-310.pyc differ diff --git a/backend/__pycache__/server.cpython-310.pyc b/backend/__pycache__/server.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a85b262ddd8c290a7ac543dba98cfb8c5039cd50 Binary files /dev/null and b/backend/__pycache__/server.cpython-310.pyc differ diff --git a/backend/database.py b/backend/database.py new file mode 100644 index 0000000000000000000000000000000000000000..3d3e8e74eebf807c124b221a62c80f701a31a036 --- /dev/null +++ b/backend/database.py @@ -0,0 +1,18 @@ +# database.py +from sqlalchemy import create_engine, Column, Integer, String +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +DATABASE_URL = "sqlite:///./test.db" + +engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) +Base = declarative_base() + +class FileContent(Base): + __tablename__ = "files" + id = Column(Integer, primary_key=True, index=True) + filename = Column(String, index=True) + content = Column(String) + +Base.metadata.create_all(bind=engine) diff --git a/backend/mashinka__2_.py b/backend/mashinka__2_.py new file mode 100644 index 0000000000000000000000000000000000000000..24b504cf2f4c367902d7612a94c4c7c6068d099a --- /dev/null +++ b/backend/mashinka__2_.py @@ -0,0 +1,107 @@ +''' +1)predict +''' +import pandas as pd +import pandas as pd +from sklearn.metrics import mean_squared_error +import numpy as np +import matplotlib.pyplot as plt +from sklearn.preprocessing import MinMaxScaler +from tensorflow.keras.models import load_model +import keras +import numpy as np +import matplotlib.pyplot as plt +import seaborn as sns +import time +from datetime import datetime +from sklearn.model_selection import train_test_split +from sklearn.linear_model import LinearRegression +from sklearn.metrics import mean_squared_error +from sklearn.preprocessing import MinMaxScaler +from sklearn.model_selection import train_test_split +from sklearn.metrics import mean_absolute_error +from tensorflow.keras.models import Sequential +from tensorflow.keras.layers import LSTM, Dense +import matplotlib.pyplot as plt +import joblib +import keras +import pickle + + +def smart_reader(data): + normal_column_names = telemetry_dict = { + 'telemetry_0': 'temp4', #Температура (датчик 4) + 'telemetry_1': 'consumption', #Питание (загрузка печи) + 'telemetry_2': 'temp1', #Температура (датчик 1) + 'telemetry_3': 'ampere_add', #Сила тока + 'telemetry_4': 'press_add', #Давление (датчик 3) + 'telemetry_5': 'temp3', #Температура (датчик 3) + 'telemetry_6': 'speed', #Скорость + 'telemetry_7': 'press1', #Давление (датчик 1) + 'telemetry_8': 'press2', #Давление (датчик 2) + 'telemetry_9': 'temp2', #Температура (датчик 2) + 'telemetry_10': 'temp5', #Температура (датчик 5) + 'telemetry_11': 'temp6', #Температура (датчик 6) + 'telemetry_12': 'item1', #Концентрация газа 1 + 'telemetry_13': 'item2', #Концентрация газа 2 + 'telemetry_14': 'item3', #Концентрация газа 3 + 'telemetry_15': 'item4', + 'Дата':'datetime'#Концентрация газа 4 + } +#переписать метрику РІ соответсвии СЃ прекрасным потрясающим просто волшебным сообщением РёР· тележки + data.rename(columns=normal_column_names, inplace=True) + data['datetime'] = pd.to_datetime(data['datetime']) + return data + + +def LSTM_feature_engineering(data): + data.drop(columns=['item1', 'item2', 'item3', 'item4'], inplace=True) + return data + + +def prediction_LSTM(data): + lstm_model = load_model('lstm_model.h5') # Загрузка модели LSTM + data['datetime'] = pd.to_datetime(data['datetime']) + hoho = pd.DataFrame({'datetime':data['datetime']})# Преобразование столбца СЃ датой Рё временем РІ datetime + data.set_index('datetime', inplace=True) # Установка индекса РїРѕ datetime + + features = data # Рзвлечение признаков + feature_scaler = MinMaxScaler() + scaled_features = feature_scaler.fit_transform(features) # Нормализация признаков + + def create_sequences(X, time_steps=1): + Xs = [] + for i in range(len(X) - time_steps): + Xs.append(X[i:(i + time_steps)]) + return np.array(Xs) + + time_steps = 10 + X_income = create_sequences(scaled_features, time_steps) # Создание последовательностей + y_predicted = lstm_model.predict(X_income) # Предсказание СЃ помощью модели LSTM + hoho['values'] = {'values':y_predicted} + return hoho + + +def prediction_XGBoost(data): + model = 0 + + +def calculate_mae(df1, df2): + df1.set_index('datetime', inplace=True) + df2.set_index('datetime', inplace=True) + + # Объединяем DataFrame РїРѕ индексу + merged_df = pd.concat(df1, df2) + return mean_absolute_error(df1['target'], df2['values']) + +if __name__ == '__main__': + data = smart_reader(pd.read_csv(f'data_train.csv')) + biba = data['datetime'] + meow = LSTM_feature_engineering(data) + #gav = XGB_feature_engineering(smart_reader(pd.read_csv('data_train.csv'))) + hehe = prediction_LSTM(data) + #haha = prediction_XGB(gav) + check = smart_reader(pd.read_csv(f'target_train.csv')) + print(check) + print(hehe) + print(calculate_mae(check, hehe), mean_absolute_error(check['values'], hehe['target'])) diff --git a/backend/server.py b/backend/server.py new file mode 100644 index 0000000000000000000000000000000000000000..84ab53ea3e071ddf4f8d5e4453bb46bb0a476f0c --- /dev/null +++ b/backend/server.py @@ -0,0 +1,35 @@ +# server.py +from fastapi import FastAPI, File, UploadFile, Depends, HTTPException +from sqlalchemy.orm import Session +from fastapi.responses import JSONResponse +import pandas as pd +from database import SessionLocal, FileContent, Base, engine + +app = FastAPI() + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() + +# async go_ml(content): +# # your ML code here] + +# return "ML result" + +@app.post("/uploadfile/") +async def create_upload_file(file: UploadFile = File(...), db: Session = Depends(get_db)): + content = await file.read() + # go_ml(content) + db_file = FileContent(filename=file.filename, content=content.decode('utf-8')) + db.add(db_file) + db.commit() + db.refresh(db_file) + return JSONResponse(content={"filename": file.filename, "content": db_file.content}) + +@app.get("/files/") +def read_files(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)): + files = db.query(FileContent).offset(skip).limit(limit).all() + return files diff --git a/frontend/app.py b/frontend/app.py new file mode 100644 index 0000000000000000000000000000000000000000..8456ac131931b7334d9d6e8bcfe63cf1bb4460bf --- /dev/null +++ b/frontend/app.py @@ -0,0 +1,129 @@ +# app.py +import streamlit as st +import requests +import asyncio +import aiohttp +import pandas as pd +import numpy as np +import networkx as nx +import plotly.express as px +from plotly.subplots import make_subplots +import plotly.graph_objects as go +import matplotlib.pyplot as plt +import io +from streamlit_option_menu import option_menu +import seaborn as sns + + +async def main(): + st.set_page_config(page_title="Uslugi santehnika", page_icon="рџ¤–") + with open('style.css') as f: + st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True) + + st.title("Виртуальный датчик") + + async with aiohttp.ClientSession() as session: + + # Sidebar Menu + with st.sidebar: + selected = option_menu( + "Меню", ["Загрузка файлов", "Анализ данных"], + icons=["house", "graph-up-arrow"], menu_icon="cast", default_index=0) + + uploaded_file = st.file_uploader("Выберите файл СЃ признаками", type=["csv"], key="my-upload-button") + normal_column_names = telemetry_dict = { + 'telemetry_0': 'temp4', #Температура (датчик 4) + 'telemetry_1': 'consumption', #Питание (загрузка печи) + 'telemetry_2': 'temp1', #Температура (датчик 1) + 'telemetry_3': 'ampere_add', #Сила тока + 'telemetry_4': 'press_add', #Давление (датчик 3) + 'telemetry_5': 'temp3', #Температура (датчик 3) + 'telemetry_6': 'speed', #Скорость + 'telemetry_7': 'press1', #Давление (датчик 1) + 'telemetry_8': 'press2', #Давление (датчик 2) + 'telemetry_9': 'temp2', #Температура (датчик 2) + 'telemetry_10': 'temp5', #Температура (датчик 5) + 'telemetry_11': 'temp6', #Температура (датчик 6) + 'telemetry_12': 'item1', #Концентрация газа 1 + 'telemetry_13': 'item2', #Концентрация газа 2 + 'telemetry_14': 'item3', #Концентрация газа 3 + 'telemetry_15': 'item4' #Концентрация газа 4 + } + # generate_file_input = st.button("Рллюстрация графиков") + if selected == "Загрузка файлов": + generate_file_input = st.button("Рллюстрация графиков") + if generate_file_input and uploaded_file: + + files = {"file": (uploaded_file.name, uploaded_file.getvalue())} + response = requests.post("http://localhost:8000/uploadfile/", files=files) + if response.status_code == 200: + s = response.json().get('content') + + df1 = pd.read_csv(io.StringIO(s), sep=",") + + + df1.rename(columns=normal_column_names, inplace=True) + df1['datetime'] = pd.to_datetime(df1['datetime']) + df1.drop(columns=['item1', 'item2', 'item3', 'item4'], inplace=True) + # fig = px.line(df1, y='target', title='График распределения предикт', labels={'index': 'Дата', 'target': 'Значение'}) + # st.plotly_chart(fig) + st.write(df1) + + uploaded_train_file = st.file_uploader("Выберите файл target", type=["csv"]) + generate_train_file_input = st.button("Рллюстрация графиков target") + + if generate_train_file_input and uploaded_train_file: + df = pd.read_csv(uploaded_train_file) + df.set_index(df.columns[0], inplace=True) + fig = px.line(df, y='target', title='График распределения target', labels={'index': 'Дата', 'target': 'Значение'}) + st.plotly_chart(fig) + st.write(df) + + elif selected == "Анализ данных": + st.header("Анализ данных") + + if uploaded_file: + df = pd.read_csv(uploaded_file) + df.rename(columns=normal_column_names, inplace=True) + df['datetime'] = pd.to_datetime(df['datetime']) + df.drop(columns=['item1', 'item2', 'item3', 'item4'], inplace=True) + st.write(df) + + show_test_of_time = st.button("График показаний каждого параметра РѕС‚ времени") + show_correlation_chart = st.button("График корреляции") + + if show_test_of_time: + fig, axs = plt.subplots(len(df.columns[1:]), 1, figsize=(10, 30), sharex=True) + for i, column in enumerate(sorted(df.columns[1:])): + axs[i].plot(pd.to_datetime(df['datetime']), df[column], label=column, color='blue') + axs[i].set_title(column) + axs[i].grid(True) + axs[i].legend() + fig.tight_layout() + plt.xlabel('Дата') + st.pyplot(fig) + + if show_correlation_chart: + # Удаление столбца СЃ датами РёР· данных для корреляции + df_corr = df.drop(columns=['datetime']) + + # Построение корреляционной матрицы + corr_matrix = df_corr.corr() + + # Отображение тепловой карты корреляционной матрицы + fig, ax = plt.subplots(figsize=(16, 14)) + sns.heatmap(corr_matrix, annot=True, fmt=".2f", cmap="coolwarm", ax=ax) + ax.set_title("Корреляционная матрица", fontsize=16) + + # Настройка меток РѕСЃРё x + ax.tick_params(axis='x', rotation=0) + ax.tick_params(axis='y', rotation=0) + + + st.pyplot(fig) + + + + +if __name__ == '__main__': + asyncio.run(main()) diff --git a/frontend/style.css b/frontend/style.css new file mode 100644 index 0000000000000000000000000000000000000000..003e3ba6575afece1099ebc84d337c5a97315e2b --- /dev/null +++ b/frontend/style.css @@ -0,0 +1,37 @@ +div.css-1 { + background-color: #100778; + border: 0cap; + padding: 20px 20px 20px 70px; +} + +.stButton > button { + background-color: #a9c4cc; + border: none; + border-radius: 4px; + color: black; +} + +.stButton:hover > button { + background-color: #5f8b99; + border: black; + color: black; +} + +.stButton:focus > button { + box-shadow: none; + outline: none; + color: purple; +} + +.stButton:active > button { + box-shadow: none; + outline: none; + color: black; +} + + +#my-upload-button > button { + background-color: #0000FF; + border: 2px solid #000000; + color: white; +}