Exemplo n.º 1
0
def app():
    nodes = []
    edges = []

    nodes.append(Node(id="Spiderman", label="Spid", size=400))
    nodes.append(Node(id="Captain_Marvel", label="marvel", size=400))
    edges.append(
        Edge(source="Captain_Marvel", target="Spiderman", label="friend_of"))

    # nodes = [Node(id=n['id'], label=n['name']) for n in json_nodes]  # add value to payload
    # edges = [Edge(source=e['sourceId'], target=e['targetId']) for e in json_edges]

    config = Config(
        width=1600,
        height=1000,
        directed=True,
        nodeHighlightBehavior=True,
        highlightColor="#F7A7A6",
        collapsible=True,
        node={'labelProperty': 'label'},  # config labelProperty
        link={
            'labelProperty': 'label',
            'renderLabel': True
        })

    return_value = agraph(nodes=nodes, edges=edges, config=config)
Exemplo n.º 2
0
def app():
  footer()
  st.title("Graph Example")
  st.sidebar.title("Welcome")
  filename = file_selector()
  st.write('You selected `%s`' % filename)
  # sparql_endpoint = st.sidebar.text_input("SPARQL ENDPOINT: ", "http://dbpedia.org/sparql")
  query_type = st.sidebar.selectbox("Quey Tpye: ", ["Person", "Inspirationals"], key="second") #rdfs:Resource , "Company", "Location"
  # resource_name = st.sidebar.text_input("Quey Tpye: ", "Barack_Obama" )
  config = Config(height=500, width=700, nodeHighlightBehavior=True, highlightColor="#F7A7A6", directed=True,
                  collapsible=True)
  if query_type == "Person":
    st.subheader("Person (Date of birth and place)")
    persons = list(get_people())
    st.write(len(persons))
    chosen_person = st.sidebar.selectbox("Choose a Person: ", persons)
    nodes, edges = do_query(chosen_person)
    agraph(nodes, edges, config)
  if query_type=="FOAF":
    st.subheader("Inspirationals")
    with st.spinner("Loading data"):
      store = get_inspired()
      st.write(len(store.getNodes()))
    st.success("Done")
    agraph(list(store.getNodes()), (store.getEdges() ), config)
Exemplo n.º 3
0
def app():
  st.subheader("Person (Date of birth and place)")
  persons = list(get_people())
  st.write(len(persons))

  chosen_person = st.sidebar.selectbox("Choose a Person: ", persons)
  config = Config(height=500, width=700, nodeHighlightBehavior=True,
                  highlightColor="#F7A7A6", directed=True, collapsible=True)
  if chosen_person != "":
    store, abstract = get_people(chosen_person)
Exemplo n.º 4
0
def plot_graph2(graph):
    nodes = [Node(id=i, label=str(i), size=200) for i in range(len(graph.nodes))]
    edges = [Edge(source=i, target=j, type="CURVE_SMOOTH") for (i, j) in graph.edges]

    config = Config(width=500,
                    height=500,
                    directed=True,
                    nodeHighlightBehavior=True,
                    highlightColor="#F7A7A6",
                    collapsible=True,
                    node={'labelProperty': 'label'},
                    link={'labelProperty': 'label', 'renderLabel': True}
                    )

    return_value = agraph(nodes=nodes,
                          edges=edges,
                          config=config)
Exemplo n.º 5
0
def app():
  persState = PersService.state()
  st.subheader("Person (Date of birth and place)")
  st.markdown("---")
  if not persState.loaded:
    st.write("Please load data in the Data Management Page first.")
    node_names = []
  else:
    store = persState.store
    algos = persState.algos
    node_names = persState.node_names

  persons = list(PersService.get_people())
  st.write(len(persons))

  chosen_person = st.sidebar.selectbox("Choose a Person: ", persons)

  config = Config(height=500, width=700, nodeHighlightBehavior=True,
                  highlightColor="#F7A7A6", directed=True, collapsible=True)
  if chosen_person != "":
    store, abstract = PersService.load_persons(chosen_person)
Exemplo n.º 6
0
def app():
    footer()
    st.title("Graph Example")
    st.sidebar.title("Welcome")
    query_type = st.sidebar.selectbox(
        "Query Tpye: ", ["Inspirationals", "Marvel"]
    )  # could add more stuff here later on or add other endpoints in the sidebar.
    config = Config(height=600,
                    width=700,
                    nodeHighlightBehavior=True,
                    highlightColor="#F7A7A6",
                    directed=True,
                    collapsible=True)

    if query_type == "Inspirationals":
        st.subheader("Inspirationals")
        with st.spinner("Loading data"):
            store = get_inspired()
            st.write("Nodes loaded: " + str(len(store.getNodes())))
        st.success("Done")
        agraph(list(store.getNodes()), (store.getEdges()), config)

    if query_type == "Marvel":
        #based on http://marvel-force-chart.surge.sh/
        with open("./marvel.json", encoding="utf8") as f:
            marvel_file = json.loads(f.read())
            marvel_store = TripleStore()
            for sub_graph in marvel_file["children"]:
                marvel_store.add_triple(marvel_file["name"],
                                        "has_subgroup",
                                        sub_graph["name"],
                                        picture=marvel_file["img"])
                for node in sub_graph["children"]:
                    node1 = node["hero"]
                    link = "blongs_to"
                    node2 = sub_graph["name"]
                    pic = node["img"]
                    marvel_store.add_triple(node1, link, node2, picture=pic)
            agraph(list(marvel_store.getNodes()), (marvel_store.getEdges()),
                   config)
Exemplo n.º 7
0
def app():
    df = load_data(path)
    st.title("Open Knowledge Graph Visualization")

    heads = st.multiselect('Choose heads', df["head"].unique())
    threshold = st.slider('Set confidence threshold',
                          0.,
                          df["confidence"].max(),
                          value=0.0000001)

    store = subset_data(df, heads, threshold)

    config = Config(height=600,
                    width=700,
                    nodeHighlightBehavior=True,
                    highlightColor="#F7A7A6",
                    directed=True,
                    collapsible=True,
                    link={"renderLabel": True})

    st.write("Nodes loaded: " + str(len(store.getNodes())))

    agraph(list(store.getNodes()), (store.getEdges()), config)
Exemplo n.º 8
0
    graph.replace_filters(triplet_filters=triplet_filters,
                          group_filters=group_filters)
    return graph


# Debug check to see if filters are added correctly
if st.button("Print input to terminal"):
    print(filters.values())
    print(group_filters.values())

# Construct the knowledge graph (time consuming part)
graph = create_graph_with_filters(list(filters.values()),
                                  list(group_filters.values()))
# Get the nodes
nodes = set([triplet.head for triplet in graph.filtered_triplets])
# Choose nodes to plot
st.write("N. nodes loaded: " + str(len(nodes)))
heads = st.multiselect("Choose nodes to plot", list(nodes))

# convert selected nodes to streamlit graph store
store = beliefgraph_to_triplestore(graph, heads)

config = Config(height=600,
                width=700,
                nodeHighlightBehavior=True,
                highlightColor="#F7A7A6",
                directed=True,
                collapsible=True,
                link={"renderLabel": True})

agraph(list(store.getNodes()), (store.getEdges()), config)
Exemplo n.º 9
0
    edges.append(
        Edge(source="Captain_Marvel",
             label="Amiga de ",
             target="Spiderman",
             type="CURVE_SMOOTH"))  # includes **kwargs
    edges.append(
        Edge(source="Captain_Marvel",
             label="Conhece o",
             target="Thor",
             type="CURVE_SMOOTH"))  # includes **kwargs
    edges.append(Edge(source="Thor", label="Inimigo de",
                      target="Thanos"))  # includes **kwargs

    config = Config(
        width=500,
        height=500,
        directed=True,
        nodeHighlightBehavior=True,
        highlightColor="#F7A7A6",  # or "blue"
        collapsible=True,
        node={'labelProperty': 'label'},
        link={
            'labelProperty': 'label',
            'renderLabel': True
        }
        # **kwargs e.g. node_size=1000 or node_color="blue"
    )

    return_value = agraph(nodes=nodes, edges=edges, config=config)
Exemplo n.º 10
0
    # session_state.checkboxed = True
=======
  if not inspState.loaded:
    st.write("Please load data in the Data Management Page first.")
    node_names = []
>>>>>>> 6f6a9624da414e66674de21213f6c8f387db8519
  else:
    store = inspState.store
    algos = inspState.algos
    node_names = inspState.node_names
  if len(node_names) > 0:
    chosen_person_a = st.sidebar.selectbox("Choose Person A: ", node_names, key="p1")
    chosen_person_b = st.sidebar.selectbox("Choose Person B: ", node_names, key="p2")
    algo_type = st.sidebar.selectbox("Algo ", ["", "Shortest Path", "Community", "PageRank"], key="second")
<<<<<<< HEAD
    config = Config(height=500, width=700, nodeHighlightBehavior=True,
                    highlightColor="#F7A7A6", directed=True, collapsible=True)
=======
    config = Config(height=500,
                    width=700,
                    nodeHighlightBehavior=True,
                    highlightColor="#F7A7A6",
                    directed=True,
                    collapsible=True,
                    link={'labelProperty': 'label', 'renderLabel': True}
                    )
>>>>>>> 6f6a9624da414e66674de21213f6c8f387db8519
    if algo_type == "Shortest Path":
      if chosen_person_a != "" and chosen_person_b != "" and chosen_person_a != chosen_person_b:
        analysis_results = algos.shortest_path(chosen_person_a, chosen_person_b)
        sp_store = TripleStore()
        if len(analysis_results) > 0:
Exemplo n.º 11
0
                                        'circo', 
                                        'fdp', 
                                        'sfdp'])

rankdir = st.sidebar.selectbox("rankdir", ['BT', 'TB', 'LR', 'RL'])
ranksep = st.sidebar.slider("ranksep",min_value=0, max_value=10)
nodesep = st.sidebar.slider("nodesep",min_value=0, max_value=10)

config = Config(width=2000, 
                height=1000,
                graphviz_layout=layout,
                graphviz_config={"rankdir": rankdir, "ranksep": ranksep, "nodesep": nodesep},
                directed=True,
                nodeHighlightBehavior=True, 
                highlightColor="#F7A7A6",
                collapsible=True,
                node={'labelProperty':'label'},
                link={'labelProperty': 'label', 'renderLabel': True},
                maxZoom=2,
                minZoom=0.1,
                staticGraphWithDragAndDrop=False,
                staticGraph=False,
                initialZoom=1
                ) 


return_value = agraph(nodes=nodes, 
                      edges=edges, 
                      config=config)

Exemplo n.º 12
0
def main():
    """Semi Automated ML App with Streamlit """
    activities = ["Matrics Monitored", "Data Visualization"]

    choice = st.sidebar.selectbox("Select Activities", activities)

    if choice == 'Matrics Monitored':

        st.title("Social Media Computing Assignment")

        df = pd.read_csv('audience_size.csv')
        # df
        fig = px.bar(df,
                     x="company",
                     y="count",
                     color="type",
                     title="Audience Size")
        st.plotly_chart(fig)

    if choice == 'Data Visualization':

        activities = [
            "Audience Country Spread", "Campaign Categories",
            "Favourite And Retweet Count", "Frequency Tweets", "Word Map",
            "Network Graph"
        ]
        choice = st.sidebar.selectbox("Select Activities", activities)

        if choice == 'Audience Country Spread':
            st.title("Audience Country Spread")
            brand = ["Omega", "Rolex", "Daniel Wellington", "SwatchUS"]
            brand_choice = st.sidebar.selectbox("Select Brand", brand)
            if brand_choice == 'Omega':

                omega_loc = pd.read_csv('omega_loc.csv')
                omega_country = px.bar(omega_loc,
                                       x='Followers(%)',
                                       y='Country',
                                       title='Omega - Audience country spread',
                                       text='Followers(%)',
                                       orientation='h')
                st.plotly_chart(omega_country)

            if brand_choice == 'Rolex':

                rolex_loc = pd.read_csv('rolex_loc.csv')
                rolex_country = px.bar(rolex_loc,
                                       x='Followers(%)',
                                       y='Country',
                                       title='Rolex - Audience country spread',
                                       text='Followers(%)',
                                       orientation='h')
                st.plotly_chart(rolex_country)

            if brand_choice == 'Daniel Wellington':

                DanielWellington_loc = pd.read_csv('itisdw_loc.csv')
                DanielWellington_country = px.bar(
                    DanielWellington_loc,
                    x='Followers(%)',
                    y='Country',
                    title='Daniel Wellington - Audience country spread',
                    text='Followers(%)',
                    orientation='h')
                st.plotly_chart(DanielWellington_country)

            if brand_choice == 'SwatchUS':

                swatch_loc = pd.read_csv('swatch_loc.csv')
                swatch_country = px.bar(
                    swatch_loc,
                    x='Followers(%)',
                    y='Country',
                    title='SwatchUS - Audience country spread',
                    text='Followers(%)',
                    orientation='h')
                st.plotly_chart(swatch_country)

        if choice == 'Campaign Categories':

            st.title("Campaign Categories")

            brand = ["Omega", "Rolex", "Daniel Wellington", "SwatchUS"]
            brand_choice = st.sidebar.selectbox("Select Brand", brand)
            if brand_choice == 'Omega':

                company = "omega"
                camp_eng = pd.read_csv('campaign_engagement.csv')
                camp_eng = camp_eng.query('company == @company')
                fig = px.bar(camp_eng,
                             x="campaign",
                             y="avg",
                             title="Average Campaign Engagement")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="count",
                             title="Total Tweeted Campaign")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="rate",
                             title="Total Campaign Engagement Rate")
                st.plotly_chart(fig)

            if brand_choice == 'Rolex':

                company = "rolex"
                camp_eng = pd.read_csv('campaign_engagement.csv')
                camp_eng = camp_eng.query('company == @company')
                fig = px.bar(camp_eng,
                             x="campaign",
                             y="avg",
                             title="Average Campaign Engagement")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="count",
                             title="Total Tweeted Campaign")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="rate",
                             title="Total Campaign Engagement Rate")
                st.plotly_chart(fig)

            if brand_choice == 'Daniel Wellington':

                company = "itisdw"
                camp_eng = pd.read_csv('campaign_engagement.csv')
                camp_eng = camp_eng.query('company == @company')
                fig = px.bar(camp_eng,
                             x="campaign",
                             y="avg",
                             title="Average Campaign Engagement")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="count",
                             title="Total Tweeted Campaign")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="rate",
                             title="Total Campaign Engagement Rate")
                st.plotly_chart(fig)

            if brand_choice == 'SwatchUS':

                company = "swatch"
                camp_eng = pd.read_csv('campaign_engagement.csv')
                camp_eng = camp_eng.query('company == @company')
                fig = px.bar(camp_eng,
                             x="campaign",
                             y="avg",
                             title="Average Campaign Engagement")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="count",
                             title="Total Tweeted Campaign")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="rate",
                             title="Total Campaign Engagement Rate")
                st.plotly_chart(fig)

        if choice == 'Favourite And Retweet Count':

            st.title("Favourite Count")

            omega_camp = pd.read_csv('omega_camp.csv')
            omega_camp = px.bar(omega_camp,
                                x='campaign',
                                y='likes_sum',
                                title='Omega Favourite Count')
            st.plotly_chart(omega_camp)

            rolex_camp = pd.read_csv('rolex_camp.csv')
            rolex_camp = px.bar(rolex_camp,
                                x='campaign',
                                y='likes_sum',
                                title='Rolex Favourite Count')
            st.plotly_chart(rolex_camp)

            itisdw_camp = pd.read_csv('itisdw_camp.csv')
            itisdw_camp = px.bar(itisdw_camp,
                                 x='campaign',
                                 y='likes_sum',
                                 title='Daniel Wellington Favourite Count')
            st.plotly_chart(itisdw_camp)

            swatch_camp = pd.read_csv('swatch_camp.csv')
            swatch_camp = px.bar(swatch_camp,
                                 x='campaign',
                                 y='likes_sum',
                                 title='SwatchUS Favourite Count')
            st.plotly_chart(swatch_camp)

            st.title("Retweet Count")

            omega_camp = pd.read_csv('omega_camp.csv')
            omega_camp = px.bar(omega_camp,
                                x='campaign',
                                y='retweet_sum',
                                title='Omega Retweet Count')
            st.plotly_chart(omega_camp)

            rolex_camp = pd.read_csv('rolex_camp.csv')
            rolex_camp = px.bar(rolex_camp,
                                x='campaign',
                                y='retweet_sum',
                                title='Rolex Retweet Count')
            st.plotly_chart(rolex_camp)

            itisdw_camp = pd.read_csv('itisdw_camp.csv')
            itisdw_camp = px.bar(itisdw_camp,
                                 x='campaign',
                                 y='retweet_sum',
                                 title='Daniel Wellington Retweet Count')
            st.plotly_chart(itisdw_camp)

            swatch_camp = pd.read_csv('swatch_camp.csv')
            swatch_camp = px.bar(swatch_camp,
                                 x='campaign',
                                 y='retweet_sum',
                                 title='SwatchUS Retweet Count')
            st.plotly_chart(swatch_camp)

        if choice == 'Frequency Tweets':

            st.title("Frequency Tweet")

            brand = ["All", "Omega", "Rolex", "Daniel Wellington", "SwatchUS"]
            brand_choice = st.sidebar.selectbox("Select Brand", brand)

            if brand_choice == 'Omega':

                company = "omega"
                tweet_freq = pd.read_csv('tweet_freq.csv')
                tweet_freq = tweet_freq.query('company == @company')
                fig = px.line(tweet_freq,
                              x="week",
                              y="count",
                              title="Tweet Frequency")
                st.plotly_chart(fig)

                company = "omega"
                eng_freq = pd.read_csv('engagement_rate.csv')
                eng_freq = eng_freq.query('company == @company')
                fig = px.line(eng_freq,
                              x="week",
                              y="count",
                              title="Engagement rate")
                st.plotly_chart(fig)

            if brand_choice == 'Rolex':

                company = "rolex"
                tweet_freq = pd.read_csv('tweet_freq.csv')
                tweet_freq = tweet_freq.query('company == @company')
                fig = px.line(tweet_freq,
                              x="week",
                              y="count",
                              title="Tweet Frequency")
                st.plotly_chart(fig)

                company = "rolex"
                eng_freq = pd.read_csv('engagement_rate.csv')
                eng_freq = eng_freq.query('company == @company')
                fig = px.line(eng_freq,
                              x="week",
                              y="count",
                              title="Engagement rate")
                st.plotly_chart(fig)

            if brand_choice == 'Daniel Wellington':

                company = "itisdw"
                tweet_freq = pd.read_csv('tweet_freq.csv')
                tweet_freq = tweet_freq.query('company == @company')
                fig = px.line(tweet_freq,
                              x="week",
                              y="count",
                              title="Tweet Frequency")
                st.plotly_chart(fig)

                company = "itisdw"
                eng_freq = pd.read_csv('engagement_rate.csv')
                eng_freq = eng_freq.query('company == @company')
                fig = px.line(eng_freq,
                              x="week",
                              y="count",
                              title="Engagement rate")
                st.plotly_chart(fig)

            if brand_choice == 'SwatchUS':

                company = "swatch"
                tweet_freq = pd.read_csv('tweet_freq.csv')
                tweet_freq = tweet_freq.query('company == @company')
                fig = px.line(tweet_freq,
                              x="week",
                              y="count",
                              title="Tweet Frequency")
                st.plotly_chart(fig)

                company = "swatch"
                eng_freq = pd.read_csv('engagement_rate.csv')
                eng_freq = eng_freq.query('company == @company')
                fig = px.line(eng_freq,
                              x="week",
                              y="count",
                              title="Engagement rate")
                st.plotly_chart(fig)

            if brand_choice == 'All':
                tweet_freq = pd.read_csv('tweet_freq.csv')
                fig = px.line(tweet_freq,
                              x="week",
                              y="count",
                              color='company',
                              title="Tweet Frequency")
                st.plotly_chart(fig)

                eng_freq = pd.read_csv('engagement_rate.csv')
                fig = px.line(eng_freq,
                              x="week",
                              y="count",
                              color='company',
                              title="Engagement rate")
                st.plotly_chart(fig)

        if choice == 'Word Map':

            image_mask = np.array(Image.open("watch.jpg"))
            word_cloud = pd.read_csv('word_cloud.csv')

            st.title("Word Map")
            brand = ["Omega", "Rolex", "Daniel Wellington", "SwatchUS"]
            brand_choice = st.sidebar.selectbox("Select Brand", brand)

            word = word_cloud.query('(company == @brand_choice)')
            camp = word.campaign.to_numpy()

            if brand_choice == 'Omega':

                camp = [
                    'all', 'DeVille', 'ValentinesDay',
                    'OMEGAOfficialTimekeeper'
                ]
                camp_choice = st.sidebar.selectbox("Select Brand", camp)

                company = 'omega'
                campaign = "all"
                word = word_cloud.query(
                    '(company == @company) & (campaign == @camp_choice)'
                )['word'].values[0]

                # generate word cloud
                wc = WordCloud(background_color="white",
                               max_words=2000,
                               mask=image_mask)
                wc.generate(word)

                # plot the word cloud
                plt.figure(figsize=(8, 6), dpi=120)
                plt.imshow(wc, interpolation='bilinear')
                plt.axis("off")
                st.pyplot()

            if brand_choice == 'Rolex':

                camp = ['all', 'perpetual', 'reloxfamily']
                camp_choice = st.sidebar.selectbox("Select Brand", camp)

                company = 'rolex'
                campaign = "all"
                word = word_cloud.query(
                    '(company == @company) & (campaign == @camp_choice)'
                )['word'].values[0]

                # generate word cloud
                wc = WordCloud(background_color="white",
                               max_words=2000,
                               mask=image_mask)
                wc.generate(word)

                # plot the word cloud
                plt.figure(figsize=(8, 6), dpi=120)
                plt.imshow(wc, interpolation='bilinear')
                plt.axis("off")
                st.pyplot()

            if brand_choice == 'Daniel Wellington':

                camp = ['all', 'dwgiftsoflove', 'danielwellington', 'layzhang']
                camp_choice = st.sidebar.selectbox("Select Brand", camp)

                company = 'itisdw'
                campaign = "all"
                word = word_cloud.query(
                    '(company == @company) & (campaign == @camp_choice)'
                )['word'].values[0]

                # generate word cloud
                wc = WordCloud(background_color="white",
                               max_words=2000,
                               mask=image_mask)
                wc.generate(word)

                # plot the word cloud
                plt.figure(figsize=(8, 6), dpi=120)
                plt.imshow(wc, interpolation='bilinear')
                plt.axis("off")
                st.pyplot()

            if brand_choice == 'SwatchUS':

                camp = [
                    'all', 'timeiswhatyoumakeofit', 'swatchwithlove',
                    'swatchmytime'
                ]
                camp_choice = st.sidebar.selectbox("Select Brand", camp)

                company = 'swatch'
                campaign = "all"
                word = word_cloud.query(
                    '(company == @company) & (campaign == @camp_choice)'
                )['word'].values[0]

                # generate word cloud
                wc = WordCloud(background_color="white",
                               max_words=2000,
                               mask=image_mask)
                wc.generate(word)

                # plot the word cloud
                plt.figure(figsize=(8, 6), dpi=120)
                plt.imshow(wc, interpolation='bilinear')
                plt.axis("off")
                st.pyplot()

        if choice == 'Network Graph':

            st.title("Network Graph")

            brand = ["Omega", "Rolex", "Daniel Wellington", "SwatchUS"]
            brand_choice = st.sidebar.selectbox("Select Brand", brand)
            if brand_choice == 'Omega':

                st.title("Graph Example")
                config = Config(height=500,
                                width=700,
                                nodeHighlightBehavior=True,
                                highlightColor="#F7A7A6",
                                directed=True,
                                collapsible=True)
                if query_type == "Inspirationals":
                    st.subheader("Inspirationals")
                    with st.spinner("Loading data"):
                        store = get_inspired()
                        st.write(len(store.getNodes()))
                    st.success("Done")
                    agraph(list(store.getNodes()), (store.getEdges()), config)

            if brand_choice == 'Rolex':

                company = "rolex"
                camp_eng = pd.read_csv('campaign_engagement.csv')
                camp_eng = camp_eng.query('company == @company')
                fig = px.bar(camp_eng,
                             x="campaign",
                             y="avg",
                             title="Average Campaign Engagement")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="count",
                             title="Total Tweeted Campaign")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="rate",
                             title="Total Campaign Engagement Rate")
                st.plotly_chart(fig)

            if brand_choice == 'Daniel Wellington':

                company = "itisdw"
                camp_eng = pd.read_csv('campaign_engagement.csv')
                camp_eng = camp_eng.query('company == @company')
                fig = px.bar(camp_eng,
                             x="campaign",
                             y="avg",
                             title="Average Campaign Engagement")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="count",
                             title="Total Tweeted Campaign")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="rate",
                             title="Total Campaign Engagement Rate")
                st.plotly_chart(fig)

            if brand_choice == 'SwatchUS':

                company = "swatch"
                camp_eng = pd.read_csv('campaign_engagement.csv')
                camp_eng = camp_eng.query('company == @company')
                fig = px.bar(camp_eng,
                             x="campaign",
                             y="avg",
                             title="Average Campaign Engagement")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="count",
                             title="Total Tweeted Campaign")
                st.plotly_chart(fig)

                fig = px.bar(camp_eng,
                             x="campaign",
                             y="rate",
                             title="Total Campaign Engagement Rate")
                st.plotly_chart(fig)
Exemplo n.º 13
0
def app():

    # Set title and user input elements
    st.title("Recipe Recommender Network")
    sidebar = st.sidebar
    middle, rsidebar = st.beta_columns([3, 1])
    sidebar.title("Choose meal type and ingredients")
    userIngredients = sidebar.text_input(
        "Input ingredients that should be included in returned recipes:")
    userInput = sidebar.text_input("Input recipe to use as cluster seed: ")

    # create empty lists for holding nodes and edges for network
    #net = Network() # place holder for transitioning to pyvis
    nodes = []
    edges = []
    nodeSize = 500

    # Bring in the initial data
    tmp = pd.read_csv(
        r'C:\Users\jdnun\OneDrive\Documents\GT\Spring2021\Project\code\cse6242_project-main\src\cluster_test.csv'
    )  # Here is where we would access the data from the backend
    print('length before filter: ', len(tmp))

    # filter data for only recipes that contain the user inputs
    if userIngredients != "":
        ingredients = userIngredients.split(',')
        ingredients = [i.strip() for i in ingredients]
        contains = [
            tmp["RecipeIngredientParts"].str.contains(i) for i in ingredients
        ]
        #print(ingredients)
        tmp = tmp[np.all(contains, axis=0)]
        print('length of filtered: ', len(tmp))

    if len(tmp) != 0:
        edgeList = []

        ### Used for loading the data directly from the dictionary output from Orion's clustering script
        # for i in range(0, len(tmp["c1"]["nodes"])):
        #     nodes.extend([Node(id=int(tmp["c1"]["nodes"].iloc[i]['RecipeId']), label=tmp["c1"]["nodes"].iloc[i]["Name"],
        #                        size=nodeSize)])
        #     for j in range(0, len(tmp["c1"]["nodes"])):
        #         if tmp["c1"]["nodes"].iloc[i]['RecipeId'] != tmp["c1"]["nodes"].iloc[j]['RecipeId'] and int(tmp["c1"]["nodes"].iloc[i]["Ingredient Difference"]) == int(tmp["c1"]["nodes"].iloc[j]["Ingredient Difference"]) \
        #                 and [int(tmp["c1"]["nodes"].iloc[j]['RecipeId']),int(tmp["c1"]["nodes"].iloc[i]['RecipeId'])] not in edgeList:
        #             edgeList.append([int(tmp["c1"]["nodes"].iloc[i]['RecipeId']),int(tmp["c1"]["nodes"].iloc[j]['RecipeId'])])
        #             edges.extend([Edge(source=int(tmp["c1"]["nodes"].iloc[i]['RecipeId']), label=int(tmp["c1"]["nodes"].iloc[j]["Ingredient Difference"]),
        #                                target=int(tmp["c1"]["nodes"].iloc[j]["RecipeId"]), type="CURVE_SMOOTH")])
        for i in range(0, len(tmp["nodes"])):
            nodes.extend([
                Node(id=int(tmp.iloc[i]['RecipeId']),
                     label=tmp.iloc[i]["Name"],
                     size=nodeSize)
            ])
            #net.add_node(n_id=int(tmp.iloc[i]['RecipeId']), value=nodeSize, label=tmp.iloc[i]["Name"]) # place holder for transitioning to pyvis
            for j in range(0, len(tmp["nodes"])):
                if tmp.iloc[i]['RecipeId'] != tmp.iloc[j]['RecipeId'] and int(tmp.iloc[i]["Ingredient Difference"]) == int(tmp.iloc[j]["Ingredient Difference"]) \
                        and [int(tmp.iloc[j]['RecipeId']),int(tmp.iloc[i]['RecipeId'])] not in edgeList:
                    edgeList.append([
                        int(tmp.iloc[i]['RecipeId']),
                        int(tmp.iloc[j]['RecipeId'])
                    ])
                    edges.extend([
                        Edge(source=int(tmp.iloc[i]['RecipeId']),
                             label=int(tmp.iloc[j]["Ingredient Difference"]),
                             target=int(tmp.iloc[j]["RecipeId"]),
                             type="CURVE_SMOOTH")
                    ])
                    #net.add_edge(int(tmp.iloc[i]['RecipeId']),int(tmp.iloc[j]["RecipeId"]),title=int(tmp.iloc[j]["Ingredient Difference"])) # # place holder for transitioning to pyvis

        # diffList = [str(i) for i in set(tmp["c1"]["nodes"]["Ingredient Difference"])]
        # diffList.append('All')
        # diffList.sort(reverse=True)
        # display_category = sidebar.selectbox("Ingredient difference: ",index=0, options = diffList) # could add more stuff here later on or add other endpoints in the sidebar.
        # if display_category == "all":
        viewEdges = edges
        # else:
        #     viewEdges = [edge for edge in edges if edge.label == display_category]
        #mealType = sidebar.selectbox("Meal Type: ", index=0, options = ["Breakfast", "Lunch", "Dinner"]) # Just a place holder could be 'soup', 'salad', or 'italian', 'indian', etc

        # set network configuration
        config = Config(height=500,
                        width=700,
                        nodeHighlightBehavior=True,
                        highlightColor="#F7A7A6",
                        directed=False,
                        collapsible=True,
                        node={'labelProperty': 'label'},
                        link={
                            'labelProperty': 'label',
                            'renderLabel': False
                        })
        # add network to middle column of streamlit canvas
        with middle:
            #st.text("Displaying {} cuisine types".format(display_category))
            return_value = agraph(nodes=nodes, edges=viewEdges, config=config)
            #net.show('testgraph.html') # place holder for transitioning to pyvis

    st.text("Showing recipes based on the following ingredients: {}".format(
        userIngredients))
Exemplo n.º 14
0
    print(temp_data["@@edgeSet"][0])

    nodes = []
    edges = []
    for val in temp_data["@@edgeSet"]:
        nodes.append(Node(id=val['from_id']))
        nodes.append(Node(id=val['to_id']))
        edges.append(
            Edge(source=val['from_id'],
                 target=val['to_id'],
                 labelProperty=val['e_type'],
                 renderLabel=True))

    config = Config(height=500,
                    width=700,
                    nodeHighlightBehavior=True,
                    highlightColor="#F7A7A6",
                    directed=True,
                    collapsible=True)

    agraph(nodes, edges, config)

elif itemSelected == 'Automatic Data Analysis':
    st.title('Automatic Data Analysis')

    data = st.file_uploader("Upload a Dataset", type=["csv"])
    if data is not None:
        df = pd.read_csv(data)
        st.dataframe(df)

        if st.checkbox("Show Shape"):
            st.write(df.shape)