Я написал программу, созданную на основе колбы. Эта программа в основном создана для умножения данных, которые она будет принимать, когда пользовательские данные будут случайным образом печатать данные, которые когда-либо захотят получить 5k .. 10k..so, после этого я хочусделать это через веб-страницу, чтобы я использовал Flask, там я добавил файл select (для просмотра CSV-файла) и количество записей, где пользователь указывает, сколько данных они хотят сгенерировать, и очень важная часть, где я застрял, то есть «из года»и «в год», который я делаю с помощью JavaScript в HTML-файле, это кнопка раскрывающегося списка, в которой указаны годы
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> upload </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link href="https://bootswatch.com/4/slate/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<script>
$( document ).ready(function() {
for(var i=1970; i<=2018; i++){
var fromYearSelect = document.getElementById("fromYear");
var toYearSelect = document.getElementById("toYear");
var option = document.createElement("OPTION");
fromYearSelect.options.add(option);
option.text = i;
option.value = i;
var option2 = document.createElement("OPTION");
toYearSelect.options.add(option2);
option2.text = i;
option2.value = i;
}
});
</script>
<body>
<div class="container">
<div class="jumbotron">
<div class = "mx-auto" style="width:500px;">
<h1>Large Data Generation</h1>
</div>
</div>
<form id = "upload-form" action="{{ url_for('upload') }}" method="POST" enctype="multipart/form-data">
<div id="file-selector">
<strong>Input File: </strong>
<input id="source_fileName" type="file" name="source_fileName" accept="csv/*" multiple style="
margin-left: 30px;">
</div>
<br></br>
<div id="div_records">
<strong>Record Count: </strong>
<input id="records" type="text" name="records" value="1000" >
<br> <br> <br>
<strong>From Year: </strong>
<select id="fromYear" name="fromYear" style="margin-left: 25px;"></select>
<!-- <input type="month" id="fromDate" name="fromDate" multiple style="margin-left: 20px;" > -->
<strong style="margin-left:20px">To Year: </strong>
<select id="toYear" name="toYear" style="margin-left: 5px;"></select>
<!-- <input type="month" id="toDate" name="toDate" multiple style="margin-left: 40px;"> -->
</div>
<br></br><br></br>
<input type="submit" value="Manufacture Data" id="upload-button" >
</form>
</div>
</body>
Эта программа очень хорошо работает, когда я выбираю диапазон лет меньше 5, если я выбираюбольше 5 он не работает.
from io import StringIO
import pandas as pd
import numpy as np
import random
import os
import csv
from random import randint
from flask import Flask, render_template, request,Response, redirect, make_response
import boto3
from botocore.client import Config
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
tempFile =""
#defined the flask route
@app.route("/")
def index():
print("Loading the root file")
return render_template("uploadDataManf.html")
@app.route("/uploadDataManf", methods=['POST'])
def upload():
target = os.path.join(APP_ROOT, 'metadata/')
print("target-",target)
if not os.path.isdir(target):
os.mkdir(target)
global recordCount
recordCount = int(request.values.get("records"))
print("recordCount-",recordCount)
global fromYear
fromYear = int(request.values.get("fromYear"))
print("From Year - " + request.values.get("fromYear"));
global toYear
toYear = int(request.values.get("toYear"))
print("To Year - " + request.values.get("toYear"));
for file in request.files.getlist("source_fileName"):
print("file-",file)
filename = file.filename
print("filename-",filename)
destination = "/".join([target, filename])
print("destination-",destination)
file.save(destination)
print("file>",file)
global tempFile
tempFile = destination
print("tempFile - " + tempFile)
#define global scope and reference it
global destination_fileName
destination_fileName = request.form.get('target_fileName')
print("destination_fileName",destination_fileName)
return redirect("/compute", )
def segment():
number= recordCount
a = number
n = 12
assert a >= n >= 1
seg = []
for idx in range(n-1):
# Number between 1 and a
# minus the current total so we don't overshoot
# minus 1 for each number that hasn't been picked
# so they can all be nonzero
seg.append(randint(1,a-sum(seg)-n+idx))
seg.append(a-sum(seg))
random.shuffle(seg)
print("NumberOfseg-",seg)
return seg
@app.route("/compute")
def compute():
Year_Array=[]
for val in range(fromYear, toYear+1):
Year_Array.append(val)
print("Year Array - ",Year_Array)
Month_Array=['Jan','Feb','Mar','April','May','June','July','Aug','Sep','Oct','Nov','Dec']
final_Array=[]
p=0
global recordCount
recordCount = recordCount / len(Year_Array)
df = pd.read_csv(tempFile)
temp = df.iloc[1]
print(temp)
#print(temp.loc)
#print(temp['Asset_Id'])
for p in range(0, len(Year_Array), 1):
c = 0
# Regenerate segments
seg = segment()
for i in range(0,len(seg), 1):
h=seg[i]
for j in range(0, int(h) , 1):
num=randint(0, len(df)-1)
row=df.iloc[num]
final_Array.append(((Year_Array[p], Month_Array[c],row.get("Asset_Id"),row.get("Asset Family"),row.get("Asset Name"),row.get("Location"),row.get("Asset Component"),row.get("Keywords"),row.get("Conditions"),row.get("Parts"))))
c += 1
data = pd.DataFrame(final_Array)
data['SR_ID'] = 'SR_' + pd.Series(np.arange(1, len(data.index) + 1)).astype(str).str.zfill(4)
data.columns = ['Year', 'Month', 'Asset_Id ', 'Asset Family', 'Asset Name', 'Location', 'Asset Component', 'Keywords', 'Conditions', 'Parts','SR_ID']
result = data[['SR_ID','Year', 'Month', 'Asset_Id ', 'Asset Family', 'Asset Name', 'Location', 'Asset Component', 'Keywords', 'Conditions', 'Parts']]
print("result-",result)
resp = make_response(result.to_csv(index=False,))
resp.headers["Content-Disposition"] = "attachment; filename=OutputData.csv"
resp.headers["Content-Type"] = "text/csv"
return resp
if __name__ == '__main__':
app.run(debug=True)
На самом деле я знаю, в чем проблема, это в функции compute
, где у меня есть:
global recordCount
recordCount = recordCount / len(Year_Array)
Если я уберу это, это решит моипроблема, но после этого он не будет генерировать данные в соответствии с пользователем, он будет умножать данные с диапазоном лет, что я не хочу, я хочу, если я выберу в записиcount 1k означает, что он должен печатать только 1k, не более того.
Пример ввода файла csv:
Asset_Id Asset Family Asset Name Location Asset Component Keywords Conditions Parts
1 Haptic Analyser HAL1 Zenoa Tetris Measuring Unit Measurement Inaccuracy, Mirror Angle Skewed Alignment - Lower Axis - positive angle Tetris Controller, Measurement Unit, Processor, Signal Emitter, TDU
1 Haptic Analyser HAL1 Zenoa Micro Pressure Platform Low air pressure, Pressure - Fluctuating Measuring Faces, Cycle Timer, Pressure Simulator, Platform Unit, Sensometer, Pressure Release,
1 Haptic Analyser HAL1 Technopolis Rotation Chamber Rotation Chamber Intermittent Slowdown Current - Fluctuating Anti-Rotation Pin, Springs, Gyroscope, Joiner, Separator, Sealant, Chamber Enclosure, Mount Unit
1 Haptic Analyser HAL1 Technopolis Mirror Lens Combinator Mirror Angle Skewed, Alignment - Mid Axis - negative angle "Mirror Unit, Lens Unit,
2 Hyperdome Inspector HISP1 Technopolis Turbo Quantifier Quantifier output Drops Intermittently Pressure - Low Gas Generator, Quantifier Processing Unit, Turbo Generator, Backup Unit, Turbo Drive
2 Hyperdome Inspector HISP1 Technopolis Generator Generator Power Failure, Vibration - 135% above threshold Generator Armature, Generator Unit, Measurement Gauge, Pressure Gauge, Temperature Gauge,
2 Hyperdome Inspector HISP1 Technopolis High Frequency Emulator Emulator Frequency Drop Speed at entrance - Fluctuating Amplifier, Oscillator, Frequency Emulator, Display Unit, High Frequency Simululator, Drum,
2 Hyperdome Inspector HISP1 Zenoa Center Stage Stage not Balanced Vibration - 110% above threshold Stage Support, Stage Enclosure, Stage Balancer, Alignment Unit, Line Control,