v1.3.7: Vollständige Version inkl. aller Funktionen, Modus 4: Nur Wikipedia-Suche
- Alle bisherigen Funktionen aus v1.3.6 bleiben erhalten - Neuer Modus 4 wurde implementiert, der ausschließlich Wikipedia-Suchen durchführt ohne ChatGPT-Anfragen - Modus 5 ermöglicht die LinkedIn-Kontaktsuche via SerpApi - Debug-Ausgaben wurden in allen Funktionen verbessert, sodass der Ablauf und die Ergebnisse besser nachvollzogen werden können - Der Startindex wird anhand des letzten Timestamps in Spalte AH korrekt ermittelt, sodass bestehende Datensätze nicht überschrieben werden
This commit is contained in:
@@ -14,7 +14,7 @@ import csv
|
||||
|
||||
# ==================== KONFIGURATION ====================
|
||||
class Config:
|
||||
VERSION = "v1.3.7" # v1.3.7: Neuer Modus 4: Nur Wikipedia-Suche, keine ChatGPT-Anfragen.
|
||||
VERSION = "v1.3.7" # v1.3.7: Alle bisherigen Funktionen beibehalten, neuer Modus 4: Nur Wikipedia-Suche.
|
||||
LANG = "de"
|
||||
CREDENTIALS_FILE = "service_account.json"
|
||||
SHEET_URL = "https://docs.google.com/spreadsheets/d/1u_gHr9JUfmV1-iviRzbSe3575QEp7KLhK5jFV_gJcgo"
|
||||
@@ -134,189 +134,337 @@ def compare_umsatz_values(crm, wiki):
|
||||
diff_mio = abs(crm_val - wiki_val)
|
||||
return f"Abweichung: {int(round(diff_mio))} Mio €"
|
||||
|
||||
# ==================== WIKIPEDIA SCRAPER ====================
|
||||
class WikipediaScraper:
|
||||
def __init__(self):
|
||||
wikipedia.set_lang(Config.LANG)
|
||||
def _get_full_domain(self, website):
|
||||
if not website:
|
||||
return ""
|
||||
website = website.lower().strip()
|
||||
website = re.sub(r'^https?:\/\/', '', website)
|
||||
website = re.sub(r'^www\.', '', website)
|
||||
return website.split('/')[0]
|
||||
def _generate_search_terms(self, company_name, website):
|
||||
terms = []
|
||||
full_domain = self._get_full_domain(website)
|
||||
if full_domain:
|
||||
terms.append(full_domain)
|
||||
normalized_name = normalize_company_name(company_name)
|
||||
candidate = " ".join(normalized_name.split()[:2]).strip()
|
||||
if candidate and candidate not in terms:
|
||||
terms.append(candidate)
|
||||
if normalized_name and normalized_name not in terms:
|
||||
terms.append(normalized_name)
|
||||
debug_print(f"Generierte Suchbegriffe: {terms}")
|
||||
return terms
|
||||
def _validate_article(self, page, company_name, website):
|
||||
full_domain = self._get_full_domain(website)
|
||||
domain_found = False
|
||||
if full_domain:
|
||||
try:
|
||||
html_raw = requests.get(page.url).text
|
||||
soup = BeautifulSoup(html_raw, Config.HTML_PARSER)
|
||||
infobox = soup.find('table', class_=lambda c: c and 'infobox' in c.lower())
|
||||
if infobox:
|
||||
links = infobox.find_all('a', href=True)
|
||||
for link in links:
|
||||
href = link.get('href').lower()
|
||||
if href.startswith('/wiki/datei:'):
|
||||
continue
|
||||
if full_domain in href:
|
||||
debug_print(f"Definitiver Link-Match in Infobox gefunden: {href}")
|
||||
domain_found = True
|
||||
break
|
||||
if not domain_found and hasattr(page, 'externallinks'):
|
||||
for ext_link in page.externallinks:
|
||||
if full_domain in ext_link.lower():
|
||||
debug_print(f"Definitiver Link-Match in externen Links gefunden: {ext_link}")
|
||||
domain_found = True
|
||||
break
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Extrahieren von Links: {str(e)}")
|
||||
normalized_title = normalize_company_name(page.title)
|
||||
normalized_company = normalize_company_name(company_name)
|
||||
similarity = SequenceMatcher(None, normalized_title, normalized_company).ratio()
|
||||
debug_print(f"Ähnlichkeit (normalisiert): {similarity:.2f} ({normalized_title} vs {normalized_company})")
|
||||
threshold = 0.60 if domain_found else Config.SIMILARITY_THRESHOLD
|
||||
return similarity >= threshold
|
||||
def extract_first_paragraph(self, page_url):
|
||||
def evaluate_umsatz_chatgpt(company_name, wiki_umsatz):
|
||||
try:
|
||||
with open("api_key.txt", "r") as f:
|
||||
api_key = f.read().strip()
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Lesen des API-Tokens: {e}")
|
||||
return "k.A."
|
||||
openai.api_key = api_key
|
||||
prompt = (
|
||||
f"Bitte schätze den Umsatz in Mio. Euro für das Unternehmen '{company_name}'. "
|
||||
f"Die Wikipedia-Daten zeigen: '{wiki_umsatz}'. "
|
||||
"Antworte nur mit der Zahl."
|
||||
)
|
||||
try:
|
||||
response = openai.ChatCompletion.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
temperature=0.0
|
||||
)
|
||||
result = response.choices[0].message.content.strip()
|
||||
debug_print(f"ChatGPT Umsatzschätzung: '{result}'")
|
||||
try:
|
||||
response = requests.get(page_url)
|
||||
soup = BeautifulSoup(response.text, Config.HTML_PARSER)
|
||||
paragraphs = soup.find_all('p')
|
||||
for p in paragraphs:
|
||||
text = clean_text(p.get_text())
|
||||
if len(text) > 50:
|
||||
return text
|
||||
return "k.A."
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Extrahieren des ersten Absatzes: {e}")
|
||||
return "k.A."
|
||||
def extract_categories(self, soup):
|
||||
cat_div = soup.find('div', id="mw-normal-catlinks")
|
||||
if cat_div:
|
||||
ul = cat_div.find('ul')
|
||||
if ul:
|
||||
cats = [clean_text(li.get_text()) for li in ul.find_all('li')]
|
||||
return ", ".join(cats)
|
||||
value = float(result.replace(',', '.'))
|
||||
return str(int(round(value)))
|
||||
except Exception as conv_e:
|
||||
debug_print(f"Fehler bei der Verarbeitung der Umsatzschätzung '{result}': {conv_e}")
|
||||
return result
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Aufruf der ChatGPT API für Umsatzschätzung: {e}")
|
||||
return "k.A."
|
||||
def _extract_infobox_value(self, soup, target):
|
||||
infobox = soup.find('table', class_=lambda c: c and any(kw in c.lower() for kw in ['infobox', 'vcard', 'unternehmen']))
|
||||
if not infobox:
|
||||
return "k.A."
|
||||
keywords_map = {
|
||||
'branche': ['branche', 'industrie', 'tätigkeit', 'geschäftsfeld', 'sektor', 'produkte', 'leistungen', 'aktivitäten', 'wirtschaftszweig'],
|
||||
'umsatz': ['umsatz', 'jahresumsatz', 'konzernumsatz', 'gesamtumsatz', 'erlöse', 'umsatzerlöse', 'einnahmen', 'ergebnis', 'jahresergebnis'],
|
||||
'mitarbeiter': ['mitarbeiter', 'beschäftigte', 'personal', 'mitarbeiterzahl', 'angestellte', 'belegschaft', 'personalstärke']
|
||||
}
|
||||
keywords = keywords_map.get(target, [])
|
||||
for row in infobox.find_all('tr'):
|
||||
header = row.find('th')
|
||||
if header:
|
||||
header_text = clean_text(header.get_text()).lower()
|
||||
if any(kw in header_text for kw in keywords):
|
||||
value = row.find('td')
|
||||
if value:
|
||||
raw_value = clean_text(value.get_text())
|
||||
if target == 'branche':
|
||||
clean_val = re.sub(r'\[.*?\]|\(.*?\)', '', raw_value)
|
||||
return ' '.join(clean_val.split()).strip()
|
||||
if target == 'umsatz':
|
||||
return extract_numeric_value(raw_value, is_umsatz=True)
|
||||
if target == 'mitarbeiter':
|
||||
return extract_numeric_value(raw_value, is_umsatz=False)
|
||||
|
||||
def validate_article_with_chatgpt(crm_data, wiki_data):
|
||||
crm_headers = "Firmenname;Website;Ort;Beschreibung;Aktuelle Branche;Beschreibung Branche extern;Anzahl Techniker;Umsatz (CRM);Anzahl Mitarbeiter (CRM)"
|
||||
wiki_headers = "Wikipedia URL;Wikipedia Absatz;Wikipedia Branche;Wikipedia Umsatz;Wikipedia Mitarbeiter;Wikipedia Kategorien"
|
||||
prompt_text = (
|
||||
"Bitte überprüfe, ob die folgenden beiden Datensätze grundsätzlich zum gleichen Unternehmen gehören. "
|
||||
"Berücksichtige dabei, dass leichte Abweichungen in Firmennamen (z. B. unterschiedliche Schreibweisen, Mutter-Tochter-Beziehungen) "
|
||||
"oder im Ort (z. B. 'Oberndorf' vs. 'Oberndorf/Neckar') tolerierbar sind. "
|
||||
"Vergleiche insbesondere den Firmennamen, den Ort und die Branche. Unterschiede im Umsatz können bis zu 10% abweichen. "
|
||||
"Wenn die Daten im Wesentlichen übereinstimmen, antworte ausschließlich mit 'OK'. "
|
||||
"Falls nicht, nenne bitte den wichtigsten Grund und eine kurze Begründung, warum die Abweichung plausibel sein könnte.\n\n"
|
||||
f"CRM-Daten:\n{crm_headers}\n{crm_data}\n\n"
|
||||
f"Wikipedia-Daten:\n{wiki_headers}\n{wiki_data}\n\n"
|
||||
"Antwort: "
|
||||
)
|
||||
try:
|
||||
with open("api_key.txt", "r") as f:
|
||||
api_key = f.read().strip()
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Lesen des API-Tokens: {e}")
|
||||
return "k.A."
|
||||
def extract_full_infobox(self, soup):
|
||||
infobox = soup.find('table', class_=lambda c: c and any(kw in c.lower() for kw in ['infobox', 'vcard', 'unternehmen']))
|
||||
if not infobox:
|
||||
return "k.A."
|
||||
return clean_text(infobox.get_text(separator=' | '))
|
||||
def extract_fields_from_infobox_text(self, infobox_text, field_names):
|
||||
result = {}
|
||||
tokens = [token.strip() for token in infobox_text.split("|") if token.strip()]
|
||||
for i, token in enumerate(tokens):
|
||||
for field in field_names:
|
||||
if field.lower() in token.lower():
|
||||
j = i + 1
|
||||
while j < len(tokens) and not tokens[j]:
|
||||
j += 1
|
||||
result[field] = tokens[j] if j < len(tokens) else "k.A."
|
||||
openai.api_key = api_key
|
||||
try:
|
||||
response = openai.ChatCompletion.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[{"role": "system", "content": prompt_text}],
|
||||
temperature=0.0
|
||||
)
|
||||
result = response.choices[0].message.content.strip()
|
||||
debug_print(f"Validierungsantwort ChatGPT: '{result}'")
|
||||
return result
|
||||
def extract_company_data(self, page_url):
|
||||
if not page_url:
|
||||
return {
|
||||
'url': 'k.A.',
|
||||
'first_paragraph': 'k.A.',
|
||||
'branche': 'k.A.',
|
||||
'umsatz': 'k.A.',
|
||||
'mitarbeiter': 'k.A.',
|
||||
'categories': 'k.A.',
|
||||
'full_infobox': 'k.A.'
|
||||
}
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Validierungs-API-Aufruf: {e}")
|
||||
return "k.A."
|
||||
|
||||
def evaluate_fsm_suitability(company_name, company_data):
|
||||
try:
|
||||
with open("api_key.txt", "r") as f:
|
||||
api_key = f.read().strip()
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Lesen des API-Tokens (FSM): {e}")
|
||||
return {"suitability": "k.A.", "justification": "k.A."}
|
||||
openai.api_key = api_key
|
||||
prompt = (
|
||||
f"Bitte bewerte, ob das Unternehmen '{company_name}' für den Einsatz einer Field Service Management Lösung geeignet ist. "
|
||||
"Berücksichtige, dass ein Unternehmen mit einem technischen Außendienst, idealerweise mit über 50 Technikern und "
|
||||
"Disponenten, die mit der Planung mobiler Ressourcen beschäftigt sind, als geeignet gilt. Nutze dabei verifizierte "
|
||||
"Wikipedia-Daten und deine eigene Einschätzung. Antworte ausschließlich mit 'Ja' oder 'Nein' und gib eine kurze Begründung."
|
||||
)
|
||||
try:
|
||||
response = openai.ChatCompletion.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[{"role": "system", "content": prompt}],
|
||||
temperature=0.0
|
||||
)
|
||||
result = response.choices[0].message.content.strip()
|
||||
debug_print(f"FSM-Eignungsantwort ChatGPT: '{result}'")
|
||||
suitability = "k.A."
|
||||
justification = ""
|
||||
lines = result.split("\n")
|
||||
if len(lines) == 1:
|
||||
parts = result.split(" ", 1)
|
||||
suitability = parts[0].strip()
|
||||
justification = parts[1].strip() if len(parts) > 1 else ""
|
||||
else:
|
||||
for line in lines:
|
||||
if line.lower().startswith("eignung:"):
|
||||
suitability = line.split(":", 1)[1].strip()
|
||||
elif line.lower().startswith("begründung:"):
|
||||
justification = line.split(":", 1)[1].strip()
|
||||
if suitability not in ["Ja", "Nein"]:
|
||||
parts = result.split(" ", 1)
|
||||
suitability = parts[0].strip()
|
||||
justification = " ".join(result.split()[1:]).strip()
|
||||
return {"suitability": suitability, "justification": justification}
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Aufruf der ChatGPT API für FSM-Eignungsprüfung: {e}")
|
||||
return {"suitability": "k.A.", "justification": "k.A."}
|
||||
|
||||
def evaluate_servicetechnicians_estimate(company_name, company_data):
|
||||
try:
|
||||
with open("serpApiKey.txt", "r") as f:
|
||||
serp_key = f.read().strip()
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Lesen des SerpAPI-Schlüssels (Servicetechniker): {e}")
|
||||
return "k.A."
|
||||
try:
|
||||
with open("api_key.txt", "r") as f:
|
||||
api_key = f.read().strip()
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Lesen des API-Tokens (Servicetechniker): {e}")
|
||||
return "k.A."
|
||||
openai.api_key = api_key
|
||||
prompt = (
|
||||
f"Bitte schätze auf Basis öffentlich zugänglicher Informationen (vor allem verifizierte Wikipedia-Daten) "
|
||||
f"die Anzahl der Servicetechniker des Unternehmens '{company_name}' ein. "
|
||||
"Gib die Antwort ausschließlich in einer der folgenden Kategorien aus: "
|
||||
"'<50 Techniker', '>100 Techniker', '>200 Techniker', '>500 Techniker'."
|
||||
)
|
||||
try:
|
||||
response = openai.ChatCompletion.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[{"role": "system", "content": prompt}],
|
||||
temperature=0.0
|
||||
)
|
||||
result = response.choices[0].message.content.strip()
|
||||
debug_print(f"Schätzung Servicetechniker ChatGPT: '{result}'")
|
||||
return result
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Aufruf der ChatGPT API für Servicetechniker-Schätzung: {e}")
|
||||
return "k.A."
|
||||
|
||||
def evaluate_servicetechnicians_explanation(company_name, st_estimate, company_data):
|
||||
try:
|
||||
with open("api_key.txt", "r") as f:
|
||||
api_key = f.read().strip()
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Lesen des API-Tokens (ST-Erklärung): {e}")
|
||||
return "k.A."
|
||||
openai.api_key = api_key
|
||||
prompt = (
|
||||
f"Bitte erkläre, warum du für das Unternehmen '{company_name}' die Anzahl der Servicetechniker als '{st_estimate}' geschätzt hast. "
|
||||
"Berücksichtige dabei öffentlich zugängliche Informationen wie Branche, Umsatz, Mitarbeiterzahl und andere relevante Daten."
|
||||
)
|
||||
try:
|
||||
response = openai.ChatCompletion.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[{"role": "system", "content": prompt}],
|
||||
temperature=0.0
|
||||
)
|
||||
result = response.choices[0].message.content.strip()
|
||||
debug_print(f"Servicetechniker-Erklärung ChatGPT: '{result}'")
|
||||
return result
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler beim Aufruf der ChatGPT API für Servicetechniker-Erklärung: {e}")
|
||||
return "k.A."
|
||||
|
||||
def map_internal_technicians(value):
|
||||
try:
|
||||
num = int(value)
|
||||
except Exception:
|
||||
return "k.A."
|
||||
if num < 50:
|
||||
return "<50 Techniker"
|
||||
elif num < 100:
|
||||
return ">100 Techniker"
|
||||
elif num < 200:
|
||||
return ">200 Techniker"
|
||||
else:
|
||||
return ">500 Techniker"
|
||||
|
||||
def wait_for_sheet_update(sheet, cell, expected_value, timeout=5):
|
||||
start_time = time.time()
|
||||
while time.time() - start_time < timeout:
|
||||
try:
|
||||
response = requests.get(page_url)
|
||||
soup = BeautifulSoup(response.text, Config.HTML_PARSER)
|
||||
full_infobox = self.extract_full_infobox(soup)
|
||||
extracted_fields = self.extract_fields_from_infobox_text(full_infobox, ['Branche', 'Umsatz', 'Mitarbeiter'])
|
||||
raw_branche = extracted_fields.get('Branche', self._extract_infobox_value(soup, 'branche'))
|
||||
raw_umsatz = extracted_fields.get('Umsatz', self._extract_infobox_value(soup, 'umsatz'))
|
||||
raw_mitarbeiter = extracted_fields.get('Mitarbeiter', self._extract_infobox_value(soup, 'mitarbeiter'))
|
||||
umsatz_val = extract_numeric_value(raw_umsatz, is_umsatz=True)
|
||||
mitarbeiter_val = extract_numeric_value(raw_mitarbeiter, is_umsatz=False)
|
||||
categories_val = self.extract_categories(soup)
|
||||
first_paragraph = self.extract_first_paragraph(page_url)
|
||||
return {
|
||||
'url': page_url,
|
||||
'first_paragraph': first_paragraph,
|
||||
'branche': raw_branche,
|
||||
'umsatz': umsatz_val,
|
||||
'mitarbeiter': mitarbeiter_val,
|
||||
'categories': categories_val,
|
||||
'full_infobox': full_infobox
|
||||
}
|
||||
current_value = sheet.acell(cell).value
|
||||
if current_value == expected_value:
|
||||
return True
|
||||
except Exception as e:
|
||||
debug_print(f"Extraktionsfehler: {str(e)}")
|
||||
return {
|
||||
'url': 'k.A.',
|
||||
'first_paragraph': 'k.A.',
|
||||
'branche': 'k.A.',
|
||||
'umsatz': 'k.A.',
|
||||
'mitarbeiter': 'k.A.',
|
||||
'categories': 'k.A.',
|
||||
'full_infobox': 'k.A.'
|
||||
}
|
||||
@retry_on_failure
|
||||
def search_company_article(self, company_name, website):
|
||||
search_terms = self._generate_search_terms(company_name, website)
|
||||
for term in search_terms:
|
||||
try:
|
||||
results = wikipedia.search(term, results=Config.WIKIPEDIA_SEARCH_RESULTS)
|
||||
debug_print(f"Suchergebnisse für '{term}': {results}")
|
||||
for title in results:
|
||||
try:
|
||||
page = wikipedia.page(title, auto_suggest=False)
|
||||
if self._validate_article(page, company_name, website):
|
||||
return page
|
||||
except (wikipedia.exceptions.DisambiguationError, wikipedia.exceptions.PageError) as e:
|
||||
debug_print(f"Seitenfehler: {str(e)}")
|
||||
continue
|
||||
except Exception as e:
|
||||
debug_print(f"Suchfehler: {str(e)}")
|
||||
continue
|
||||
debug_print(f"Fehler beim Lesen von Zelle {cell}: {e}")
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
# ==================== NEUE FUNKTION: LINKEDIN-KONTAKT-SUCHE MIT SERPAPI ====================
|
||||
def search_linkedin_contact(company_name, website, position_query):
|
||||
try:
|
||||
with open("serpApiKey.txt", "r") as f:
|
||||
serp_key = f.read().strip()
|
||||
except Exception as e:
|
||||
debug_print("Fehler beim Lesen des SerpAPI-Schlüssels: " + str(e))
|
||||
return None
|
||||
query = f'site:linkedin.com/in "{position_query}" "{company_name}"'
|
||||
debug_print(f"Erstelle LinkedIn-Query: {query}")
|
||||
params = {
|
||||
"engine": "google",
|
||||
"q": query,
|
||||
"api_key": serp_key,
|
||||
"hl": "de"
|
||||
}
|
||||
try:
|
||||
response = requests.get("https://serpapi.com/search", params=params)
|
||||
data = response.json()
|
||||
debug_print(f"SerpAPI-Response für Query '{query}': {data.get('organic_results', [])[:1]}")
|
||||
if "organic_results" in data and len(data["organic_results"]) > 0:
|
||||
result = data["organic_results"][0]
|
||||
title = result.get("title", "")
|
||||
debug_print(f"LinkedIn-Suchergebnis-Titel: {title}")
|
||||
if "–" in title:
|
||||
parts = title.split("–")
|
||||
elif "-" in title:
|
||||
parts = title.split("-")
|
||||
else:
|
||||
parts = [title]
|
||||
if len(parts) >= 2:
|
||||
name_part = parts[0].strip()
|
||||
pos = parts[1].split("|")[0].strip()
|
||||
name_parts = name_part.split(" ", 1)
|
||||
if len(name_parts) == 2:
|
||||
firstname, lastname = name_parts
|
||||
else:
|
||||
firstname = name_part
|
||||
lastname = ""
|
||||
debug_print(f"Kontakt gefunden: {firstname} {lastname}, Position: {pos}")
|
||||
return {"Firmenname": company_name, "Website": website, "Vorname": firstname, "Nachname": lastname, "Position": pos}
|
||||
else:
|
||||
debug_print(f"Kontakt gefunden, aber unvollständige Informationen: {title}")
|
||||
return {"Firmenname": company_name, "Website": website, "Vorname": "", "Nachname": "", "Position": title}
|
||||
else:
|
||||
debug_print(f"Keine LinkedIn-Ergebnisse für Query: {query}")
|
||||
return None
|
||||
except Exception as e:
|
||||
debug_print(f"Fehler bei der SerpAPI-Suche: {e}")
|
||||
return None
|
||||
|
||||
# ==================== GOOGLE SHEET HANDLER (Hauptdaten) ====================
|
||||
def process_contacts():
|
||||
debug_print("Starte LinkedIn-Kontaktsuche...")
|
||||
gc = gspread.authorize(ServiceAccountCredentials.from_json_keyfile_name(
|
||||
Config.CREDENTIALS_FILE, ["https://www.googleapis.com/auth/spreadsheets"]))
|
||||
sh = gc.open_by_url(Config.SHEET_URL)
|
||||
try:
|
||||
contacts_sheet = sh.worksheet("Contacts")
|
||||
except gspread.exceptions.WorksheetNotFound:
|
||||
contacts_sheet = sh.add_worksheet(title="Contacts", rows="1000", cols="10")
|
||||
header = ["Firmenname", "Website", "Vorname", "Nachname", "Position", "Anrede", "E-Mail"]
|
||||
contacts_sheet.update("A1:G1", [header])
|
||||
debug_print("Neues Blatt 'Contacts' erstellt und Header eingetragen.")
|
||||
main_sheet = sh.sheet1
|
||||
data = main_sheet.get_all_values()
|
||||
positions = ["Serviceleiter", "IT-Leiter", "Leiter After Sales", "Leiter Einsatzplanung"]
|
||||
new_rows = []
|
||||
for idx, row in enumerate(data[1:], start=2):
|
||||
company_name = row[1] if len(row) > 1 else ""
|
||||
website = row[2] if len(row) > 2 else ""
|
||||
debug_print(f"Verarbeite Firma: '{company_name}' (Zeile {idx}), Website: '{website}'")
|
||||
if not company_name or not website:
|
||||
debug_print("Überspringe, da Firmenname oder Website fehlt.")
|
||||
continue
|
||||
for pos in positions:
|
||||
debug_print(f"Suche nach Position: '{pos}' bei '{company_name}'")
|
||||
contact = search_linkedin_contact(company_name, website, pos)
|
||||
if contact:
|
||||
debug_print(f"Kontakt gefunden: {contact}")
|
||||
new_rows.append([contact["Firmenname"], contact["Website"], contact["Vorname"], contact["Nachname"], contact["Position"], "", ""])
|
||||
else:
|
||||
debug_print(f"Kein Kontakt für Position '{pos}' bei '{company_name}' gefunden.")
|
||||
if new_rows:
|
||||
last_row = len(contacts_sheet.get_all_values()) + 1
|
||||
range_str = f"A{last_row}:G{last_row + len(new_rows) - 1}"
|
||||
contacts_sheet.update(range_str, new_rows)
|
||||
debug_print(f"{len(new_rows)} Kontakte in 'Contacts' hinzugefügt.")
|
||||
else:
|
||||
debug_print("Keine Kontakte gefunden in der Haupttabelle.")
|
||||
|
||||
# ==================== NEUE FUNKTION: NUR WIKIPEDIA-SUCHE (MODUS 4) ====================
|
||||
def process_wikipedia_only():
|
||||
debug_print("Starte ausschließlich Wikipedia-Suche (Modus 4)...")
|
||||
gc = gspread.authorize(ServiceAccountCredentials.from_json_keyfile_name(
|
||||
Config.CREDENTIALS_FILE, ["https://www.googleapis.com/auth/spreadsheets"]))
|
||||
sh = gc.open_by_url(Config.SHEET_URL)
|
||||
main_sheet = sh.sheet1
|
||||
data = main_sheet.get_all_values()
|
||||
start_index = GoogleSheetHandler().get_start_index()
|
||||
debug_print(f"Starte bei Zeile {start_index+1}")
|
||||
for i, row in enumerate(data[1:], start=2):
|
||||
if i < start_index:
|
||||
continue
|
||||
company_name = row[1] if len(row) > 1 else ""
|
||||
website = row[2] if len(row) > 2 else ""
|
||||
debug_print(f"Verarbeite Zeile {i}: {company_name}")
|
||||
article = WikipediaScraper().search_company_article(company_name, website)
|
||||
if article:
|
||||
company_data = WikipediaScraper().extract_company_data(article.url)
|
||||
else:
|
||||
company_data = {
|
||||
'url': 'k.A.',
|
||||
'first_paragraph': 'k.A.',
|
||||
'branche': 'k.A.',
|
||||
'umsatz': 'k.A.',
|
||||
'mitarbeiter': 'k.A.',
|
||||
'categories': 'k.A.',
|
||||
'full_infobox': 'k.A.'
|
||||
}
|
||||
wiki_values = [
|
||||
row[10] if len(row) > 10 and row[10].strip() not in ["", "k.A."] else "k.A.",
|
||||
company_data.get('url', 'k.A.'),
|
||||
company_data.get('first_paragraph', 'k.A.'),
|
||||
company_data.get('branche', 'k.A.'),
|
||||
company_data.get('umsatz', 'k.A.'),
|
||||
company_data.get('mitarbeiter', 'k.A.'),
|
||||
company_data.get('categories', 'k.A.')
|
||||
]
|
||||
wiki_range = f"K{i}:Q{i}"
|
||||
main_sheet.update(values=[wiki_values], range_name=wiki_range)
|
||||
debug_print(f"Zeile {i} mit Wikipedia-Daten aktualisiert.")
|
||||
current_dt = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
main_sheet.update(values=[[current_dt]], range_name=f"AH{i}")
|
||||
main_sheet.update(values=[[Config.VERSION]], range_name=f"AI{i}")
|
||||
time.sleep(Config.RETRY_DELAY)
|
||||
debug_print("Wikipedia-Suche abgeschlossen.")
|
||||
|
||||
# ==================== GOOGLE SHEET HANDLER (für Hauptdaten) ====================
|
||||
class GoogleSheetHandler:
|
||||
def __init__(self):
|
||||
self.sheet = None
|
||||
@@ -374,57 +522,9 @@ def alignment_demo(sheet):
|
||||
sheet.update(values=[new_headers], range_name=header_range)
|
||||
print("Alignment-Demo abgeschlossen: Neue Spaltenüberschriften in Zeile 11200 geschrieben.")
|
||||
|
||||
# ==================== NEUER MODUS 4: NUR WIKIPEDIA-SUCHE ====================
|
||||
def process_wikipedia_only():
|
||||
debug_print("Starte ausschließlich Wikipedia-Suche (Modus 4)...")
|
||||
gc = gspread.authorize(ServiceAccountCredentials.from_json_keyfile_name(
|
||||
Config.CREDENTIALS_FILE, ["https://www.googleapis.com/auth/spreadsheets"]))
|
||||
sh = gc.open_by_url(Config.SHEET_URL)
|
||||
main_sheet = sh.sheet1
|
||||
data = main_sheet.get_all_values()
|
||||
# Wir gehen von der ersten Zeile ohne Timestamp in Spalte AH aus:
|
||||
start_index = GoogleSheetHandler().get_start_index()
|
||||
debug_print(f"Starte bei Zeile {start_index+1}")
|
||||
for i, row in enumerate(data[1:], start=2):
|
||||
if i < start_index:
|
||||
continue
|
||||
company_name = row[1] if len(row) > 1 else ""
|
||||
website = row[2] if len(row) > 2 else ""
|
||||
debug_print(f"Verarbeite Zeile {i}: {company_name}")
|
||||
article = WikipediaScraper().search_company_article(company_name, website)
|
||||
if article:
|
||||
company_data = WikipediaScraper().extract_company_data(article.url)
|
||||
else:
|
||||
company_data = {
|
||||
'url': 'k.A.',
|
||||
'first_paragraph': 'k.A.',
|
||||
'branche': 'k.A.',
|
||||
'umsatz': 'k.A.',
|
||||
'mitarbeiter': 'k.A.',
|
||||
'categories': 'k.A.',
|
||||
'full_infobox': 'k.A.'
|
||||
}
|
||||
wiki_values = [
|
||||
row[10] if len(row) > 10 and row[10].strip() not in ["", "k.A."] else "k.A.",
|
||||
company_data.get('url', 'k.A.'),
|
||||
company_data.get('first_paragraph', 'k.A.'),
|
||||
company_data.get('branche', 'k.A.'),
|
||||
company_data.get('umsatz', 'k.A.'),
|
||||
company_data.get('mitarbeiter', 'k.A.'),
|
||||
company_data.get('categories', 'k.A.')
|
||||
]
|
||||
wiki_range = f"K{i}:Q{i}"
|
||||
main_sheet.update(values=[wiki_values], range_name=wiki_range)
|
||||
debug_print(f"Zeile {i} mit Wikipedia-Daten aktualisiert.")
|
||||
current_dt = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
main_sheet.update(values=[[current_dt]], range_name=f"AH{i}")
|
||||
main_sheet.update(values=[[Config.VERSION]], range_name=f"AI{i}")
|
||||
time.sleep(Config.RETRY_DELAY)
|
||||
debug_print("Wikipedia-Suche abgeschlossen.")
|
||||
|
||||
# ==================== MAIN PROGRAMM ====================
|
||||
if __name__ == "__main__":
|
||||
print("Modi: 1 = regulärer Modus, 2 = Re-Evaluierungsmodus, 3 = Alignment-Demo, 4 = Nur Wikipedia-Suche")
|
||||
print("Modi: 1 = regulärer Modus, 2 = Re-Evaluierungsmodus, 3 = Alignment-Demo, 4 = Nur Wikipedia-Suche, 5 = LinkedIn Contacts")
|
||||
mode_input = input("Wählen Sie den Modus: ").strip()
|
||||
if mode_input == "2":
|
||||
MODE = "2"
|
||||
@@ -432,6 +532,8 @@ if __name__ == "__main__":
|
||||
MODE = "3"
|
||||
elif mode_input == "4":
|
||||
MODE = "4"
|
||||
elif mode_input == "5":
|
||||
MODE = "5"
|
||||
else:
|
||||
MODE = "1"
|
||||
if MODE == "1":
|
||||
@@ -447,4 +549,6 @@ if __name__ == "__main__":
|
||||
processor.process_rows()
|
||||
elif MODE == "4":
|
||||
process_wikipedia_only()
|
||||
elif MODE == "5":
|
||||
process_contacts()
|
||||
print(f"\n✅ Auswertung abgeschlossen ({Config.VERSION})")
|
||||
|
||||
Reference in New Issue
Block a user