import streamlit as st from dotenv import load_dotenv import requests from bs4 import BeautifulSoup import openai import os load_dotenv() def create_article(length_option, articles, params): article_string = "; ".join(f"Artikel {index + 1}: {artikel}" for index, artikel in enumerate(articles)) if length_option == "Short": length = 3 elif length_option == "Middle": length = 6 elif length_option == "Long": length = 9 openai.api_key = os.environ.get("OPEN_API_KEY") openai.api_base = os.environ.get("OPEN_API_BASE") openai.api_type = os.environ.get("OPEN_API_TYPE") openai.api_version = os.environ.get("OPEN_API_VERSION") writing_style = "You write in a boulevard style, explaining and characterizing events for your readers. You use expressive verbs, sometimes onomapoetic in nature. You use adjectives liberally, both to guide your readers, and to create a narrative flow. You favor short and uncomplicated sentences, rarely utilizing subordinate clauses, to reduce reading difficulty and to keep your articles concise and to the point." try: res = openai.ChatCompletion.create( engine="gpt-4-1106", temperature=0.4, messages=[ { "role": "system", "content": f"You are a professional journalist whose task is to write your own article based on one or more articles. This article should combine the content of the original articles, but have its own writing style, which is as follows: {writing_style} The length of your article should be {length} sentences long.", }, { "role": "system", "content": f"Source articles: {article_string}" }, { "role": "system", "content": f"Please also note the following instructions defined by the user: {params}" } ], ) return res["choices"][0]["message"]["content"] except Exception as e: print(f"Fehler beim erstellen des artikels: {str(e)}") st.error(f"Something went wrong: {str(e)}", icon="🚨") def extract_article(url): # Webseite herunterladen response = requests.get(url) # Überprüfen, ob die Anfrage erfolgreich war (Status-Code 200) if response.status_code == 200: # HTML-Inhalt parsen soup = BeautifulSoup(response.text, 'html.parser') # Alle

-Tags finden und den Textinhalt extrahieren paragraphs = soup.find_all('p') # Textinhalt der

-Tags zusammenführen text_content = '\n'.join([p.get_text() for p in paragraphs]) return text_content else: # Falls die Anfrage nicht erfolgreich war, eine Fehlermeldung ausgeben print(f"Fehler: {response.status_code}") return None def extract_article_links(**kwargs): # print(len(kwargs["links"])) with st.spinner("Extracting..."): results = [] for link in kwargs["links"]: results.append(extract_article(link)) st.session_state["extracted_articles"] = results def finalize_articles(): final_articles = [] for i in range(len(st.session_state["extracted_articles"])): final_articles.append(st.session_state["final_article_"+str(i+1)]) st.session_state["final_articles"] = final_articles if "extracted_articles" not in st.session_state: st.session_state["extracted_articles"] = [] if "article_links" not in st.session_state: st.session_state["article_links"] = [] if "final_articles" not in st.session_state: st.session_state["final_articles"] = [] def check_password(): """Returns `True` if the user had the correct password.""" def password_entered(): """Checks whether a password entered by the user is correct.""" if hmac.compare_digest(st.session_state["password"], os.environ.get("PASSWORD")): st.session_state["password_correct"] = True del st.session_state["password"] # Don't store the password. else: st.session_state["password_correct"] = False # Return True if the password is validated. if st.session_state.get("password_correct", False): return True # Show input for password. st.text_input( "Password", type="password", on_change=password_entered, key="password" ) if "password_correct" in st.session_state: st.error("😕 Password incorrect") return False if not check_password(): st.stop() # Do not continue if check_password is not True. col1, col2 = st.columns([2, 1]) col1.title("AI journalist") col2.image("tensora_logo.png") if len(st.session_state["final_articles"]) < 1: if len(st.session_state["extracted_articles"]) < 1: st.write("Please enter the links of the articles to use them for the summary. ") st.text_input("Please enter the "+str(len(st.session_state["article_links"])+1)+". link:",key="link_input_"+str(len(st.session_state["article_links"])+1)) if st.session_state["link_input_"+str(len(st.session_state["article_links"])+1)]: st.session_state["article_links"].append(st.session_state["link_input_"+str(len(st.session_state["article_links"])+1)]) st.rerun() for i in range(len(st.session_state["article_links"])): st.write(f"Link nr. {i+1}:\n\n{st.session_state['article_links'][0]}") if(len(st.session_state["article_links"])>0): st.button("Extract articles",on_click=extract_article_links,kwargs={"links":st.session_state["article_links"]}) else: st.write("Here you can view the extracted articles and edit them if necessary") for i,article in enumerate(st.session_state["extracted_articles"]): with st.expander(f"Article {i+1}"): if article: st.text_area("Edit the article if needed:", value=article, key="final_article_"+str(i+1), height=500) else: st.info("The website on which the article is published blocks the automatic extraction of its content. If you still want to use the article, you will have to insert the text manually.", icon="ℹ️") st.text_area("Paste the article if needed:", value=article, key="final_article_"+str(i+1), height=500) st.button("Finalize articles",on_click=finalize_articles) for i in range(len(st.session_state["final_articles"])): if st.session_state["final_articles"][i]: with st.expander("Article "+ str(i+1)): st.write(st.session_state["final_articles"][i]) if len(st.session_state["final_articles"]) > 0: st.text_area("Add additional information for the prompt if needed:",key="add_info") st.write("Article length") st.radio("Length options",["Short", "Middle", "Long"], key="length_option") if st.button("Create article", key="article_btn"): with st.spinner("Creating the article..."): created_article = create_article(st.session_state["length_option"],st.session_state["final_articles"],st.session_state["add_info"]) st.write(created_article)