Team Ai
Apppublic

atriguha/PythonProject

sourceHugging Faceupdated 4y agoView on Hugging Face
0likes
app.py713 linesDownload Raw Back to root
1import streamlit as st2from platform import python_version3import os4import pandas as pd5from datetime import datetime6 7import openpyxl 8from openpyxl.styles import PatternFill, Border, Side9from openpyxl.utils.dataframe import dataframe_to_rows10from openpyxl import Workbook11 12# [theme]13# primaryColor = "#E694FF"14# backgroundColor = "#00172B"15# secondaryBackgroundColor = "#0083B8"16# textColor = "#C6CDD4"17# font = "sans-serif"18# add_selectbox = st.sidebar.selectbox(19#     "How would you like to be contacted?",20#     ("Email", "Home phone", "Mobile phone")21# )22 23# Using "with" notation24# with st.sidebar:25#     add_radio = st.radio(26#         "Choose a shipping method",27#         ("Standard (5-15 days)", "Express (2-5 days)")28#     )29def tut4(of):30    u = of['U']  # assigning a list to columns of input file31    v = of['V']32    w = of['W']33    t = of['T']34 35    # calculating the avg value sum() returns summation and len() return length36    avgu = [sum(u) / len(u)]37    avgv = [sum(v) / len(v)]38    avgw = [sum(w) / len(w)]39 40    au = sum(u) / len(u)41    av = sum(v) / len(v)42    aw = sum(w) / len(w)43 44    u_ = []45    v_ = []46    w_ = []47 48    for i in u:49        u_.append(i - au)  # pushing the element at back of list50    for i in v:51        v_.append(i - av)52    for i in w:53        w_.append(i - aw)54 55    # filling the remaining spaces in the column with blank space using extend function56    avgu.extend([''] * (len(u) - 1))57    avgv.extend([''] * (len(u) - 1))58    avgw.extend([''] * (len(u) - 1))59 60    octs = [1, -1, 2, -2, 3, -3, 4, -4]61 62    lenc = {}  # dictionary to store longest subsequence length for each octant63    for i in octs:64        lenc[i] = 065 66    octants = []  # list to store octants for each case67 68    col2 = []  # column to store longest subsequence length for each octant69    col4 = []  # column to store octants and time row70    col5 = []  # column to store start time71    col6 = []  # column to store end time72 73    # loop to determine the octant and to store the octants74    # and update the length of subsequence with maxmimum length each time75    c = 176    p = 177    for i in range(len(u_)):78        oc = 179        if (u_[i] > 0) and (v_[i] > 0) and (w_[i] > 0):80            oc = 181        elif (u_[i]) < 0 and (v_[i]) > 0 and (w_[i]) > 0:82            oc = 283        elif (u_[i]) < 0 and (v_[i]) < 0 and (w_[i]) > 0:84            oc = 385        elif (u_[i]) > 0 and (v_[i]) < 0 and (w_[i]) > 0:86            oc = 487        elif (u_[i]) > 0 and (v_[i]) > 0 and (w_[i]) < 0:88            oc = -189        elif (u_[i]) < 0 and (v_[i]) > 0 and (w_[i]) < 0:90            oc = -291        elif (u_[i]) < 0 and (v_[i]) < 0 and (w_[i]) < 0:92            oc = -393        elif (u_[i]) > 0 and (v_[i]) < 0 and (w_[i]) < 0:94            oc = -495 96        octants.append(oc)97        if i > 0:98            if oc == p:99                c += 1100            else:101                c = 1102        p = oc103        lenc[oc] = max(lenc[oc], c)104 105    octants.extend([''] * (len(u_) - len(octants)))106 107    of['         '] = ''108 109    col1 = []  # column to store the octant values110    for i in octs:111        col1.append(i)112 113    col1.extend([''] * (len(u_) - len(col1)))114    of['Octant ##'] = col1115 116    # column to store the longest subsequence length for each octant value117    for i in lenc.values():118        col2.append(i)119 120    col2.extend([''] * (len(u_) - len(col2)))121    of['Longest Subsequence Length'] = col2122 123    col3 = []  # column to store count of longest subsequence for each octant value124 125    maxc = {}  # dictionary to store count of longest subsequence for each octant value126    maxl = {}  # dictionary to store start and end time for each octant's longest subsequence127    for i in octs:128        maxc[i] = 0129        maxl[i] = []130 131    p = 0132    c = 1133    time = t[0]134    f = 0135    j = 0136    # loop performing required operations to store count of longest subsequence for each octant value137    # and start and end time for each longest subsequence of individual octant138    for i in octants:139        if f == 0:140            time = t[j]141            f = 1142        oc = i143        if oc == p:144            c += 1145        else:146            c = 1147            time = t[j]148 149        if c == lenc[oc]:150            maxc[oc] += 1151            maxl[oc].append([time, t[j]])152            f = 0153 154        p = oc155        j = j + 1156 157    for i in maxc.values():158        col3.append(i)159 160    col3.extend([''] * (len(u_) - len(col3)))161    of['Count '] = col3162 163    of['      '] = ''164 165    # forming the required output columns accordingly from this tut's output166    for i in octs:167        col4.append(i)168        col5.append(lenc[i])169        col6.append(maxc[i])170 171        col4.append('Time')172        col5.append('From')173        col6.append('To')174 175        for j in maxl[i]:176            col5.append(j[0])177            col6.append(j[1])178 179        col4.extend([''] * (len(col6) - len(col4)))180 181    cnt = len(col6)182    col4.extend([''] * (len(u_) - len(col4)))183    col5.extend([''] * (len(u_) - len(col5)))184    col6.extend([''] * (len(u_) - len(col6)))185 186    of['Octant ###'] = col4187    of[' Longest Subsequence Length'] = col5188    of['Count  '] = col6189    return cnt190 191 192def tut2(of, mod=5000):193    u = of['U']  # assigning list to columns of input file194    v = of['V']195    w = of['W']196 197    # calculating the avg value sum() returns summation and len() return length198    avgu = [sum(u) / len(u)]199    avgv = [sum(v) / len(v)]200    avgw = [sum(w) / len(w)]201 202    au = sum(u) / len(u)203    av = sum(v) / len(v)204    aw = sum(w) / len(w)205 206    u_ = []207    v_ = []208    w_ = []209 210    for i in u:211        u_.append(i - au)  # pushing the element at back of list212    for i in v:213        v_.append(i - av)214    for i in w:215        w_.append(i - aw)216 217    # filling the remaining spaces in the column with blank space218    avgu.extend([''] * (len(u) - 1))219    avgv.extend([''] * (len(u) - 1))220    avgw.extend([''] * (len(u) - 1))221 222    col = ['', 'User Input']223    col.extend([''] * (len(u_) - 2))224 225    ranges = (len(u_) + mod - 1) // mod226 227    oc_id = ['Overall Count', 'Mod ' + str(mod)]228    # loop for creating the mod range's column229    for i in range(ranges):230        if i == ranges - 1:231            oc_id.append(str(i * mod) + '-' +232                         str(min((i + 1) * mod - 1, len(u) - 1)))233        else:234            oc_id.append(str(i * mod) + '-' + str((i + 1) * mod - 1))235 236    octs = [1, -1, 2, -2, 3, -3, 4, -4]237    values = {}238    xx = {}239 240    ran = 2 + int(len(u_) / mod) + bool(len(u_) // mod) + 14 * \241        (1 + int(len(u_) / mod) + bool(len(u_) // mod))242 243    num = 2 + int(len(u_) / mod) + bool(len(u_) // mod)244 245    # initializing the dictionary with value equal to 0 and blank spaces as per requirements246    for i in octs:247        values[i] = [0] * (ran)248        values[i][1] = ''249 250        for k in range(num - 1):251            for j in range(5):252                values[i][j + 14 * k + num] = ''253 254        values[i][num + 5] = i255        xx[i] = 0256 257    octants = []258 259    # dictionary to store position of octant in columns260    inds = {}261    inds[1] = num + 6262    col[inds[1]] = "From"263 264    for i in range(len(octs)):265        if i > 0:266            inds[octs[i]] = inds[octs[i - 1]] + 1267 268    # loop to determine the octant and to store the counts of octants269    # and to store the total transition count270    p = 1271    for i in range(len(u_)):272        oc = 1273        if (u_[i] > 0) and (v_[i] > 0) and (w_[i] > 0):274            oc = 1275        elif (u_[i]) < 0 and (v_[i]) > 0 and (w_[i]) > 0:276            oc = 2277        elif (u_[i]) < 0 and (v_[i]) < 0 and (w_[i]) > 0:278            oc = 3279        elif (u_[i]) > 0 and (v_[i]) < 0 and (w_[i]) > 0:280            oc = 4281        elif (u_[i]) > 0 and (v_[i]) > 0 and (w_[i]) < 0:282            oc = -1283        elif (u_[i]) < 0 and (v_[i]) > 0 and (w_[i]) < 0:284            oc = -2285        elif (u_[i]) < 0 and (v_[i]) < 0 and (w_[i]) < 0:286            oc = -3287        elif (u_[i]) > 0 and (v_[i]) < 0 and (w_[i]) < 0:288            oc = -4289 290        octants.append(oc)291        values[oc][0] += 1292        values[oc][2 + i // mod] += 1293 294        if i > 0:295            values[oc][inds[p]] += 1296 297        p = oc298 299    # formation and adjustment of octant id column300    for i in range(3):301        oc_id.append('')302 303    oc_id.append('Overall Transition Count')304    oc_id.append('')305    oc_id.append('Count')306    values[1][num + 4] = "To"307 308    for i in range(len(octs)):309        oc_id.append(octs[i])310 311    p = octants[0]312    # loop for individual mod range's transition count and table formation313    for i in range(num - 2):314 315        for j in range(3):316            oc_id.append('')317 318        oc_id.append('Mod Transition Count')319 320        if i == num - 3:321            oc_id.append(str(i * mod) + '-' +322                         str(min((i + 1) * mod - 1, len(u) - 1)))323        else:324            oc_id.append(str(i * mod) + '-' + str((i + 1) * mod - 1))325 326        values[1][inds[1] + 14 - 2] = "To"327        col[inds[1] + 14] = "From"328        oc_id.append("Octant #")329 330        for j in octs:331            oc_id.append(j)332 333        for j in octs:334            values[j][inds[1] + 14 - 1] = j335 336        for j in range(mod * (i) + 1, min(mod * (i + 1), len(u_) - 1) + 1):337            oc = octants[j]338 339            if j > 0:340                values[oc][inds[p] + 14] += 1341            p = oc342 343        for j in octs:344            inds[j] += 14345 346    oc_id.extend([''] * (len(u_) - len(oc_id)))347 348    # forming the columns required from this tut's output349    for i in octs:350        values[i].extend([''] * (len(u_) - len(values[i])))351 352    req1 = []353    req2 = []354    req3 = {}355    for i in octs:356        req3[i] = []357 358    for i in range(len(oc_id)):359        if i >= num + 4:360            req1.append(col[i])361            req2.append(oc_id[i])362            for j in octs:363                req3[j].append(values[j][i])364 365    blank = [''] * (len(u_))366    of['ok1'] = blank367 368    req1.extend([''] * (len(u_) - len(req1)))369    req2.extend([''] * (len(u_) - len(req2)))370    of['ok2' + col[num + 3]] = req1371    of[oc_id[num + 3]] = req2372 373    i = 3374    for j in octs:375        req3[j].extend([''] * (len(u_) - len(req3[j])))376        of['ok' + str(i) + values[j][num + 3]] = req3[j]377        i = i + 1378 379 380cols = {}381cols[1] = 23382cols[-1] = 24383cols[2] = 25384cols[-2] = 26385cols[3] = 27386cols[-3] = 28387cols[4] = 29388cols[-4] = 30389 390 391def tut5(of, f, poss, mod=5000):392    # try:393    octant_name_id_mapping = {"1": "Internal outward interaction", "-1": "External outward interaction",394                              "2": "External Ejection", "-2": "Internal Ejection",395                              "3": "External inward interaction", "-3": "Internal inward interaction",396                              "4": "Internal sweep", "-4": "External sweep"}397    398    u = of['U']  # assigning a list to columns of input file399    v = of['V']400    w = of['W']401 402    # calculating the avg value sum() returns summation and len() returns length403    avgu = [round(sum(u) / len(u), 3)]404    avgv = [round(sum(v) / len(v), 3)]405    avgw = [round(sum(w) / len(w), 3)]406 407    au = round(sum(u) / len(u), 3)408    av = round(sum(v) / len(v), 3)409    aw = round(sum(w) / len(w), 3)410 411    u_ = []412    v_ = []413    w_ = []414 415    for i in u:416        u_.append(round(i - au, 3))  # pushing the element at the end of list using append417    for i in v:418        v_.append(round(i - av, 3))419    for i in w:420        w_.append(round(i - aw, 3))421 422    # filling the remaining spaces in the column with blank space using extend 423    avgu.extend([''] * (len(u) - 1))424    avgv.extend([''] * (len(u) - 1))425    avgw.extend([''] * (len(u) - 1))426 427    try:428        of["U Avg"] = avgu  # creating a column in output file429        of["V Avg"] = avgv430        of["W Avg"] = avgw431 432        of["U'=U-U avg"] = u_433        of["V'=V-V avg"] = v_434        of["W'=W-W avg"] = w_435    except:436        print('Error encountered : Mismatch in length of columns')437 438    emp = [''] * (len(u_))439    col = ['', 'Mod ' + str(mod)]440    col.extend([''] * (len(u_) - 2))441 442    ranges = (len(u_) + mod - 1) // mod443 444    oc_id = ['Overall Count']445 446    # loop for creating the mod range's column447    for i in range(ranges):448        if i == ranges - 1:449            oc_id.append(str(i * mod) + '-' +450                         str(min((i + 1) * mod - 1, len(u) - 1)))451        else:452            oc_id.append(str(i * mod) + '-' + str((i + 1) * mod - 1))453 454    octs = [1, -1, 2, -2, 3, -3, 4, -4]455    values = {}  # columns before ranking starts456    ranks = {}  # columns containing ranks457    rank = []458    rank.extend([''] * (len(u_)))459    name = []460    name.extend([''] * (len(u_)))461 462    ran = 2 + int(len(u_) / mod) + bool(len(u_) // mod) + 14 * \463        (1 + int(len(u_) / mod) + bool(len(u_) // mod))464 465    num = 1 + int(len(u_) / mod) + bool(len(u_) // mod)466 467    # initializing the dictionary with value equal to 0 and blank spaces as per requirements468    for i in octs:469        values[i] = [''] * (len(u_))470        values[i] = [0] * (num)471        ranks[i] = [''] * (len(u_))472        ranks[i] = [0] * (num)473 474    octants = []475 476    # loop to determine the octant and to store the counts of octants477    # and to store the total transition count478 479    for i in range(len(u_)):480        oc = 1481        if (u_[i] > 0) and (v_[i] > 0) and (w_[i] > 0):482            oc = 1483        elif (u_[i]) < 0 and (v_[i]) > 0 and (w_[i]) > 0:484            oc = 2485        elif (u_[i]) < 0 and (v_[i]) < 0 and (w_[i]) > 0:486            oc = 3487        elif (u_[i]) > 0 and (v_[i]) < 0 and (w_[i]) > 0:488            oc = 4489        elif (u_[i]) > 0 and (v_[i]) > 0 and (w_[i]) < 0:490            oc = -1491        elif (u_[i]) < 0 and (v_[i]) > 0 and (w_[i]) < 0:492            oc = -2493        elif (u_[i]) < 0 and (v_[i]) < 0 and (w_[i]) < 0:494            oc = -3495        elif (u_[i]) > 0 and (v_[i]) < 0 and (w_[i]) < 0:496            oc = -4497 498        octants.append(oc)499        values[oc][0] += 1500        values[oc][1 + i // mod] += 1501 502    # formation and adjustment of octant id column503    for i in range(3):504        oc_id.append('')505 506    try:507        of['Octant'] = octants508        of[' '] = emp509        of[''] = col  # forming a column in output file510    except:511        print('Error encountered : Mismatch in length of columns')512 513    oc_id.extend([''] * (len(u_) - len(oc_id)))514    of['Octant ID'] = oc_id515 516    cnt = {}517    for i in octs:518        cnt[i] = 0519    520    #loop to calculate rank of each octant for each mod range and assignment of the values521    for i in range(num):522        seq = []523        for j in octs:524            seq.append([values[j][i], j])525        seq.sort()526 527        for j in range(len(seq)):528            ranks[seq[j][1]][i] = 8 - j529 530        rank[i] = seq[len(seq) - 1][1]531        poss.append([rank[i], i])532        name[i] = octant_name_id_mapping[str(rank[i])]533 534        if i != 0:535            cnt[rank[i]] = cnt[rank[i]] + 1536 537    for i in range(1):538        ranks[4].append('')539        ranks[-4].append('')540 541    ranks[4].append('Octant ID')542    ranks[-4].append('Octant Name')543    rank[num + 1] = 'Count of Rank 1 Mod values'544 545    # representation of name of each octant and count of rank 1 value546    j = num + 2547    for i in octs:548        ranks[4].append(str(i))549        ranks[-4].append(octant_name_id_mapping[str(i)])550        rank[j] = cnt[i]551        j = j + 1552 553    #count of each octant in each mod range554    for i in octs:555        values[i].extend([''] * (len(u_) - len(values[i])))556        of[str(i)] = values[i]557    558    #rank columns of each octant559    for i in octs:560        ranks[i].extend([''] * (len(u_) - len(ranks[i])))561        of['Rank Octant ' + str(i)] = ranks[i]562 563    #forming the output columns564    of['Rank1 Octant ID'] = rank565    of['Rank1 Octant Name'] = name566 567 568 569opdir = 'output'570def tut7(f):571      # forming the output directory if not present572    if not os.path.exists(opdir):573        os.makedirs(opdir)574 575    # for f in files:576        # if ('input/' + f)[-4:] == 'xlsx':577        # reading the input file578    df = pd.read_excel(f)579    of = df580 581    u = of['U']582    num = 2 + int(len(u) / mod) + bool(len(u) // mod)583 584    # calling the required functions585    poss = []586    tut5(of, f, poss, mod)587    tut2(of, mod)588    cnt = int(tut4(of))589 590    heads = []591    c = 33592    while c <= 43:593        if c != 35:594            heads.append(c)595        c = c+1596 597    # forming a dataframe in openpyxl from pandas dataframes598    wb = Workbook()599    sheet = wb.active600    for r in dataframe_to_rows(df, index=False, header=True):601        sheet.append(r)602 603    yellow = "00FFFF00"604 605    # coloring and bordering the required cells using openpxyl's606    # patternfill and border function607    for i in range(len(poss)):608        c = cols[poss[i][0]]609        r = int(poss[i][1]+2)610        sheet.cell(row=r, column=c).fill = PatternFill(611            patternType="solid", fgColor=yellow)612 613    for i in range(len(heads)):614        sheet.cell(row=1, column=heads[i]).value = ' '615 616    c = 14617    borcol = []618    while c <= 32:619        borcol.append(c)620        c = c+1621 622    black = '000000'623    thin_border = Border(left=Side(style='thin', color=black),624                            right=Side(style='thin', color=black),625                            top=Side(style='thin', color=black),626                            bottom=Side(style='thin', color=black))627    for i in range(len(borcol)):628        for j in range(num):629            sheet.cell(row=j+1, column=borcol[i]).border = thin_border630 631    for i in range(9):632        sheet.cell(row=num + 2 + i, column=29).border = thin_border633        sheet.cell(row=num + i + 2, column=30).border = thin_border634        sheet.cell(row=num + i + 2, column=31).border = thin_border635 636    borcol = []637    c = 35638    while c <= 43:639        borcol.append(c)640        c = c+1641 642    ran = int(len(u)/mod)+bool(len(u) % mod)+1643    row = 0644    for k in range(ran):645        row = row+2646        for i in range(len(borcol)):647            for j in range(9):648                sheet.cell(649                    row=row+1+j, column=borcol[i]).border = thin_border650        row = row+12651 652    c = 44653    while c <= 46:654        c = c+1655        for i in range(9):656            sheet.cell(row=i + 1, column=c).border = thin_border657 658    for i in range(cnt+1):659        sheet.cell(row=1 + i, column=49).border = thin_border660        sheet.cell(row=i+1, column=50).border = thin_border661        sheet.cell(row=i+1, column=51).border = thin_border662 663    # forming the required output file by saving openpyxl dataframe664    wb.save(os.path.join(665            opdir, f.name[0:-4] + '_octant_analysis_mod_' + str(mod) + '.xlsx'))666 667st.title('Get output file of CS384-2022 tut-7 for free')668f=[]669 670f = st.sidebar.file_uploader('Upload your input file in xlsx format', accept_multiple_files=True671)672# f = st.file_uploader('Upload your input file in xlsx format', accept_multiple_files=True)673from zipfile import ZipFile674 675mod=0676if f is not None:677    mod=int(st.number_input('Please enter mod value'))678    if mod!=0:679        680        if st.button('Compute'):681            cnt=100/len(f)682            num=0683            bar=st.progress(num)684            for files in f:685                num+=cnt686                bar.progress(int(num))687                # print(files.name)688                tut7(files)        689            690    else:691        st.warning('Mod cannot be zero')692    693st.title('')694st.write('Output files ready for download👇')695opdir="output"696for files in os.listdir(opdir):697    # print(files)698    st.download_button("Download "+(files), os.path.join(opdir,files), file_name=files)699 700st.title('')701st.write("Thank us later✌")702 703# with ZipFile('my_python_files.zip','w') as zip:704#     # writing each file one by one705#     opdir="output"706#     for file in opdir:707#         zip.write(file)708 709# print('All files zipped successfully!') 710 711 712 713# pipreqs opdir